#!/usr/bin/perl -w
use strict;
use Tk;
# arg 1 gives a Symaxx/2 temporary directory.
$::TempDir=$ARGV[0]; die unless defined $::TempDir;
$::MaximaPID=$ARGV[1]; die unless defined $::MaximaPID;
my $M=MainWindow->new;	
$M->geometry('200x100');
my $EvalSuccess='[]';
$M->Button(-text=>'Stop Maxima',-command => sub{ &Error('ABORT');},-width=>20)->pack(-side => 'top',-fill => 'both',-expand => 1); 
$M->Label(-textvariable => \$EvalSuccess)->pack(-side => 'top',-fill => 'both',-expand => 1);
&NewCheck; 
$M->repeat(500,\&NewCheck);
#$SIG{'INT'}=sub {exit;}; # User presses CTRL-C - watchdog gets killed, too.
$SIG{'INT'}='IGNORE'; # sub {exit;}; # User presses CTRL-C - watchdog gets killed, too.
# has to be set, because it inherits IGNORE.
MainLoop;
sub NewCheck{
#    print "New check\n";
    open M, "<$::TempDir/MaximaLog" or return;
    my @Log=<M>;
    close M;
    my $Error; my $Message='';
    # Maxima goes into interactive mode?.
    if((join('[NL]',@Log).'NL')=~/\?\s*\[NL\]/){ # check for ?[NL]
	&Error('INTERACTIVE',\@Log);
    };
    $EvalSuccess='[';
    my $Line; foreach $Line(@Log){
#	print $Line;
	chop $Line;
	if ($Line=~/Evaluation of ID (\d+) succeeded\./){
	    $EvalSuccess.="$1 ";
	};
    };
    $EvalSuccess.=']';
};
sub Error{
    my $ErrCode=shift or die;
    my $Log=shift; 
    my $Message='';
    if ($ErrCode eq 'INTERACTIVE'){
	$Message="Maxima tries something interactive.\nPlease use an ASSUME-statement to answer the question in advance.\n";
    } elsif ($ErrCode eq 'USERABORT'){
	$Message="User aborted.";
    };
    if ($Log){$Message.=join('',@{$Log});};
    open M, ">$::TempDir/WatchdogLog";
    print M "***Watchdog reports: $ErrCode***\n$Message\n";
    close M;
    my $GroupID=getpgrp($::MaximaPID);
    kill -2,$GroupID; # this also kills the watchdog
    sleep(1);
    kill 9,$::MaximaPID;
    exit;
};
