#! /bin/bash
instance=$(readlink -f $2)
read answerRow

if [ "$answerRow" == "INCONSISTENT" ] && [ $1 != 20 ]; then
	echo FAIL
	echo MISMATCH OF SOLVER RETURN VALUE AND STANDARD INPUT >&2
	exit 1
fi
if [ "$answerRow" != "INCONSISTENT" ] && [ $1 == 20 ]; then
	echo FAIL
	echo MISMATCH OF SOLVER RETURN VALUE AND STANDARD INPUT >&2
	exit 1
fi
if [ "$answerRow" != "UNKNOWN" ] && [ $1 != 10 -a $1 != 20 -a $1 != 30 -a $1 != 11 ] ; then
	echo FAIL
	echo MISMATCH OF SOLVER RETURN VALUE AND STANDARD INPUT >&2
	exit 1
fi
if [ $1 == 20 ]; then
	echo DONTKNOW
        echo Instances with no solution should not be checked with this checker >&2
        exit 2
else
	if [ $1 != 10 -a $1 != 30 -a $1 != 11 ] ; then
		echo FAIL
	        exit 1
	else
		# Filter for output predicates valve/2, everything else will be ignored
		#echo "$answerRow" | grep -o -e 'valve([^,^)]\+,[^)^,]\+)\.' | ./clingo constraint.asp $2 -- >/dev/null 2>&1
		basedir=$(dirname $0)

		output_clingo=`echo "$answerRow" | cat $basedir/unexp_v.asp $instance - | $basedir/clingo -q -`
		exit_clingo=${PIPESTATUS[*]}
		if [ $exit_clingo == 20 ]; then
			echo FAIL
			echo Unexpected valve detected >&2
			exit 1
		fi

		output_clingo=`echo "$answerRow" | cat $basedir/too_many_v.asp $instance - | $basedir/clingo -q -`
		exit_clingo=${PIPESTATUS[*]}
		if [ $exit_clingo == 20 ]; then
			echo FAIL
			echo Too many valves >&2
			exit 1
		fi

		output_clingo=`echo "$answerRow" | cat $basedir/tank.asp $instance - | $basedir/clingo -q -`
		exit_clingo=${PIPESTATUS[*]}
		if [ $exit_clingo == 20 ]; then
			echo FAIL
			echo The net is not disconnected from tanks >&2
			exit 1
		fi

		output_clingo=`echo "$answerRow" | cat $basedir/v_per_pipe.asp $instance - | $basedir/clingo -q -`
		exit_clingo=${PIPESTATUS[*]}
		if [ $exit_clingo == 20 ]; then
			echo FAIL
			echo Too many valves per pipe >&2
			exit 1
		fi

		#extracting the objective value
		output_clingo=`echo "$answerRow" | cat $basedir/checker.asp $instance - | $basedir/clingo -q -`
		exit_clingo=${PIPESTATUS[*]}
		if [ $exit_clingo == 10 ]; then
			
			obj=( $output_clingo )
			for ix in ${!obj[*]}
			do
				if [ "${obj[$ix]}" == "Optimization:" ]; then
					echo OK ${obj[$ix+1]}'@'0
					exit 0
				fi
			done

			echo WARN
			echo Unrecognized input stream or general checker failure. >&2
			exit 3

		else
			if [ $exit_clingo == 20 ]; then
				echo FAIL
	    			echo Unrecognized failure. >&2
				exit 3
			else
	    			echo WARN
	    			echo Unrecognized input stream or general checker failure. >&2
	    			exit 3
			fi
		fi
	fi
fi
