#! /usr/bin/perl 
# rms <f1> <f2>
#  compares two splot files <f1> and <f2>, presuming that <f1>
#  is the more accurate, and computes the root-mean-square relative
#  error between them

$f1 = $ARGV[0];
$f2 = $ARGV[1];
open(F1, "<$f1") or die "Can't find $f1";
open(F2, "<$f2") or die "Can't find $f2";
$sumsqs = 0;
$stsumsqs = 0;
$sum = 0;
$stsum = 0;
$cnt = 0;
L: 
while ($in1 = <F1>) { #read first to EOF
  @rec = split(" ",$in1);
  if ($in2 = <F2>) {
    @sec = split(" ",$in2);
    die "File inputs don't match" unless ($rec[0]==$sec[0]);
    $sum += $rec[2];
    $stsum += $rec[1];
    $sumsqs += ($rec[2] - $sec[2])**2;
    $stsumsqs += ($rec[1] - $sec[1])**2;
  } else {
    warn "$f2 ended before $f1, continuing anyway";
    next L;
  }
$cnt++;  
}
#see if extra records in second
if ($in2 = <F2>) {
  warn "Extra records in $f2, ignored";
}
die "$f1 is empty!" if ($cnt == 0);
$ave = $sum/$cnt;
$stave = $stsum/$cnt;
$rms = sqrt($sumsqs/$cnt);
$strms = sqrt($stsumsqs/$cnt);
$rel = 100.0*$rms/(abs($ave)+.000000001);
$strel = 100.0*$strms/(abs($stave)+.000000001);
#print "Average: $ave, R-m-s: $rms ($rel%)\n";
printf "Ave: %4.2f, R-m-s: %4.2f (%3.1f%%)\n",$ave,$rms,$rel;
printf "State ave: %4.2f, State r-m-s: %4.2f (%3.1f%%)\n",$stave,$strms,$strel;

################################################
sub warn {
print STDERR "$_[0]\n";
return;
}
