#!/bin/sh
#
# This script is intended to run under Cygwin on a Window's machine
# with a clean export of CERT version 3.2 or later.
# It will run the release build of CERTDemo on Subject 32 and
# calculate the area under the ROC.


MSVS_msg="Since there doesn't seem to be any way to automatically have MSVS build the CERTDemo, make sure to build with the release configuration before running this script."

RESULTS=CERT_Results.txt
AROC=NA
AROC_file=AreaUnderROC.txt

OPTIONS=$*
KNOWNOPTIONS="NOBUILD NORUN NOGKR"

# Check if a particular option was given on the command line
function testOption()
{
    OPT=$*
    CNT=`echo ${OPTIONS} | grep -c ${OPT}`

    if [ ${CNT} -eq 0 ]; then
        return 1;
    else
        return 0;
    fi
}

if testOption "NOBUILD"; then
    echo "Skipping Building CERTDemo: `date`"
else
    echo "Building CERTDemo: `date`"
    ./buildProject.sh
fi

cd ..

if [ ! -d CERT2_VS2005/release ]; then
	echo "The directory CERT2_VS2005/release doesn't exist."
	echo ${MSVS_msg}
	exit
fi

if [ ! -x CERT2_VS2005/release/CERTDemo.exe ]; then
	echo "CERT2_VS2005/release/CERTDemo.exe doesn't exist."
	echo ${MSVS_msg}
	exit
fi

if [ ! -f CERT2_VS2005/release/libfftw3-3.dll ]; then
	cp libfftw3-3.dll CERT2_VS2005/release
fi

if ! testOption "NOGKR"; then
    GKR="-gc ../../GKR/D006_S032_GKR.xml"
fi

if testOption "NORUN"; then
    echo "Skipping Running CERTDemo: `date`"
else
# Run the CERT app on Subject 32
    echo "Running CERTDemo: `date`"
    rm -f ${RESULTS}
    cd CERT2_VS2005/release
    ./CERTDemo.exe -t ${GKR} ../../D006_S032 > ../../${RESULTS}
#./CERTDemo.exe -t ../../D006_S016 > ../../${RESULTS}
#./CERTDemo.exe -t ../../NewImages > ../../${RESULTS}
    cd ../..
fi

if [ -f ${RESULTS} ]; then
	LCNT=0
	LCNT=`cat ${RESULTS} | wc -l`
	if [ ${LCNT} -gt 0 ]; then
		echo "Calculating AROC: `date`"
		cd WinBuildAndTest
		AROC=`./CERT_ROC.sh ../${RESULTS}`
		cd ..
	else
		echo "Empty results file. Maybe CERTDemo didn't run correctly."
		exit
	fi
else
	echo "Missing results file. Maybe CERTDemo didn't run correctly."
	exit
fi


echo "Creating archive (BuildTestResults.tgz)"

rm -f ${AROC_file}
echo "AROC = ${AROC}" > ${AROC_file}

rm -f BuildLog.htm
cp CERT2_VS2005/CERTDemo/Release/BuildLog.htm .
tar -czf BuildTestResults.tgz BuildLog.htm ${RESULTS} ${AROC_file}

