#!/bin/bash

# check-solitaire.sh
#
# Martin Brain
# mjb@cs.bath.ac.uk
# 20/03/09
#
# Checks the solution to a solitaire problem
#
# Marcello Balduccini
# marcello.balduccini@gmail.com
# Jan 10, 2011
# Modified to comply with the requirements of ASPCOMP2011.
#
# Marcello Balduccini
# marcello.balduccini@gmail.com
# Oct 2, 2012
# Modified to comply with the requirements of ASPCOMP2013.
#
# GB Ianni
# ianni@mat.unical.it
# Jun 20th, 2013
# Prevents checking INCONSISTENT answers by proving inconsistency again
#
EXEDIR="`dirname $0`"

if [ -z $GROUNDER ]; then
    GROUNDER=$EXEDIR/gringo
fi

if [ -z $SOLVER ]; then
    SOLVER=$EXEDIR/clasp
fi

REFERENCE_ENCODING=$EXEDIR/solitaire.lp
CHECK_SWITCH=$EXEDIR/check-switch.lp

INFILE=/tmp/check-in-$$

EXITCODE=$1
shift
INSTANCEFILE=$1
shift

read HEADER

if [ "$EXITCODE" != "0" -a "$HEADER" = "UNKNOWN" ]; then
	RES="FAIL"
else
	RES=""
	case "$EXITCODE" in
		10)
			echo $HEADER | cat $REFERENCE_ENCODING $CHECK_SWITCH $INSTANCEFILE - | $GROUNDER 2>/dev/null | $SOLVER 2>/dev/null | grep -q "^Answer: "
			if [ $? = 0 ]; then
			    RES="OK"
			else
			    RES="FAIL"
			fi
			;;
		20)
			if [ "$HEADER" != "INCONSISTENT" ]; then
				RES="FAIL"
			else
			        echo "DONTKNOW"
        			echo "Instances with no solution should not be checked with this checker" >&2
        			exit 2
			fi
			;;
		*)
			RES="FAIL"
			;;
	esac
fi

case "$RES" in
	"OK")
		echo "OK"
		exit 0
		;;
	"FAIL")
		echo "FAIL"
		exit 1
		;;
	"DONTKNOW")
		echo "DONTKNOW"
		exit 2
		;;
	"WARN"|*)
		echo "WARN"
		exit 3
		;;
esac
