#!/usr/exp/bin/perl -w
#
# civscore2gnuplot - prepare civscore.log files for use with gnuplot
#
# $Id: civscore2gnuplot,v 1.6 1999/10/18 22:11:38 hop Exp hop $

# usage: ( civscore2gnuplot /path/to/civscore.log; sleep 100) | gnuplot -

my $turns = 0;

while ($ARGV[0] =~ /^-./)
{
  my $arg = shift(@ARGV);
  if ($arg eq '-t|--turn')
  {
    $turns = 1;
  }
  else
  {
    die("Usage: $0 [--turn] civscore1.log [civscore2.log [...]]\n");
  }
}

my (%player,%quantity);

foreach $f (@ARGV)
{
  ($f eq '-' || (-f $f && -r $f)) && open(CIVSCORELOG,"$f")
    || die("cannot open civscore.log file '$f'\n");

  &scan(\%quantity);
  &scan(\%player);

  #print "players are ",join(',',keys %player),"\n";
  #print "quantities are ",join(',',keys %quantity),"\n";

  print "set auto\nset data style histeps\nset key left\n";
  for $q (keys %quantity)
  {
    my $x = $turns ? 0 : 3;  # determines whether x has turns or years
    print "plot ", join(',', map
	{"'$f' using $x:(\$1==$q?(\$2==$_?\$4:1/0):1/0) title '$quantity{$q} for $player{$_}'"}
	keys %player), "\n";
  }
}

sub scan
{
  my $hashref = shift(@_);

  while (<CIVSCORELOG>)
  {
    last if /^end/;
    chomp;
    my ($num,$val) = split;
    $hashref->{$num} = $val unless $num =~ /\D/;
  }
}
