#! /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 pushtogoal pushtonongoal move, everything else will be ignored
		filteredLoad=$(echo "$answerRow" | grep -o -P 'pushtogoal\(.+?,.+?,.+?,.+?,.+?,.+?,.+?\)\.' | perl -ne 'chomp and print')
		filteredUnload=$(echo "$answerRow" | grep -o -P 'pushtonongoal\(.+?,.+?,.+?,.+?,.+?,.+?,.+?\)\.' | perl -ne 'chomp and print')
		filteredDrive=$(echo "$answerRow" | grep -o -P 'move\(.+?,.+?,.+?,.+?,.+?\)\.' | perl -ne 'chomp and print')
		# Provide filtered witness, additionally specify input instance ($2)
		# echo "$filteredLoad $filteredUnload $filteredDrive | gringo ./constraint.asp $2 - | clasp"
                systemResult=$(echo "$filteredLoad $filteredUnload $filteredDrive" | cat ./constraint.asp $instance - | ./gringo | ./clasp)
#		systemResult=$(echo "$filteredLoad $filteredUnload $filteredDrive" | ./gringo ./constraint.asp $2 - | ./clasp)
		chkexit=$?
		if [[ $chkexit -eq 10 ]] ; then
	    		echo "OK"
	    		exit 0
		elif [[ $chkexit -eq 20 ]] ; then
	    		echo "FAIL"
	    		exit 1
#	elif [[ $chkexit -eq 1 && $systemResult =~ (\s)*ERROR ]] ; then
		elif [[ $chkexit -eq 1 ]] ; then
    	    		echo "WARN"
    	    		echo "Unrecognized input stream or general checker failure." >&2
    	    		exit 3
		fi
	fi
fi
