#!/usr/bin/env bash

# $1 test dir suffix (debug / release)

set -o pipefail

EXECUTABLES="aepsilon2 atrim2 adeterminize2 aminimize2 anormalize2 acompare2 aderivation2 aintegral2 aconversions2"
TESTS_DIR="`pwd`/examples2/regexp"

# ----------------------------

for FILE in $EXECUTABLES; do
	if [ ! -f bin-$1/$FILE ]; then
		echo "Executable $FILE is required for testing. Make sure it is in bin-$1 folder."
		exit 1
	fi
done

cd bin-$1/

# ----------------------------

function regexpToMDFA {
	echo "$1" | ./aconversions2 -t fa | ./aepsilon2 | ./atrim2 | ./adeterminize2 | ./aminimize2 | ./anormalize2 --labels automaton
}

function compareRegexp {
	# relies on ret code by adiff.automaton
	./acompare2 <(regexpToMDFA "$1") <(regexpToMDFA "$2") > /dev/null
	return $?
}


# $1 - input regexp
# $2 - output regexp
function runTest {
	compareRegexp "$1" "$2"

	TEST_EXITVALUE=$?

	if [ $TEST_EXITVALUE == 0 ]; then
		echo -n "."
	elif [ $TEST_EXITVALUE == 1 ]; then
		echo -n "x"
	elif [ $TEST_EXITVALUE == 2 ]; then
		echo -n "T"
	elif [ $TEST_EXITVALUE == 3 ]; then
		echo -n "F"
	else
		echo -n "?"
	fi

}

function runTestD {
	 FILE_REGEXP_ORIG="$1"
	 FILE_REGEXP_RESULT="$2"
	 shift 2

	 REGEXP_DERIVATIVE=$(./aconvert2 --string_from_string <<< "$1" | ./aderivation2 -r $TESTS_DIR/$FILE_REGEXP_ORIG -s - )
	 REGEXP_RESULT=$(cat $TESTS_DIR/$FILE_REGEXP_RESULT)
	 runTest "$REGEXP_DERIVATIVE" "$REGEXP_RESULT"
}

function runTestI {
	 FILE_REGEXP_ORIG="$1"
	 FILE_REGEXP_RESULT="$2"
	 shift 2

	 REGEXP_INTEGRAL=$(./aconvert2 --string_from_string <<< "$1" | ./aintegral2 -r $TESTS_DIR/$FILE_REGEXP_ORIG -s - )
	 REGEXP_RESULT=$(cat $TESTS_DIR/$FILE_REGEXP_RESULT)

	 runTest "$REGEXP_INTEGRAL" "$REGEXP_RESULT"
}


# derivatives
echo "Derivatives"
runTestD "unbounded.oppa.4.13.xml" "unbounded.oppa.4.13.d0.xml" "\"0\""
runTestD "unbounded.oppa.4.13.xml" "unbounded.oppa.4.13.d00.xml" "\"0 0\""
runTestD "unbounded.oppa.4.14.xml" "unbounded.oppa.4.14.d1.xml" "\"1\""
runTestD "unbounded.oppa.4.14.xml" "unbounded.oppa.4.14.d10.xml" "\"1 0\""
runTestD "unbounded.oppa.4.15.xml" "unbounded.oppa.4.15.d100.xml" "\"1 0 0\""

# integrals 
echo ""
echo "Integrals"
runTestI "unbounded.oppa.4.16.xml" "unbounded.oppa.4.16.i1.xml" "\"1\""
runTestI "Melichar2-94.xml" "Melichar2-94.i0.xml" "\"0\""
runTestI "Melichar2-94.xml" "Melichar2-94.i1.xml" "\"1\""

echo ""
