#!/bin/sh

# This script will check out all of the pieces of FeatureLearning and CERT that are needed for
# exporting CERT for use by NRL or someone else outside the MPLab.
# Needed data files will be generated and anything that's not needed will be removed
# Subversion Revision: $LastChangedRevision$

OPTIONS=$*
KNOWNOPTIONS="NOFEATURES OLDMLR ADD BINARY NODOCS NRL"

SVNVER=/usr/local/bin/svnversion

# 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 [ $# -lt 2 ]; then
    if [ "$1" = "list" ]; then
        echo "Known Options: ${KNOWNOPTIONS}"
    else
        echo "$0 [list] <MPT Revision> <CERT Revision> [NOFEATURES | OLDMLR | ADD | BINARY | NODOCS | NRL]"
        echo "  Usage: You must supply a Subversion revision number for MPT and CERT. Checking for current revision..."
        CURMPT=`${SVNVER} -n $MPT`
        CURCERT=`${SVNVER} -n $MPT/../../CERT`
        echo "  Current revisions are:  ${CURMPT}  and  ${CURCERT}"
    fi
    exit
fi

# If any output directories already exist svn will complain, so tell the user then exit
if [ -d mptslidingwindow -o -d eyefinder -o -d CERTWrapper -o -d Documentation -o -d Misc -o -d aligneyes -o -d mp_auCoder -o -d featuredetector -o -d MLR -o -d CERT2_VS2005 ]; then
    echo "Some output directories already exist, you will need to clear out the destination directory before exporting CERT 2.0"
    exit
fi

STARTDATE=`date`
DOXYGEN=/Users/Shared/Applications/Doxygen.app/Contents/Resources/doxygen
QUIET=-q

MPTREV=$1
CERTREV=$2
#BRANCH=branches/CERT2_0
BRANCH=trunk
MPTRUN=svn+ssh://mplab.ucsd.edu/usr/local/svnroot/FeatureLearning/${BRANCH}/Runtime
SVNCMD=export
#SVNCMD=checkout
SRCDIR=`pwd`

if [ "X${BRANCH}" != "Xtrunk" ]; then
    echo "Warning! Working from branch: ${BRANCH}"
fi

# 1) checkout all the different pieces
echo "Exporting FeatureLearning source..."
svn ${SVNCMD} ${QUIET} -r ${MPTREV} ${MPTRUN}/Libraries/mptslidingwindow/src mptslidingwindow
svn ${SVNCMD} ${QUIET} -r ${MPTREV} ${MPTRUN}/Libraries/eyefinder/src eyefinder
svn ${SVNCMD} ${QUIET} -r ${MPTREV} ${MPTRUN}/Libraries/smiledetector/src smiledetector
svn ${SVNCMD} ${QUIET} -r ${MPTREV} ${MPTRUN}/Libraries/PoseDetector/src posedetector
svn ${SVNCMD} ${QUIET} -r ${MPTREV} ${MPTRUN}/Libraries/FeaturePointImprover/src FeaturePointImprover
svn ${SVNCMD} ${QUIET} -r ${MPTREV} ${MPTRUN}/Build Build

if ! testOption "NOFEATURES"; then
# if the featuredetector is ready for use in this svn version check it out as well
    FD=`svn list -r ${MPTREV} ${MPTRUN}/Libraries/featuredetector/frozenData 2> /dev/null`
    if [ "X${FD}" != "X" ]; then
        svn ${SVNCMD} ${QUIET} -r ${MPTREV} ${MPTRUN}/Libraries/featuredetector/src featuredetector
        svn ${SVNCMD} ${QUIET} -r ${MPTREV} ${MPTRUN}/Libraries/featuredetector/frozenData featuredetector/frozenData
        svn ${SVNCMD} ${QUIET} -r ${MPTREV} ${MPTRUN}/Applications/featuredetector/ fdtemp
    fi
fi

