#!/bin/bash

# test -exe algo

LUTIN="$LURETTE_PATH/$HOSTTYPE/bin/lutin  -seed 9 -l 100"

TDIR=,testexe
IDIR=,ins

function getnodes {
	cat $1 | grep "^node " | sed -e "s/^node [ ]*\([^ (]*\)[ (].*$/\1/"
}


function dolutin {
	local base=$1
	local n=$2
	local ins="$IDIR/$base-$n.ins"
	local rif=$TDIR/$base-$n.rif
	if [ ! -f "$ins" ]; then
		#ins="/dev/null"
		cat /dev/null | $LUTIN "$base.lut" -m $n -l 1 | grep -e "#inputs"
		echo "-- please provide a file \"$ins\" (even empty !)"
		exit 1
	fi
#set -x
	echo "cat \"$ins\" | $LUTIN \"$base.lut\" -m $n | grep -v Version > \"$rif\""
	cat "$ins" | $LUTIN "$base.lut" -m $n  | grep -v " Version" > "$rif"
	if [ $? != 0 ]; then exit 1; fi
#set +x

}

function testit {
	local f="$1"
	local n=$2
	local base=`basename "$f" .lut`
	local rif="$TDIR/$base-$n.rif"
	local ref="$rif.ref"
	local res="$base-$n.res"
	if [ ! -f "$ref" ]; then
		echo "-- RUN \"make utest\" first !"
		exit 1
	fi
	dolutin "$base" $n
	diff -B -u -i "$ref" "$rif" > "$res"
	if [ $? != 0 ]; then
            echo "*** Error: $rif and $ref differs"
            cat "$res"
            exit 1
        fi
	local problem=`cat "$res" | wc -c`
	if [ $problem != 0 ]; then
		exit 1
	else
		echo rm -f "$res"
		rm -f "$res"
	fi
}

function utestit {
	local f="$1"
	local n=$2
	local base=`basename "$f" .lut`
	dolutin "$base" $n
	local rif="$TDIR/$base-$n.rif"
	local ref="$rif.ref"
	mv -f "$rif" "$ref"
}

if [ "$1" = "-u" ]; then
	treat=utestit
else
	treat=testit
fi

for f in *.lut; do
	for n in `getnodes $f`; do
		$treat $f $n
	done
done
