#!/usr/sww/bin/perl

# die if they didn't give us work to do
#
die "Please enter a list of files (or extensions) to report on!\n"
  if (@ARGV == 0);

# read all the files
#
for ($i = 0; $i < @ARGV; $i++) {

  # try to open the file
  #
  $file = $ARGV[$i];
  if (!open(DATA, $file)) {
    if (!open(DATA, 'longrun.'.$file)) {
      print STDERR "Couldn't read data file $file!\n";
      next;
    }

    # they only specified the extension
    #
    $file = 'longrun.'.$file;
  }

  # figure out what the array should be called
  #
  $file =~ /.*\.([^.]*$)/;
  $array = $1;
  push(@arraylist, $array);

  while (<DATA>) {
    if (/[ 0-9]*: Seed=[0-9.]*, Last=([0-9]*), Best=[0-9]*, Time=([0-9.]*)/) {
      ($last,$time) = ($1,$2);
      $cmd = '$' . $array . "[$last]++;";
      eval $cmd;
      $cmd = '$' . $array . "tot[$last] += $time;";
      eval $cmd;
      $cmd = '$' . $array . "cnt[$last]++;";
      eval $cmd;
      $maxgen = $last if ($maxgen < $last);
    } else {
      print STDERR "Mismatch '$_'"
	if (! /^Initial seed = / && !/^\s+[0-9]+: H\[.*\] S\[.*\]/);
    }
  }
  close(DATA);
}

foreach $array (@arraylist) {
  for ($i = 0; $i <= $maxgen; $i++) {
    $cmd = '$' . $array . "[$i] += 0;";
    eval $cmd;
    $cmd = '$total{"' . $array . '"} += $' . $array . "[$i];";
    eval $cmd;
  }
}

open(GRAPH, ">/tmp/run.xgraph") || die "Couldn't save longrun info!\n";
# open(GRAPH, ">-") || die "Couldn't write to STDOUT!\n";
print GRAPH "TitleText: % of runs completed\n";
foreach $array (@arraylist) {

  print GRAPH "\"$array\"\n";
  $sum = 0;
  for ($i = 0; $i <= $maxgen; $i++) {
    $cmd = '$sum += ($' . $array . '[' . $i . '] / ' . $total{$array} . ') * 100;';
    eval $cmd;
    print GRAPH "$i $sum\n";
  }
  print GRAPH "\n";
}
close(GRAPH);
&background('(xgraph /tmp/run.xgraph; rm -f /tmp/run.xgraph)');

open(GRAPH, ">/tmp/gentime.xgraph") || die "Couldn't save generation times!\n";
# open(GRAPH, ">-") || die "Couldn't write to STDOUT!\n";
print GRAPH "TitleText: Average time per generation\n";
$discontinuous = 0;
foreach $array (@arraylist) {

  print GRAPH "\"$array\"\n";
  for ($i = 0; $i <= $maxgen; $i++) {
    $cmd = '$flag = $' . $array . 'cnt[$i] > 0;';
    eval $cmd;
    if ($flag) {
      $cmd = '$genavg = $' . $array . 'tot[$i]/$' . $array . 'cnt[$i];';
      eval $cmd;
      $genavg /= ($i + 1);
      if ($discontinuous) {
	print GRAPH "move $i $genavg\n";
	$discontinuous = 0;
      }
      print GRAPH "$i $genavg\n";
    } else {
      $discontinuous = 1;
    }

  }
  print GRAPH "\n";
}
close(GRAPH);
&background('(xgraph -P /tmp/gentime.xgraph; rm -f /tmp/gentime.xgraph)');

exit 0;

sub background {
  local($cmd) = @_;

  if (fork) {

    # parent waits to give daemon a chance to start
    #
    sleep(3);
  } else {

    # start subprocess
    #
    exec $cmd || die "Cant start subprocess '$cmd'!\n";
  }
}
