#!/usr/bin/perl -w

my $oldscores = $ARGV[0];
my $newscores = $ARGV[1];

if (!defined $newscores) {
  die "usage: rewrite-cf-with-new-scores oldscores.cf newscores.cf\n";
}

# read the skipped scores and their previous values
%skipped_scores = ();
my ($name, $base, $muta);
open (IN, "<tmp/scores.data");
while (<IN>) {
  chomp;
  /^n(.*)$/ and $name = $1;
  /^b(.*)$/ and $base = $1;
  /^m(.*)$/ and $muta = $1;

  if (/^\./ && defined($name)) {
    if ($muta == 0) { $skipped_scores{$name} = $base; }
  }
}
if ($muta == 0) { $skipped_scores{$name} = $base; }
close IN;

# now read the evolved scores
my $gascores = '';
open (STDIN, "<$newscores") or die "cannot open $newscores";
while (<STDIN>) {
  /^score\s+(\S+)\s/ or next;
  next if (defined $skipped_scores{$1});
  next if ($1 eq '(null)');	# er, oops ;)
  $gascores .= $_;
}

open (IN, "<$oldscores") or die "cannot open $oldscores";
my $out = '';
my $pre = '';

# read until '# Start of GA-evolved scores', removing scores from our
# new list if we come across them.
while (<IN>) {
  if (/^\s*score\s+(\S+)\s/) {
    delete $skipped_scores{$1};
    $gascores =~ s/^score\s+$1\s.*?\n//gm;
  }
  $pre .= $_;
  /^# Start of GA-evolved scores/ and last;
}

# now skip until '# End of GA-evolved scores'
while (<IN>) {
  /^# End of GA-evolved scores/ and last;
}
if (defined $_) {
  $out .= $_;
}

# and read until EOF, again removing score sfrom our list as we find 'em.
while (<IN>) {
  if (/^\s*score\s+(\S+)\s/) {
    delete $skipped_scores{$1};
    $gascores =~ s/^score\s+$1\s.*?\n//gm;
  }
  $out .= $_;
}
close IN;

# finally, make a string of the scores that were not in either list
my $missing = '';
foreach my $key (sort keys %skipped_scores) {
  $missing .= sprintf ("score %-30s %3.1f\n", $key, $skipped_scores{$key});
}
if ($missing ne '') { $missing = "# Missed scores:\n\n".$missing; }

print $pre, "\n", $gascores, "\n", $out, "\n", $missing;
