#
# (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
#
# Perl script expect bindings for the following variables to be prepended
#
#   DEFAULT_TMPDIR libdir
#
# without them, not much success :-(
#

$debug = 0; # first line of script, builds confidence :-)
$outsuffix = ".resid.ps";	# change as appropriate

if ( $ENV{'TMPDIR'} ) { # where to make tmp file names
    $tmpfile = $ENV{'TMPDIR'} . "/$$.resid.data";
} else {
    $tmpfile ="${DEFAULT_TMPDIR}/$$.resid.data";
    $ENV{'TMPDIR'} = ${DEFAULT_TMPDIR}; # set the env var as well
}

@INC = ( ${libdir} );

require('parse-gcstats.prl')   || die "Can't load parse-gcstats.prl!\n";
require('process-gcstats.prl') || die "Can't load process-gcstats.prl!\n";

if ($#ARGV < 0) {
    $infile = "-";
    $outfile = "";				# gnuplot: set output
} elsif ($#ARGV == 0) {
    $infile = $ARGV[0];
    if ($infile =~ /^(.*)\.stat$/) {
	$base = $1;
    } else {
        $base = $infile;
	$infile  = "$base.stat";
    };
    $outfile = "\"$base$outsuffix\"";	        # gnuplot: set output "outfile"
} elsif ($#ARGV == 1) {
    $infile = $ARGV[0];
    $outfile = "\"$ARGV[1]\"";
} else {
    die "Usage: command [infile[.stat] [outfile]]";
};   

%gcstats = &parse_stats($infile);

&print_stats(">&STDERR", %gcstats) if $debug;

if ($gcstats{"collector"} eq "APPEL") {
    die "APPEL stats: no residency plot possible\n";
}

#
# stats are now loaded into %gcstats -- write out info
#

open(DATAFILE, ">$tmpfile") || die "Cant open >$tmpfile \n";
$i = -1;
$user = 0;
printf DATAFILE "%4.2f %d\n", $user, 0;
while (++$i < $gcstats{"gc_no"}) {
   $user += $gcstats{"mut_user_$i"};
   printf DATAFILE "%4.2f %d\n", $user, $gcstats{"live_$i"}; 
}; 
printf DATAFILE "%4.2f %d\n", $gcstats{"mut_user_total"}, 0;
close(DATAFILE);

open(PLOTFILE, "|gnuplot") || die "Cant pipe into |gnuplot \n";
print PLOTFILE "set data style linespoints\n";
print PLOTFILE "set function style lines\n";
print PLOTFILE "set nokey\n";
print PLOTFILE "set xlabel \"Mutator Time (secs)\"\n";
print PLOTFILE "set ylabel \"Heap Residency (bytes)\" 0,-1\n";
print PLOTFILE "set term post eps \"Times-Roman\" 20\n";
printf PLOTFILE "set title \"%s %s  (%s)\"\n", $gcstats{"command"}, $gcstats{"args"}, $infile;
print PLOTFILE "set output $outfile\n" ;
print PLOTFILE "plot \"$tmpfile\"\n";
close(PLOTFILE);

unlink($tmpfile);
exit 0;
