#!/usr/bin/perl
#
# chkres.pl
#    uses fmark.dat
#
# checks the result log files of bench.sh
#
# 2002/8/23,24
#

# print "$#ARGV\n";
$DEBUG = 0 ;

$ref = "chkres.dat";
if (! -e $ref) {$ref = "../$ref";}
if (! -e $ref) { print STDERR "$res must be in the current or the parent directory.\n"; die;}
# $n = `cat $ref|wc -l`; chomp($n);

open(FL,$ref);
while($bb=<FL>){
  if ($bb =~ /^([A-Za-z0-9]+):/){
     $program = $1;
     push (@programs,$program);
  }
}
close(FL);
$n = $#programs + 1;

if($iprint >=0){printf(" #programs = %d\n",$n);}

$iprint = 1; # print level
$nerr = 0; $nfile = 0;

for($iarg=0;$iarg <= $#ARGV;$iarg++) {
$fli = $ARGV[$iarg];

if ($fli eq "-h" || $fli eq "--help") {
  print <<EOD;
chkres.pl: version 2002/8/24 (y/m/d)
usage:
  chkres.pl (options and input files)
options:
  -help    : show this message
Output format is either detailed or concise:
  -detail  : detailed output for each input file (default)
  -oneline : one-line output for each input file
EOD
  next;
}

if ( $fli eq "-detail" ) { $iprint = 9 ; next; }
if ( $fli eq "-oneline") { $iprint = 0 ; next; }

$nfile++;
unless(open(FLI,$fli)) {
  print(STDERR "$fli cannot be opened.\n");
  $nerr++;
  next;
}

$program = ""; $result = "";
while ($b = <FLI>){
  if($b =~ /^ {0,2}-{70,} *$/){
    if($iprint>=1){print($b);}
    $program = ""; $result = "";
  }
  if($program eq ""){
    if($b =~ /^ {0,2}\(\d{1,3}\) program = +([A-Za-z0-9]+)\.f/){
      $program = $1;
      if($iprint >= 1) {printf(" Program = %s\n",$program);}
      open(FL,$ref);
      while($bb=<FL>){
        if($bb =~ /^${program}:(.+)$/){ $result = $1;}
      }
      close(FL);
      if($result eq "") { print STDERR "$ref does not include data for $program.\n"; die;}
      if($DEBUG) {printf("Ref=%s\n",$result);}
    }
  }
  else {
    if(index($b,$result) >= 0) { 
      $check{$program} = "OK";
      if($iprint >= 1) {print($b);}
    }
  }
}
close(FLI);

$cr = 0; $icr=0;
foreach $program (@programs){
  if ($check{$program} eq "OK"){
    $cr++;
    if($iprint >= 1){printf(" %12s : correct result\n",$program);}
  }
  else {
    $icr++;
    if($iprint >= 1){printf(" %12s : INCORRECT result \n",$program);}
 }
}

if ($icr != 0) {
  if($iprint>=0){printf(" Summary : check ** NG ** for $fli\n");}
  $nerr ++;
}
else {
  if($iprint>=0){printf(" Summary : check    OK    for $fli\n");}
}

} # end of the for-loop for $iarg

if($nfile>1){
  print(" $nerr errors in $nfile files\n");
}

exit($nerr);