CERTREP=svn+ssh://mplab.ucsd.edu/usr/local/svnroot/CERT/${BRANCH}
echo "Exporting CERT source..."
svn ${SVNCMD} ${QUIET} -r ${CERTREV} ${CERTREP}/Build/aligneyes aligneyes
svn ${SVNCMD} ${QUIET} -r ${CERTREV} ${CERTREP}/Build/mp_auCoder mp_auCoder
svn ${SVNCMD} ${QUIET} -r ${CERTREV} ${CERTREP}/Build/Misc Misc
svn ${SVNCMD} ${QUIET} -r ${CERTREV} ${CERTREP}/Build/CERTWrapper CERTWrapper
svn ${SVNCMD} ${QUIET} -r ${CERTREV} ${CERTREP}/Build/CERT2_VS2005 CERT2_VS2005
svn ${SVNCMD} ${QUIET} -r ${CERTREV} ${CERTREP}/Build/DemoAndLicensing DemoAndLicensing
svn ${SVNCMD} ${QUIET} -r ${CERTREV} ${CERTREP}/Build/GKR GKR
svn ${SVNCMD} ${QUIET} -r ${CERTREV} ${CERTREP}/Build/IntervalDetection IntervalDetection
svn ${SVNCMD} ${QUIET} -r ${CERTREV} ${CERTREP}/AdditionalAUs/BlinkAUDetector/MPT_BlinkAU.bundle/Contents/Resources/Weights/ BlinkAU
svn ${SVNCMD} ${QUIET} -r ${CERTREV} ${CERTREP}/AdditionalAUs/Unilaterals/Weights Unilaterals
if testOption "OLDMLR"; then
    svn ${SVNCMD} ${QUIET} -r ${CERTREV} ${CERTREP}/Build/MLR MLR
fi

#svn ${SVNCMD} ${QUIET} -r ${CERTREV} ${CERTREP}/Build/ExpressionFilter ExpressionFilter
svn ${SVNCMD} ${QUIET} -r ${CERTREV} ${CERTREP}/Documentation Documentation

echo "Exporting Third-Party source..."
#THIRDPARTY=svn+ssh://mplab.ucsd.edu/usr/local/svnroot/third-party
#svn ${SVNCMD} ${QUIET} ${THIRDPARTY}/SOBI/src hipersat

# 2) Generate data files
echo "Generating Gabor Kernels..."
make -s -C mp_auCoder/KernelExport CERT=$MPT/../../CERT IS_SILENT=1 sourceonly
echo "Generating SVM weight files..."
make -s -C mp_auCoder/SVMWeights CERT=$MPT/../../CERT IS_SILENT=1
if testOption "EMOT"; then
    CS=${MPT}/../../CERT/Source
    if [ -f ${CS}/Gwen_emotions.mat ]; then
        REALEMOT=`readlink -f ${CS}/Gwen_emotions.mat | xargs basename`
        if [ -f ${CS}/${REALEMOT} ]; then
            make -s -C mp_auCoder/SVMWeights CERT=$MPT/../../CERT IS_SILENT=1 WEIGHTSFILE=${REALEMOT} WEIGHTS_PREFIX=LabEmotions
        else
            echo "No emotion weights file: ${CS}/${REALEMOT}"
        fi
    else
        echo "No emotion weights link file: ${CS}/Gwen_emotions.mat"
    fi
else
    echo "No emotion option."
fi
if testOption "ADD"; then
    if [ -x mp_auCoder/SVMWeights/makeAdditionalWeights.sh ]; then
        echo "Generating Additional AU weight files..."
        CURPWD=`pwd`
        cd mp_auCoder/SVMWeights
        export CERT=$MPT/../../CERT
        ./makeAdditionalWeights.sh ${CERTREV}
        cd ${CURPWD}
    fi
fi

