#!/bin/bash


# HERE BEGINS THE SCRIPT

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

usage()
{
    echoPre "\nUsage:\n $(basename $0) xmlDescriptorFile.xml [groupId]\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

if [ -n "$2" ]
then
    GROUP="$2"
else 
    GROUP="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";

#include "fits.i"
img = lp_plot_uvmap(world, $GROUP);
fh = fits_create("uv_model.fits",bitpix=-32,dimlist=dimsof(img));
fits_write_header, fh;
fits_set, fh, "COMMENT","Generated by LITpro";
fits_write_array ,fh ,img;

fits_close, fh;

lp_plot_uvmap, world, $GROUP;
pdf, "uv_model_data";
window, display="",hcp="img.ps";
lp_plot_uvmap, world, $GROUP, edges=1;
pdf, "uv_model_data_edges";
quit;
EOF

# Run batch
runYorickBatch "$BATCH_FILE"

uv_model_data_desc="markers without edges"
uv_model_data_edges_desc="markers with edges"

for img in uv_model_data uv_model_data_edges
do
    convertPdfToPng ${img}.pdf
    eval imgDesc=\$${img}_desc
    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)\"><description>$imgDesc</description></resultFile>"
    echo "  <resultFile name=\"${img}.pdf\" href=\"data:application/pdf;base64,$(cat ${img}.pdf.b64)\"/>"

    if [ -e "${img}.fits" ] 
    then
        encode64.py ${img}.fits ${img}.fits.b64
        echo "  <resultFile name=\"${img}.fits\" href=\"data:application/fits;base64,$(cat ${img}.fits.b64)\"/>"
    fi

done

# HERE ENDS THE SCRIPT
