#!/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);

# open files to write graphs to
#
open(BESTHITS, ">/tmp/besthits.xgraph") ||
  die "Couldn't save graph info to /tmp/besthits.xgraph\n";
print BESTHITS "TitleText: Best Hits\n";
open(AVGHITS, ">/tmp/avghits.xgraph") ||
  die "Couldn't save graph info to /tmp/avghits.xgraph\n";
print AVGHITS "TitleText: Average Hits\n";
open(BESTSTD, ">/tmp/beststd.xgraph") ||
  die "Couldn't save graph info to /tmp/beststd.xgraph\n";
print BESTSTD "TitleText: Best Standardized Fitness\n";
open(AVGSTD, ">/tmp/avgstd.xgraph") ||
  die "Couldn't save graph info to /tmp/avgstd.xgraph\n";
print AVGSTD "TitleText: Average Standardized Fitness\n";

# read all the files
#
$maxgen = 0;
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 graph should be named
  #
  if ($file =~ /.*\.([^.]*$)/) {
    $name = $1;
  } else {
    $name = $file;
  }
  while (<DATA>) {
    if (/([ 0-9]*): Seed=[0-9.]*, Last=[0-9]*, Best=[0-9]*, Time=[0-9.]*/) {
      $run = $1;

      print BESTHITS "\"$run\"\n";
      for ($i = 0; $i < @besthits; $i++) {
	print BESTHITS "$i $besthits[$i]\n";
      }
      print BESTHITS "\n";
      @besthits = ();

      print AVGHITS "\"$run\"\n";
      for ($i = 0; $i < @avghits; $i++) {
	print AVGHITS "$i $avghits[$i]\n";
      }
      print AVGHITS "\n";
      @avghits = ();

      print BESTSTD "\"$run\"\n";
      for ($i = 0; $i < @beststd; $i++) {
	print BESTSTD "$i $beststd[$i]\n";
      }
      print BESTSTD "\n";
      @beststd = ();

      print AVGSTD "\"$run\"\n";
      for ($i = 0; $i < @avgstd; $i++) {
	print AVGSTD "$i $avgstd[$i]\n";
      }
      print AVGSTD "\n";
      @avgstd = ();

    } elsif (/^\s+([0-9]+): H\[([0-9]+), ([0-9]+)\] S\[([0-9\-\.]+), ([0-9\-\.]+)\]/) {
      $besthits[$1] = $2;
      $avghits[$1] = $3;
      $beststd[$1] = $4;
      $avgstd[$1] = $5;
    } else {
      print STDERR "Mismatch '$_'"
	if (! /^Initial seed = /);
    }
  }
  close(DATA);
}

close(BESTHITS);
&background('(xgraph /tmp/besthits.xgraph; rm -f /tmp/besthits.xgraph)');
close(AVGHITS);
&background('(xgraph /tmp/avghits.xgraph; rm -f /tmp/avghits.xgraph)');
close(BESTSTD);
&background('(xgraph /tmp/beststd.xgraph; rm -f /tmp/beststd.xgraph)');
close(AVGSTD);
&background('(xgraph /tmp/avgstd.xgraph; rm -f /tmp/avgstd.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";
  }
}
