#!/bin/bash


# HERE BEGINS THE SCRIPT

SCRIPTSTARTUPDIR=$PWD
SCRIPTNAME=$(basename $0)
SCRIPTBASE=$(dirname $0)/..
#make SCRIPTBASE fully qualified
SCRIPTBASE=$( cd $SCRIPTBASE && pwd )


usage()
{
    echo "\nUsage:\n $(basename $0) xmlDescriptorFile.xml [-o option] <VIS2|VISamp|VISphi|T3amp|T3phi> <groupId> [angle]" 
    echo "If one angle is provided, the model is displayed\n"
}

source $SCRIPTBASE/bin/env.sh
enterTmpWorkingDir
XML_SETTINGS_FILE=settings.xml
copyXmlInputFile $1 ${XML_SETTINGS_FILE}
trap beforeExit 0 1 2 5 15
echo "<response>"

# check cmd line
if test $# -lt 1
then
    echoPre "Missing file as argument"
    usage 
    exit 1
fi

# Store full path of INPUTFILE if given path was not absolute
INPUTFILE=$1
if test ${INPUTFILE:0:1} != "/" 
then
    INPUTFILE=$PWD/$1
fi
shift 1

# Handle options of command line
while getopts "o" option
do
    case $option in
        o ) ARGSOPTIONS+=", $2" ;shift 2;;
        h ) usage ; exit ; shift ;;
        * ) usage ; exit 1 ;;
    esac
done


# Handle arguments that should be one of form given in usage function
if [ $# -eq 2 ]
then
    ARGS1="\"$1\" , groups=$2"
    ARGS2="$ARGS1"
elif [ $# -eq 3 ]
then
    ARGS1="\"$1\" , groups=$2"
    ARGS2="\"$1\" , groups=$2, angle=$3"
else
    echoXmlErrorMessage "Wrong arguments:\n $(usage)"
    echoXmlComment "DEBUG: EXITING"
    exit 1
fi

# Start real job:

# check xml descriptor file
checkXmlDescriptorFile $XML_SETTINGS_FILE
# generating yoga descriptor file
generateYogaDescFile $WORKING_DIRECTORY $XML_SETTINGS_FILE settings.i || exit $?
# decode b64 files
decodeB64Files $(ls *.b64) || exit $?

# generating batch into current directory
BATCH_FILE=batch.i
echo "/* Generated by $SCRIPTBASE/$SCRIPTNAME */" > $BATCH_FILE
echo "_GUI_SPECIALS_=1;" >> $BATCH_FILE
echo "#include \"$YOGA_LOCATION/LITpro/yorick/LITpro.i\"" >> $BATCH_FILE
cat >> $BATCH_FILE << EOF
world = lp_load_model("settings.i");
window, display="",hcp="img.ps";
EOF
if [ "$ARGS2" != "$ARGS1" ]
then
    echo "lp_plot_radial_model, world, degree=1, $ARGS2;" >> $BATCH_FILE
fi
cat >> $BATCH_FILE << EOF
lp_plot_radial, world, degree=1, $ARGS1;
limits, 0.,limits()(2)*1.05, min(limits()(3), 0.), max(limits()(4), 1.)*1.05;
pdf, "img";
quit;
EOF

# Run batch
runYorickBatch "$BATCH_FILE"

convertPdfToPng img.pdf
encode64.py img.png img.png.b64
encode64.py img.pdf img.pdf.b64
echo "<resultFile name=\"img.png\" href=\"data:image/png;base64,$(cat img.png.b64)\"/>"
echo "<resultFile name=\"img.pdf\" href=\"data:application/pdf;base64,$(cat img.pdf.b64)\"/>"

# HERE ENDS THE SCRIPT
