#! /bin/bash
ok=false
instance=$(readlink -f $2)
cd $(dirname $0)
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 ] && [ $1 != 20 ]; 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 ]; then
		echo "FAIL"
	        exit 1
	else
		# Filter for output predicates col/2, everything else will be ignored
		filteredAnswer=$(echo "$answerRow" | grep -o -e 'put([^,^)]\+,[^)^,]\+,[^)^,]\+)\.')
		# Provide filtered witness, additionally specify input instance ($2)
		#$(echo  "$filteredAnswer" > op.txt)
		#$( ./clingo op.txt constraint.asp $instance  >& op1.txt )

		output=$(./clingo - constraint.asp $instance <<< "$filteredAnswer" 2>&1 | egrep "^(% warning|Answer: )")

		if [[ $? = 1 ]]
		then
    			echo "WARN"
    			echo "Unrecognized input stream or general checker failure." >&2
    			exit 3
		fi
		#Warns when the required instance and/or output predicates are missing
		grep -q "^% warning" <<< "$output"
		if [[ $? = 0 ]]
		then
    			echo "WARN"
    			echo "Unrecognized input stream or general checker failure." >&2
    			exit 3
		else
		grep -q "^Answer: " <<< "$output"
			if [[ $? = 0 ]] 
			then
				ok=true
			else
				ok=false
			fi
		fi
	fi
fi
if $ok; then
	echo "OK"
	exit 0;
else
	echo "FAIL"
	exit 1;
fi 
