#!/bin/bash

EASY_VERSION="1.1"

bb=`tput bold`
nn=`tput sgr0`

# help
if [ $# -eq 0 ]; then
    echo "${bb}-------------------------------------------------------------------${nn}"
    echo "${bb}Creates sof-file for kmo_std?star-recipe and executes it.${nn}"
    echo " "
    echo "- The environment variable ${bb}KMOS_CALIB${nn} pointing to a path has to be"
    echo "  set in order to find the needed static calibration frame WAVE_BAND,"
    echo "  SOLAR_SPEC, ATMOS_MODEL, SPEC_TYPE_LOOKUP."
    echo "  Otherwise the execution of this script will fail!"
    echo "- If XCAL, YCAL, LCAL, MASTER_FLAT and ILLUM_CORR frames aren't existing"
    echo "  in the working directory the script is searching as well KMOS_CALIB in"
    echo "  order to find them."
    echo "- As argument an arbitrary exposure of an executed "
    echo "  ${bb}KMOS_spec_cal_stdstar${nn} or ${bb}KMOS_spec_cal_stdstarscipatt${nn} template must be provided."
    echo "  All matching exposures are collected automatically."
    echo "- (Optional) If as 2nd argument ${bb}sof${nn} is provided, then only"
    echo "  the sof-file is generated but not executed."
    echo " "
    echo "${bb}Usage:${nn}"
    echo "  easySPARK_std_star.sh <filename with full path>"
    echo "    or"
    echo "  easySPARK_std_star.sh <filename with full path> sof"
    echo " "
    echo "Version: "$EASY_VERSION
    echo "${bb}-------------------------------------------------------------------${nn}"
    exit
fi

# init
sofOnly=0
printVers=0

# extract all arguments beginning with KMOS, eventually imethod and sof
while [ "$1" ] ; do
    tmp=$(basename $1)
    if [[ $tmp == KMOS* ]]; then
        # file-check
        if [ ! -e $1 ]; then
            echo "${bb}ERROR:${nn} File doesn't exist! ($1)"
            exit
        fi
        fileName=$1
    else
        if [[ $tmp == sof ]]; then
            sofOnly=1
        elif [[ $tmp == vers ]]; then
            printVers=1
        fi
    fi
    shift
done

if [ $printVers = 1 ]; then
    echo $EASY_VERSION
    exit
fi

# check if gawk is existing
if command -v gawk >/dev/null; then
   :
else
    echo "'gawk' has not been found on your system!"
    OS=$(uname -s)
    if [ $OS != "Linux" ]; then
        echo "You seem using a MacOS, please use e.g. MacPorts to install gawk."
    fi
    echo "Aborting now.!"
fi

if [ -z "${KMOS_CALIB}" ]; then
    echo "${bb}ERROR:${nn} environment variable KMOS_CALIB is not defined! (see help)"
    exit
fi

#check if file is of correct template
tplId=$(dfits $fileName |\
        fitsort -d tpl.id |\
        gawk '{print $2}')
if [[ $tplId != KMOS_spec_cal_stdstar && $tplId != KMOS_spec_cal_stdstarscipatt ]]; then
    echo "${bb}ERROR${nn}: File is of wrong template: $tplId instead of KMOS_spec_cal_stdstar or KMOS_spec_cal_stdstarscipatt !"
    exit
fi

# extract TPL.START of ths file
tplStartTime=$(dfits $fileName |\
               fitsort -d tpl.start |\
               gawk '{print $2}')

# get files with matching tplStartTime and OBJECT, STD, SKY,FLUX
dataDir=$(dirname "$fileName")
matchingFiles=$(dfits $dataDir/KMOS*.fits | \
                fitsort -d tpl.start dpr.type |\
       	        grep $tplStartTime |\
                grep OBJECT,SKY,STD,FLUX |\
                gawk '{print $1}')

# populate sof-file with STD frames
sofFile="std_star_$tplStartTime.sof"
cat > $sofFile </dev/null
for file in $(dfits $dataDir/KMOS*.fits | fitsort -d tpl.start |grep $tplStartTime|gawk '{print $1}' | tr "\n" " ")
do
    echo "$file STD" >> $sofFile
done

# get grating id of first ARC_ON frame
gratingUpper=$(dfits $matchingFiles |\
               fitsort -d ins.grat1.id |\
               head -n1 |\
               gawk '{print $2}')
gratingLower=$(echo $gratingUpper|tr "A-Z" "a-z")

# add static calibration frames
echo "$KMOS_CALIB/kmos_wave_band.fits       WAVE_BAND" >> $sofFile
echo "$KMOS_CALIB/kmos_spec_type.fits       SPEC_TYPE_LOOKUP" >> $sofFile

# add band-specific static calibration frames
fnAtmosModel=$KMOS_CALIB"/"kmos_atmos_$gratingLower.fits
fnSolarSpec=
if [ $gratingUpper == "H" ]; then
    fnSolarSpec=$KMOS_CALIB"/"kmos_solar_h_2400.fits
elif [ $gratingUpper == "HK" ]; then
    fnSolarSpec=$KMOS_CALIB"/"kmos_solar_hk_1100.fits
elif [ $gratingUpper == "K" ]; then
    fnSolarSpec=$KMOS_CALIB"/"kmos_solar_k_1700.fits
fi

echo "$fnAtmosModel         ATMOS_MODEL" >> $sofFile

if [ -n "$fnSolarSpec" ]; then
    echo "$fnSolarSpec         SOLAR_SPEC" >> $sofFile
fi

# add band-specific calibration frames
fnXcal=xcal_$gratingUpper$gratingUpper$gratingUpper.fits
fnYcal=ycal_$gratingUpper$gratingUpper$gratingUpper.fits
fnLcal=lcal_$gratingUpper$gratingUpper$gratingUpper.fits
fnMasterFlat=master_flat_$gratingUpper$gratingUpper$gratingUpper.fits
fnIllumCorr=illum_corr_$gratingUpper$gratingUpper$gratingUpper.fits

if [ ! -e $fnXcal ]; then
    fnXcal=$KMOS_CALIB"/"$fnXcal
fi
if [ ! -e $fnYcal ]; then
    fnYcal=$KMOS_CALIB"/"$fnYcal
fi
if [ ! -e $fnLcal ]; then
    fnLcal=$KMOS_CALIB"/"$fnLcal
fi
if [ ! -e $fnMasterFlat ]; then
    fnMasterFlat=$KMOS_CALIB"/"$fnMasterFlat
fi
if [ ! -e $fnIllumCorr ]; then
    fnIllumCorr=$KMOS_CALIB"/"$fnIllumCorr
fi

echo "$fnXcal             XCAL" >> $sofFile
echo "$fnYcal             YCAL" >> $sofFile
echo "$fnLcal             LCAL" >> $sofFile
echo "$fnMasterFlat      MASTER_FLAT" >> $sofFile
if [ -e $fnIllumCorr ]; then
    echo "$fnIllumCorr      ILLUM_CORR" >> $sofFile
fi

echo ""
echo "${bb}-------------------- easySPARK_std_star -----------------------${nn}"
echo "${bb}INPUT${nn}"
echo "filename:  "$fileName
echo "with "
echo "TPL.START: "$tplStartTime
echo "GRATING:   "$gratingUpper
echo ""
echo "${bb}OUTPUT${nn}"
echo $sofFile" with:"
cat $sofFile
echo ""

# execute kmo_std_star
if [ $sofOnly = 0 ]; then
    echo "${bb}NOW CALCULATING STANDARD STAR:${nn}"
    echo "esorex kmo_std_star "$sofFile

    esorex kmo_std_star $sofFile
fi
echo "${bb}----------------------------------------------------------${nn}"
