#! /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]**2;
    $stsum += $rec[1]**2;
    $sumsqs += ($rec[2] - $sec[2])**2;
    $stsumsqs += ($rec[1] - $sec[1])**2;
  } else {
    die "$f2 ended before $f1";
  }
$cnt++;  
}
#see if extra records in second
if ($in2 = <F2>) {
  warn "Extra records in $f2, ignored";
}
die "$f1 is empty!" if ($cnt == 0);
$ave = sqrt($sum/$cnt);
$stave = sqrt($stsum/$cnt);
$rms = sqrt($sumsqs/$cnt);
$strms = sqrt($stsumsqs/$cnt);
$rel = 100.0*$rms/($ave+.000000001);
$strel = 100.0*$strms/($stave+.000000001);
printf "r-m-s out: %4.2f, r-m-s error: %4.2f (%3.1f%%)\n",$ave,$rms,$rel;
printf "r-m-s state: %4.2f, r-m-s error: %4.2f (%3.1f%%)\n",$stave,$strms,$strel;

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