if testOption "OLDMLR"; then
    echo "Generating MLR weight files..."
    make -s -C MLR CERT=$MPT/../../CERT CERTVER=${CERTREV} IS_SILENT=1 mex bhats
    make -s -C MLR CERT=$MPT/../../CERT CERTVER=${CERTREV} IS_SILENT=1 clean
    rm -rf MLR/main*
    rm -rf MLR/*.mat
fi

# Need an option to block this, but we might want to reuse NOMLR once the old MLR is removed
echo "Generating MLR_SVM weight files..."
make -s -C mp_auCoder/SVMWeights CERT=$MPT/../../CERT IS_SILENT=1 mlr

echo "Generating CERT 4.0 weight files..."
make -s -C mp_auCoder/SVMWeights CERT=$MPT/../../CERT IS_SILENT=1 WEIGHTSFILE=AUWeights_Ting_20080201.mat WEIGHTS_PREFIX=CERT4_0_Weights

# 3) Now do some moving around of files and cleaning up
find . -name UnitTests -type d | xargs rm -rf
find . -name 'Makefile*' -type f | xargs rm -rf
find . -name 'CFLAGS-*.txt' -type f | xargs rm -rf
find . -name 'Jamfile' -type f | xargs rm -rf   

# Set the revision numbers
sed -e "s/#define SVN_REV \"[^\"]*\"/#define SVN_REV \"${MPTREV}\"/" Build/mptVersion.c.in > Misc/mptVersion.c
mv Build/mptVersion.h Misc/
rm -rf Build
sed -e "s/#define CERT_SVN_REV \"[^\"]*\"/#define CERT_SVN_REV \"${CERTREV}\"/" Misc/certVersion.c.in > Misc/certVersion.c
rm -f Misc/certVersion.c.in
rm -f Misc/makeCERT2.sh
rm -f Misc/makeCERT2.mk
rm -rf Misc/WinBuildAndTest

rm -f CERTWrapper/mp_CERTMex.cpp
rm -f CERTWrapper/rimageFromNSImage.*
rm -f CERTWrapper/main_test.diffs
#if ! testOption "BINARY"; then
#    rm -rf CERTWrapper/Plugins
#fi

rm -rf aligneyes/BoostTests
rm -rf aligneyes/TestSerialization
rm -rf aligneyes/mexopts*.sh
rm -rf aligneyes/mp_alignEyes.*
rm -rf aligneyes/rimage_matlab.*

#rm -rf eyefinder/EyeWeightsFiles/config.h                          
rm -rf eyefinder/mp_rotatingEyefinder.*

rm -rf mptslidingwindow/perftest*
rm -rf mptslidingwindow/serializeOldWeights*
rm -rf mptslidingwindow/samplegrabber*

if [ -f featuredetector/interpolate.h ]; then
    sed -e "s/#define  *II_DO_LOG  *(1)/#define II_DO_LOG (0)/" featuredetector/interpolate.h > aligneyes/interpolate.h
else
    sed -e "s/#define  *II_DO_LOG  *(1)/#define II_DO_LOG (0)/" smiledetector/interpolate.h > aligneyes/interpolate.h
fi
rm -f featuredetector/interpolate.h
rm -rf smiledetector

mv mp_auCoder/KernelExport/kernels-96x96 mp_auCoder
rm -rf mp_auCoder/KernelExport
rm -rf mp_auCoder/kernels-96x96/Data
rm -rf mp_auCoder/kernels-96x96/flag.mk

mv mp_auCoder/SVMWeights/SVMWeights mp_auCoder/SVMWeights.tmp
rm -rf mp_auCoder/SVMWeights
mv mp_auCoder/SVMWeights.tmp mp_auCoder/SVMWeights
# if we're not doing MLR then we don't need the Emotion weights files
if ! testOption "OLDMLR"; then
    rm -rf mp_auCoder/SVMWeights/EmotionWeights_*.xml
fi
cp Unilaterals/* mp_auCoder/SVMWeights/
rm -rf Unilaterals

rm -f mp_auCoder/mp_auCoder.cpp mp_auCoder/mp_auCoder.h
rm -f mp_auCoder/Kernels.mk

if [ -d fdtemp ]; then
    mv fdtemp/* featuredetector
    rm -rf fdtemp
fi

rm -rf featuredetector/FeatureWeightsFiles
rm -rf featuredetector/serializeOldEyeWeights.cpp
rm -rf featuredetector/serializeOldEyeWeights
#rm -rf featuredetector/svd.*
# if the newer mouth weights exist, remove the older ones
if [ -f featuredetector/frozendata/mouth_CERT3_1.gpriorxml ]; then
    rm -f featuredetector/frozendata/mouth_CERT3.fdtxml
    rm -f featuredetector/frozendata/mouth_CERT3.gpriorxml
fi

mv DemoAndLicensing/DemoAndLicensing* CERTWrapper
rm -rf DemoAndLicensing

rm FeaturePointImprover/main.c

# Generate Doxygen output
if ! testOption "NODOCS"; then
    echo "Generating source documentation..."
    ${DOXYGEN} Documentation/Doxyfile 
fi
rm -rf Documentation/Doxyfile
rm -rf "Documentation/CERT Flow Chart.oo3"
rm -f "Documentation/CERT_Build.txt"
rm -f "Documentation/CERT_Versions.txt"
rm -f Documentation/*Requirements*
rm -f Documentation/*[Dd]esign*
rm -f Documentation/SVMExportHelp.txt

TESTDIR=../CERT2_0_TEST
if [ -d ${TESTDIR} ]; then
# Generate a test app, run it, and compare to expected values
    echo
    echo "Generating a test app"
    cd ${TESTDIR}
    make -s BUILD_DIR=${SRCDIR} clean
    ln -s ${SRCDIR}/mp_auCoder/SVMWeights
    MAKEOPTIONS=""
    if testOption "NOFEATURES"; then
        MAKEOPTIONS="${MAKEOPTIONS} NOFEATURES=1"
    fi
    if ! testOption "OLDMLR"; then
        MAKEOPTIONS="${MAKEOPTIONS} NOMLR=1"
    fi

    echo "Make command: make -s BUILD_DIR=${SRCDIR} ${MAKEOPTIONS}"
    make -s BUILD_DIR=${SRCDIR} ${MAKEOPTIONS}

    echo
    echo "Running test app"
    CERTOUT=`./CERT -t 1005.rimage`
    AUS=`echo ${CERTOUT} | tail -1`
# Without expression filtering, SVMWeights as of 7/31/2006, Plus Gwens extra step
    GOOD_AUS="-0.28297521, -0.071829496, 1.027907, -1.6110861, -0.62560298, -1.2335333, -1.8351188, -1.05746"
# Without expression filtering, SVMWeights as of 7/31/2006
#GOOD_AUS="7.6072709, 0.336321, 1.6415271, -6.7245087, -3.0305008, -0.53009088, -11.736489, -6.7066323"
# Without expression filtering
#GOOD_AUS="0.904266, -0.684095, 1.13765, -1.43378, -0.0796643, -0.818025, -1.10107, 0.0245506"
# With expression filtering
#GOOD_AUS="0.853643, 0.592146, 0.853898, 0.410414, 1.08169e-05, 0.535135, 0.784918, 0.595064"

    if [ "${AUS}" == "${GOOD_AUS}" ]; then
        echo "Test appears to have run correctly"
    else
        echo "Uh, oh! you got trouble! Correct results should be:"
        echo "${GOOD_AUS}"
        echo "But you got:"
        echo "${CERTOUT}"
    fi
else
    echo "Couldn't find test directory: " ${TESTDIR}
fi

#if testOption "NRL"; then
#    cd ${SRCDIR}
#    echo "Copying ThirdPartyLibraries for NRL release."
#    mv ../ThirdPartyLibraries .
#    if [ -f ../BuildTestResults.tgz ]; then
#        echo "Copying BuildTestResults for NRL release."
#        mkdir CERT2_VS2005/BuildTestResults
#        cd CERT2_VS2005/BuildTestResults
#        tar -xzf ../../../BuildTestResults.tgz
#    fi
#fi

echo "Creating zip file."
cd ${SRCDIR}
SRCNAME=`basename ${SRCDIR}`
rm -rf ../${SRCNAME}.zip
echo "Zip command: zip -r ../${SRCNAME}.zip . -q -x \*.DS_Store"
zip -r ../${SRCNAME}.zip . -q -x \*.DS_Store

#if testOption "NRL"; then
# Put the library dir back
#    mv ThirdPartyLibraries ..
#fi

echo
echo "Exporting started: ${STARTDATE} and ended `date`"
