#!/usr/bin/env perl

use XyceRegression::Tools;

$Tools = XyceRegression::Tools->new();
#$Tools->setDebug(1);
#$Tools->setVerbose(1);

if (defined($verbose)) { $Tools->setVerbose(1); }

# The input arguments to this script are: 
# $1 = location of Xyce binary
# $2 = location of xyce_verify.pl script
# $3 = location of compare script 
# $4 = location of circuit file to test
# $5 = location of gold standard prn file

# If Xyce does not produce a prn file, then we return exit code 10.
# If Xyce succeeds, but the test fails, then we return exit code 2.
# If the shell script fails for some reason, then we return exit code 1.
# Otherwise we return the exit code of compare or xyce_verify.pl

# Since the shell script runs Xyce and the comparison program, it is
# responsible for capturing any error output from Xyce and the STDOUT & STDERR
# from the comparison program.  The outside script, run_xyce_regression,
# expects the STDERR output from Xyce to go into $CIRFILE.err, the STDOUT
# output from comparison to go into $CIRFILE.prn.out and the STDERR output from
# comparison to go into $CIRFILE.prn.err.  

use Getopt::Long;
use File::Basename;

&GetOptions( "verbose!" => \$verbose );
$XYCE=$ARGV[0];
$XYCE_VERIFY=$ARGV[1];
#$XYCE_COMPARE=$ARGV[2];
$CIRFILE=$ARGV[3];
$GOLDPRN=$ARGV[4];

# Comparison tolerances
my $absTol=1e-5;
my $relTol=1e-3;
my $zeroTol=1e-10;

# create the output files
$retval=$Tools->wrapXyce($XYCE,$CIRFILE);

my $foundDataStart=0;

# file names
my $testFileName="$CIRFILE$idx.csd";
my $goldFileName="$CIRFILE$idx.GSfile";

if ( ! -e $testFileName)
{
  print "Failed to produce output file \n";
  print "Exit code = 14\n";
  exit 14;
}

# open files and check that the files have the same number of lines
if (not -s "$goldFileName" ) 
{ 
  print STDERR "Missing Gold Standard file: $goldFileName\nExit code = 2\n"; 
  $exitCode=2; 
  print "test Failed!\n";
  print "Exit code = $exitCode\n";
  exit $exitCode;
}

if (not -s "$testFileName" ) 
{ 
  print STDERR "Missing Test file: $testFileName\nExit code = 14\n"; 
  $exitCode=14; 
  print "test Failed!\n";
  print "Exit code = $exitCode\n";
  exit $exitCode;
}

# compare the test and gold file
$dirname = dirname($XYCE_VERIFY);
$fc = "$dirname/compare_csd_files.pl";

#print "$fc $CIRFILE.errmsg $GSFILE $absTol $relTol $zeroTol\n";
`$fc $testFileName $goldFileName $absTol $relTol $zeroTol > $CIRFILE.errmsg.out 2> $CIRFILE.errmsg.err`;
$exitCode=$? >> 8;


# check on return values
if ( $exitCode != 0 )
{
  print "test Failed!\n";
  print "Exit code = $exitCode\n";
  exit $exitCode;
}
else
{
  print "test passed!\n";
  print "Exit code = $exitCode\n";
  exit $exitCode;
}
