#!/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()
{
    echo "\nUsage:\n $(basename $0) xmlDescriptorFile.xml <groupId> <xmin> <xmax> <ymin> <ymax> <pixscale>\n"   
}

echo "<response>"
trap beforeExit 0 1 2 5 15
# 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
# Handle arguments that should be one of form given in usage function
if [ $# -eq 6 ]
then
    xmin=$2
    xmax=$3
    ymin=$4
    ymax=$5
    pixscale=$6
    ARGS="$1, xmin=$2, xmax=$3, ymin=$4 , ymax=$5, pixscale=$6"
else
    echoXmlErrorMessage "Missing arguments:\n $(usage)"
    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 $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 $?

echoXmlComment "DEBUG: $(which yorick)"
# 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");

extern _LPB_MAS2DEG;

#include "fits.i"
img = lp_plot_image(world, $ARGS);
fh = fits_create("img.fits",bitpix=-32,dimlist=dimsof(img));
xmin=$xmin*1.0
ymin=$ymin*1.0
xmax=$xmax*1.0
ymax=$ymax*1.0
pixscale=$pixscale*1.0

x1=sign(xmin)*ceil(abs(xmin)/pixscale)*pixscale
x2=sign(xmax)*ceil(abs(xmax)/pixscale)*pixscale
y1=sign(ymin)*ceil(abs(ymin)/pixscale)*pixscale
y2=sign(ymax)*ceil(abs(ymax)/pixscale)*pixscale

crpix1 = 1.0 + ( -x1 / ( x2 - x1 )) * (dimsof(img)(2) - 1);
crpix2 = 1.0 + ( -y1 / ( y2 - y1 )) * (dimsof(img)(3) - 1);
//lp_warn, swrite(format="crpix1=%f ; crpix2=%f ",crpix1,crpix2 );

fits_set, fh, "CDELT1", pixscale*_LPB_MAS2DEG;
fits_set, fh, "CDELT2", pixscale*_LPB_MAS2DEG;
fits_set, fh, "CRVAL1", 0.0;
fits_set, fh, "CRVAL2", 0.0;
fits_set, fh, "CRPIX1", crpix1;
fits_set, fh, "CRPIX2", crpix2;
fits_set, fh, "COMMENT","Generated by LITpro wrapper";
fits_write_header, fh;
fits_write_array ,fh ,img;
fits_close, fh;

window, display="",hcp="img.ps";
lp_plot_image, world, $ARGS;
pdf, "img";

quit;
EOF

# Fits header sample of one public image
# http://aladin.u-strasbg.fr/cgi-bin/nph-Aladin++.cgi?out=image&position=56.87116666666667+%2B24.105138888888888&survey=2MASS&color=K&mode=MOSAIC&comp=FITS 
# SIMPLE  =                    T / file does conform to FITS standard
# BITPIX  =                  -32 / number of bits per data pixel
# NAXIS   =                    2 / number of data axes
# NAXIS1  =                  512 / length of data axis 1
# NAXIS2  =                 1024 / length of data axis 2
# BZERO   =                   0. / PhysValue = BZERO + BSCALE * ArrayValue
# BSCALE  =                   1. / PhysValue = BZERO + BSCALE * ArrayValue
# COMMENT   Standard WCS reduction:
# CRVAL1  =           56.9078355 / WCS Ref value (RA in decimal degrees)
# CRVAL2  =          24.20813822 / WCS Ref value (DEC in decimal degrees)
# CRPIX1  =                135.5 / WCS Coordinate reference pixel
# CRPIX2  =                883.5 / WCS Coordinate reference pixel
# CD1_1   = -0.000277777784447912 / WCS Coordinate scale matrix
# CD1_2   = -5.37936596340461E-09 / WCS Coordinate scale matrix
# CD2_1   = -5.37936596340461E-09 / WCS Coordinate scale matrix
# CD2_2   = 0.000277777784447912 / WCS Coordinate scale matrix
# CTYPE1  = 'RA---SIN'           / WCS Coordinate type
# CTYPE2  = 'DEC--SIN'           / WCS Coordinate type
# EQUINOX =                2000. / Equinox
# RADESYS = 'FK5     '           / Coordinate system
# MJD-OBS =     51138.2117828704 / Modified Julian Date at start of observation
# EPOCH   =     1998.88764348493 /  Epoch in Julian Year at start of observation
# CUNIT1  = 'DEG     '           / RA Coordinate Unit
# CUNIT2  = 'DEG     '           / DEC Coordinate Unit
# CDELT1  =      0.0002777777845 / WCS Coordinate scale matrix
# CDELT2  =      0.0002777777845 / WCS Coordinate scale matrix
# CNPIX1  =                    0 / New CNPIX1
# CNPIX2  =                    0 / New CNPIX2


# Run batch
if ! RES="$(runYorickBatch "$BATCH_FILE")"
then
        echoXmlComment "$RES"
            extractError "$RES"
                    exit 1
                fi
                echoXmlComment "$RES"
                extractError "$RES"
convertPdfToPng img.pdf
encode64.py img.fits img.fits.b64
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)\"/>"
echo "<resultFile name=\"img.fits\" href=\"data:image/fits;base64,$(cat img.fits.b64)\"/>"

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