#!/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 . ']++;';
      $total{$array}++;
      eval $cmd;
      $timetot[$last] += $time;
      $timecnt[$last]++;
    } else {
      print STDERR "Mismatch '$_'" if (! /^Initial seed = /);
    }
  }
  close(DATA);
}

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";
  for ($i = 0; $i < 49; $i++) {
    $cmd = '$tmpval = ($' . $array . '[' . $i . '] / ' . $total{$array} . ') * 100;';
    eval $cmd;
    print GRAPH "$i $tmpval\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: Time to finish 1 generation\n";
foreach $array (@arraylist) {

  for ($i = 0; $i < 49; $i++) {
    if ($i > 0 && $timecnt[$i] > 0) {
      $genavg = $timetot[$i]/$timecnt[$i];
      $genavg /= $i;
      print GRAPH "$i $genavg\n";
    }
  }
  print GRAPH "\n";
}
close(GRAPH);
&background('(xgraph /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";
  }
}
