#!/bin/bash

# check-incremental-scheduling.sh
#
# Marcello Balduccini
# marcello.balduccini@gmail.com
# Jan 14, 2011
#
# Checks the solution to a maze generation problem
#
# 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
#
#
# NOTE: gringo 3.x+ is REQUIRED!!!!!!!!!!!!!!!
# change the path below to point to gringo 3.x+
#

create_script() {
	local RENAME_PREDS
	local p

	RENAME_PREDS="already_started already_finished must_schedule must_not_schedule has_tot_penalty td instance_of pen_value td_value time rescheduled tot_penalty penalty"

	for p in $RENAME_PREDS
	do
		echo 's/^\('$p'[(.]\)/orig_\1/g'
		echo 's/\([^a-zA-Z0-9_]\)\('$p'[(.]\)/\1orig_\2/g'
	done
}

EXEDIR="`dirname $0`"

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

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

REFERENCE_ENCODING=$EXEDIR/incremental_scheduling.enc.asp
CHECKING_COMPONENT=$EXEDIR/checking-component.lp

EXITCODE=$1
shift
INSTANCEFILE=$1
shift

read HEADER

if [ "$EXITCODE" != "0" -a "$HEADER" = "UNKNOWN" ]; then
	RES="FAIL"
else
	RES=""
	case "$EXITCODE" in
		10)
#			echo "echo '$HEADER' | sed -f $EXEDIR/sedfile.txt | cat <(echo 'debug.') $REFERENCE_ENCODING $CHECKING_COMPONENT $INSTANCEFILE - | $GROUNDER 2>/dev/null | $SOLVER 2>/dev/null" 
			echo $HEADER | sed -f <(create_script) | cat $REFERENCE_ENCODING $CHECKING_COMPONENT $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
