#!/bin/bash


# HERE BEGINS THE SCRIPT

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

source $SCRIPTBASE/bin/env.sh

usage()
{
    echoPre "\nUsage:\n $(basename $0) [-h] xmlDescriptorFile.xml [-o option] [-m slice|probe] <xname> <xmin> <xmax> <xsampling> [<yname> <ymin> <ymax> <ysampling>]\n"   
}

echo "<response>"
trap beforeExit 0 1 2 5 15


# 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

DEFAULT_CHI2_MODE=slice
CHI2_MODE=$DEFAULT_CHI2_MODE

# Handle options of command line
# we can have numerical negative values that should not be hanlded has options
# ( do not exit in * case )
while getopts "o:m:" option
do
    case $option in
        m ) CHI2_MODE="$OPTARG" ;;
        o ) ARGSOPTIONS=", $OPTARG";;
        h ) usage ; exit ; shift ;;
#        * ) usage ; exit 1 ;;
    esac
done
shift $(($OPTIND - 1))

# check cmd line
if test $# -le 1
then
    echoPre "Missing arguments"
    usage 
    exit 1
fi

# Handle arguments that should be one of the two forms:
# <xname> <xmin> <xmax> <xsampling>
# <xname> <xmin> <xmax> <xsampling> [<yname> <ymin> <ymax> <ysampling>]
if [ $# -eq 4 ]
then
    ARGS="x=\"$1\", xmin=$2, xmax=$3, xsampling=$4 $ARGSOPTIONS"
elif [ $# -eq 8 ]
then
    x=$1
    xmin=$2
    xmax=$3
    xsampling=$4
    y=$5
    ymin=$6
    ymax=$7
    ysampling=$8
    ARGS="x=\"$x\", xmin=$xmin, xmax=$xmax, xsampling=$xsampling,  y=\"$y\", ymin=$ymin, ymax=$ymax, ysampling=$ysampling $ARGSOPTIONS"
    FITS_CODE="
#include \"fits.i\"
    img = lp_chi2_$CHI2_MODE( world, $ARGS);
    fh = fits_create(\"chi2map.fits\",bitpix=-32,dimlist=dimsof(img));
    xmin=$xmin*1.0
    xmax=$xmax*1.0
    xsampling=$xsampling*1.0
    ymin=$ymin*1.0
    ymax=$ymax*1.0
    ysampling=$ysampling*1.0

    fits_set, fh, \"CDELT1\", (xmax-xmin)/(xsampling-1);
    fits_set, fh, \"CDELT2\", (ymax-ymin)/(ysampling-1);
    fits_set, fh, \"CRVAL1\", $xmin;
    fits_set, fh, \"CRVAL2\", $ymin;
    fits_set, fh, \"CRPIX1\", 1;
    fits_set, fh, \"CRPIX2\", 1;

    fits_set, fh, \"COMMENT\",\"Generated by LITpro wrapper\";
    fits_set, fh, \"COMMENT\",\"$CHI2_MODE $ARGSOPTIONS\";
    fits_set, fh, \"COMMENT\",\"$x $xmin $xmax $xsampling\";
    fits_set, fh, \"COMMENT\",\"$y $ymin $ymax $ysampling\";
    fits_write_header, fh;
    fits_write_array ,fh ,img;
    fits_close, fh;

    "
else
  echoXmlErrorMessage "Bad arguments ($# present)"
  echoXmlComment "DEBUG: EXITING"
  exit 1
fi

echoXmlComment "DEBUG: ENTERING"
echoXmlComment "DEBUG: using $SCRIPTNAME script"
echoXmlComment "DEBUG: working base is $SCRIPTBASE"
echoXmlComment "DEBUG: path is $PATH"
echoXmlComment "DEBUG: $(date) : starting"

# Just do a simple log to get traces
echo "$(date) : $SCRIPTNAME $INPUTFILE $* ($ARGS) starts" >> $SCRIPTBASE/log/yoga.log
echoXmlComment "DEBUG: using logfile '$SCRIPTBASE/log/yoga.log'"

# creating one working area
TMPDIR=$SCRIPTBASE/tmp
if ! WORKING_DIRECTORY=$(mktemp -d)
then
    echoXmlErrorMessage "can't create working directory"
    echoXmlComment "DEBUG: EXITING"
    exit 1
fi

echoXmlComment "DEBUG: INPUTFILE is $INPUTFILE"
# get temporary filenames
XML_SETTINGS_FILE=settings.xml
cd $WORKING_DIRECTORY
echoXmlComment "DEBUG: entering working directory : $WORKING_DIRECTORY"
if ! cp $INPUTFILE $XML_SETTINGS_FILE &> /dev/null
then
    echoXmlErrorMessage "can't copy given file $INPUTFILE"
    echoXmlComment "DEBUG: EXITING"
    exit 1
fi

# Start real job:
# check xml descriptor file
checkXmlDescriptorFile $XML_SETTINGS_FILE || exit $?
# 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
#uvmap=lp_compute_model_uvmap( world, group=$GROUP);
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";
lp_chi2_$CHI2_MODE( world, $ARGS);
pdf, "chi2map";

window, display="",hcp="img.ps";

$FITS_CODE

quit;
EOF

# Run batch
if ! RES="$(runYorickBatch "$BATCH_FILE")"
then
    echoXmlComment "$RES"
    extractError "$RES"
    exit 1
fi
echoXmlComment "$RES"
extractError "$RES"

for img in chi2map
do
    if convertPdfToPng ${img}.pdf
    then
        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 "<description>$img plot</description>"
        echo "</resultFile>"
        echo "<resultFile  name=\"${img}.pdf\" description=\"$img plot\" href=\"data:application/pdf;base64,$(cat ${img}.pdf.b64)\">"
        echo "<description>$img plot</description>"
        echo "</resultFile>"
	if [ -f "$img.fits" ] 
	then
		encode64.py ${img}.fits ${img}.fits.b64
		echo "<resultFile  name=\"${img}.fits\" description=\"$img plot\" href=\"data:application/fits;base64,$(cat ${img}.fits.b64)\">"
		echo "<description>$img plot</description>"
		echo "</resultFile>"
	fi
    else
        echo "<message type=\"ERROR\">Can't get ${img} plot</message>"
    fi
done


echoXmlComment "DEBUG: EXITING"


# HERE ENDS THE SCRIPT
echo "$(date) : $SCRIPTNAME stops" >> $SCRIPTBASE/log/yoga.log
exit 0
