#!/usr/local/bin/perl5
#
# Usage: gram_process_log_file <logfile>
#
# Process a logile generated by gram_client_multi_test,
# generating a set of ".dat" files a a "multi.gplot" file.
# Run "gnuplot multi.gplot" to get an plot of GRAM activity.
#

if ($#ARGV != 0) {
    print "Usage: gram_process_log_file <logfile>\n";
    exit 1;
}

$infile   = $ARGV[0];
$gplotfile = "multi.gplot";

%grams = ();
%locns = ();
%times = ();
%ofiles = ();

$n = 0;
$filecount = 0;

$q = '"';
$b = '\\';

open(FILE,$infile);
while (<FILE>) {
   ($type,$number,$x1,$gram,$x2,$time) = split(' ',$_);
   $n++;
   if($type eq "Start") {
      if($n == 1) {
         $starttime = $time;
      }
      $locns{$number} = $gram;
      $times{$number} = $time;
   }
   else {
     if($gram ne $locns{$number}) { die "names don't match\n"; }
     ($x1,$x2,$temp) = split('/',$gram);
     ($gname,$x3) = split(':',$temp);
     $grams{$gname}++;
     if($grams{$gname} == 1) {
        $outfile[$filecount] = sprintf("%s.dat",$gname);
        $outfile_fh[$filecount] = "\*FILE$filecount";
        open($outfile_fh[$filecount], "> $outfile[$filecount]") or die "can't open $outfile[$filecount]\n";
        $ofiles{$gname} = $filecount;
	$filecount++;
     }
     printf "$gname: $grams{$gname} tasks @ %d secs\n", $time - $starttime;
     printf {$outfile_fh[$ofiles{$gname}]} "%d %d\n",$time-$starttime,$grams{$gname};
   }
};
close(FILE);

for($i=0; $i<$filecount; $i++) {
     close($outfile_fh[$i]);
}

#------------------------------------------------------------------------------------
#
# Stage 2: Write gplot file
#
#------------------------------------------------------------------------------------

if($filecount == 0) {die "No data files created\n"; }

open(OFILE, "> $gplotfile") or die "can't open $gplotfile\n";

printf OFILE "set term postscript color ${q}Times-Roman${q} 18\n";

printf OFILE "set title  ${q}Activities of GUSTO Testbed${q}\n";

#set term ppm small

printf OFILE "set ylabel ${q}Cumulative number of tasks${q}\n";
printf OFILE "set xlabel ${q}Seconds${q}\n";

#set key 480,4500000

#printf OFILE "set yrange [0:80]\n";

printf OFILE "set output ${q}multi.eps${q}\n";

printf OFILE "plot ${b}\n";
printf OFILE "  ${q}${outfile[1]}${q} t ${q}${outfile[1]}${q} with linespoints";

for($i=1; $i<$filecount; $i++) {
   printf OFILE ",${b}\n  ${q}${outfile[$i]}${q} t ${q}${outfile[$i]}${q} with linespoints";
}

printf OFILE "\n";

system("gnuplot multi.gplot");
