#!/bin/sh

CLIPC="./clipc"
CLIP="./clip"

HOME=/Users/sylvia_duan/Documents/Columbia/PLT/project/clip

#Set time limit for all operations
ulimit -t 30

globallog=testall.log
rm -f $globallog
error=0
globalerror=0

keep=0



SignalError() {
    if [ $error -eq 0 ] ; then
      	echo "FAILED"
      	error=1
    fi
        echo "  $1"
}

# Compare <outfile> <reffile> <difffile>
# Compares the outfile with reffile.  Differences, if any, written to difffile
Compare() {
    diff -b "$1" "$2" > "$3" 2>&1 || 
    {
	  SignalError "$1 differs" > $ERRORFILE
    }
}

Check() {
    error=0

    filename=$(basename "$1")
    FILENAME=$1
    FILENAME="${FILENAME%.clip}"
    filename="${filename%.clip}"
    TESTFILE="$FILENAME.clip"
    ERRORFILE="$FILENAME.error"
    REFFILE="$FILENAME.ref"
    OUTTREE="$FILENAME.tree"
    OUTFILE="$FILENAME.out"
    CCFILE="$FILENAME.cc"
    TARGET="$FILENAME"
    DIFFFILE="$FILENAME.DIFF"
    
    printf "Testing $filename ... " 
    $CLIPC $TESTFILE -c 2> $ERRORFILE
    if [[ -x "$TARGET" ]] ; then
        ./$TARGET > $OUTFILE 2> $ERRORFILE
        Compare $OUTFILE $REFFILE $DIFFFILE
        if [ $error -eq 0 ] ; then
            rm -f $DIFFFILE
            rm -f $CCFILE
            rm -f $FILENAME
            printf "\r\t\t\t\t Accept!!"
        else
            printf "\r\t\t\t\t Wrong Answer"
            globalerror=$error
        fi
    else
        printf "\r\t\t\t\t Not executable or found, refer .error file"
    fi
    echo ""
}

if [ $# -ge 1 ] ; then
    files=$@
else
    files="test/*/*.clip"
fi

rm -f test/*/*.error
rm -f test/*/*.out

for file in $files
do
    case $file in
        *test-*)
        Check $file
	      ;;
    esac
done

exit $globalerror
