#!/bin/sh

# Compare wrapper-script to be called from 'testcase_run.sh'.
#
# Usage: $0 <testdata.in> <program.out> <testdata.out> <result.out> <diff.out>
#
# <testdata.in>   File containing testdata input.
# <program.out>   File containing the program output.
# <testdata.out>  File containing the correct output.
# <result.out>    File describing the judging verdict.
# <diff.out>      File to write program/correct output differences to (optional).
#
#
# Exits successfully except when an internal error occurs. Submitted
# program output is considered correct when diff.out is empty (and
# specified).
#
# This script calls another program to check the results.
# Calling syntax:
#
#    $CHECK_PROGRAM <testdata.in> <program.out> <testdata.out>
#
# The $CHECK_PROGRAM should return the contents of <diff.out> to
# standard output. It must exit with exitcode zero to indicate
# successful checking.

SCRIPT=$(readlink -f "$0")
SCRIPTPATH=$(dirname "$SCRIPT")
CHECK_PROGRAM="${SCRIPTPATH}/check_float"

# Options to pass to check program:
CHECK_OPTIONS="--abs-prec=0.012"

TESTIN="$1"
PROGRAM="$2"
TESTOUT="$3"
RESULT="$4"
DIFFOUT="${5:-/dev/null}"

writeresult()
{
    ( cat <<EOF
result=$1
EOF
    ) > "$RESULT"
}

if [ ! -x "$CHECK_PROGRAM" ]; then
	echo "Error: '$CHECK_PROGRAM' not found or executable." >&2
	writeresult "Internal error"
	exit 1
fi

# Run the program:
"$CHECK_PROGRAM" $CHECK_OPTIONS "$TESTIN" "$PROGRAM" "$TESTOUT" > "$DIFFOUT"
EXITCODE=$?

# Exit with failure, when non-zero exitcode found:
if [ $EXITCODE -ne 0 ]; then
	echo "Error: '$CHECK_PROGRAM' exited with exitcode $EXITCODE." >&2
	writeresult "Internal error"
	exit 1
fi

# Check result and write result file:
if [ -s "$DIFFOUT" ]; then
	writeresult "Wrong answer"
else
	writeresult "Accepted"
fi

exit 0
