#!/usr/bin/env perl

use XyceRegression::Tools;

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

# The input arguments to this script are set up in 
# Xyce_Test/TestScripts/tsc_run_test_suite and are as follows:
# $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 also, it is responsible for capturing any
# error output from Xyce.  The script run_xyce_regression captures the test
# output and handles the resulting files.  

$XYCE=$ARGV[0];

$XYCE_VERIFY=$ARGV[1];
# need to use the AC comparator, because the normal one doesn't understand what 
# variables to expect in a *.SENS.prn file.
$XYCE_VERIFY=~ s/xyce_verify/ACComparator/;

$CIR1="diode_direct.cir";
$CIR2="diode_adjoint.cir";

`rm -f $CIR1.SENS.prn`;
$retval=$Tools->wrapXyce($XYCE,$CIR1);
if ($retval != 0) { print "Exit code = $retval\n"; exit $retval; }

`rm -f $CIR2.SENS.prn`;
$retval=$Tools->wrapXyce($XYCE,$CIR2);
if ($retval != 0) { print "Exit code = $retval\n"; exit $retval; }

if ( not -s "$CIR1.SENS.prn" ) 
{ 
  print STDERR "$CIR1.SENS.prn not found\n";
  print "Exit code = 14\n"; 
  exit 14; 
}
`grep -v "Index" $CIR1.SENS.prn | grep -v "End" > $CIR1.SENS.prn2`;

if ( not -s "$CIR2.SENS.prn" ) 
{
  print STDERR "$CIR2.SENS.prn not found\n";
  print "Exit code = 14\n";
  exit 14;
}

`grep -v "Index" $CIR2.SENS.prn | grep -v "End" > $CIR2.SENS.prn2`;

$retval = system("diff $CIR1.SENS.prn2 $CIR2.SENS.prn2 > $CIR1.SENS.prn.out 2> $CIR1.SENS.prn.err");
if ($retval == 0) 
{
  print "Exit code = 0\n";
  exit 0;
}
else
{
   $CMD = "$XYCE_VERIFY $CIR1.SENS.prn $CIR2.SENS.prn >> $CIR1.SENS.prn.out 2>> $CIR1.SENS.prn.err";
   print STDERR "diff failed $CIR1.SENS.prn $CIR2.SENS.prn\nRunning $CMD\n";
   if ( system("$CMD") != 0 )
   {
     print STDERR "Verify failed\n";
     print "Exit code = 2\n"; 
     exit 2;
   }
   else
   {
      print "Exit code = 0\n";
      exit 0;
   }
}
