#!/usr/bin/env perl

use XyceRegression::Tools;

$Tools = XyceRegression::Tools->new();

# 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 txt file

# If Xyce does not produce the appropriate output files, then we return exit code 14.
# 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.

# 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.txt.out and the STDERR output from
# comparison to go into $CIRFILE.txt.err.

$XYCE=$ARGV[0];
$XYCE_VERIFY=$ARGV[1];
$XYCE_COMPARE=$ARGV[2];
$CIRFILE=$ARGV[3];
$GOLDTXT=$ARGV[4];

$GOLDTXT =~ s/\.prn$//; # remove the .prn at the end.

system("rm -f $CIRFILE.txt $CIRFILE.err");

$CMD="$XYCE -namesfile $CIRFILE.txt $CIRFILE > $CIRFILE.out 2>$CIRFILE.err";

$retcode = 0;
$xyceexit = system($CMD);
if ($xyceexit != 0) {
    $retcode = 2;
}

if ($retcode != 0) {print "Exit code = $retcode\n"; exit $retcode;}

if ( !(-f "$CIRFILE.txt")) {
    print STDERR "Missing output file $CIRFILE.txt\n";
    $retcode=14;
}

if ($retcode != 0) {print "Exit code = $retcode\n"; exit $retcode;}

#If this is a VALGRIND run, we don't do our normal verification, we
# merely run "valgrind_check.sh" as if it were xyce_verify.pl

if ($XYCE_VERIFY =~ m/valgrind_check/)
{
    print STDERR "DOING VALGRIND RUN INSTEAD OF REAL RUN!";
    if (system("diff $CIRFILE.txt $GOLDTXT.txt > $CIRFILE.txt.out 2> $CIRFILE.txt.err"))
    {
        print "Exit code = 2 \n";
        exit 2;
    }
    else
    {
        print "Exit code = 0 \n";
        exit 0;
    }
}

$CMD="diff -bw $CIRFILE.txt $GOLDTXT.txt > $CIRFILE.txt.out 2> $CIRFILE.txt.err";
print "$CMD\n";
if (system("$CMD") != 0) {
    print STDERR "Verification failed on file $CIRFILE.txt, see $CIRFILE.txt.FD.err\n";
    $retcode = 2;
}

print "Exit code = $retcode\n"; exit $retcode;
