#!/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_reconstruct-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 "  Otherwise the execution of this script will fail!"
   echo "- If XCAL, YCAL and LCAL frames aren't existing in the working"
   echo "  directory the script is searching as well KMOS_CALIB in order to find them."
   echo "- As argument(s) one or more files have to be provided."
   echo "- (Optional) The reconstruction method can be provided."
   echo "  It must either be NN, lwNN, swNN or CS (default: CS)"
   echo "- (Optional) If as additional argument ${bb}sof${nn} is provided, then only"
   echo "  the sof-file is generated but not executed."
   echo " "
   echo "${bb}Usage:${nn}"
   echo "  easySPARK_reconstruct.sh <FILENAME(s)>"
   echo "    or"
   echo "  easySPARK_reconstruct.sh <FILENAME(s)> <METHOD>"
   echo "    or"
   echo "  easySPARK_reconstruct.sh <FILENAME(s)> <METHOD> sof"
   echo "    or"
   echo "  easySPARK_reconstruct.sh <FILENAME(s)> sof"
   echo " "
   echo "Version: "$EASY_VERSION
   echo "${bb}-------------------------------------------------------------------${nn}"
   exit
fi

# init
sofOnly=0
nrAllFiles=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

      allFiles[$nrAllFiles]=$1
      nrAllFiles=$[$nrAllFiles+1]
   else
      if [[ $tmp == CS || $tmp == NN || $tmp == lwNN || $tmp == swNN ]]; then
         imethodString=" --imethod=$tmp "
         imethod=$tmp
      elif [[ $tmp == sof ]]; then
         sofOnly=1
      elif [[ $tmp == vers ]]; then
         printVers=1
      fi
   fi
   shift
done

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

if [ -z "${KMOS_CALIB}" ]; then
   echo "${bb}ERROR:${nn} environment variable KMOS_CALIB is not defined! (see help)"
   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 [ $nrAllFiles = 0 ]; then
   echo "${bb}ERROR:${nn} No valid file(s) provided!"
fi

for file in ${allFiles[*]}; do
   
   # get keys from header keywords
   gratingUpper=$(dfits $file |\
                  fitsort -d ins.grat1.id |\
                  gawk '{print $2}')
   gratingLower=$(echo $gratingUpper|tr "A-Z" "a-z")
   
   rotAngle=$(dfits $file |\
              fitsort -d ocs.rot.naangle |\
              gawk '{print $2}')

   # strip & split filename
   fileNameBase=$(basename "$file")       #KMOS_SPEC_TEC327_0001.fits
   fileNameBase="${fileNameBase%.*}"      #KMOS_SPEC_TEC327_0001
   separator=${fileNameBase:4:1}               #TEC327_0001
   obsId=
   if [ $separator == "_" ]; then
       obsId=${fileNameBase:10}               #TEC327_0001
   else
       obsId=${fileNameBase:5}               #2013-01-29T09:48:56.439
   fi

   # create sof-filename
   sofFile="reconstruct_"$obsId".sof"

   fnXcal=xcal_$gratingUpper$gratingUpper$gratingUpper.fits
   fnYcal=ycal_$gratingUpper$gratingUpper$gratingUpper.fits
   fnLcal=lcal_$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

   # extract TPL.ID of ths file
   tplId=$(dfits $file |\
           fitsort -d tpl.id |\
           gawk '{print $2}')

   if [ $tplId = "KMOS_spec_cal_dark" ]; then
      category="DARK"
   else
      category="OBJECT"
   fi

   # create sof-file                  
   echo "$file        $category" > $sofFile
   echo "$fnXcal      XCAL" >> $sofFile
   echo "$fnYcal      YCAL" >> $sofFile
   echo "$fnLcal      LCAL" >> $sofFile
   echo "$KMOS_CALIB/kmos_wave_band.fits      WAVE_BAND" >> $sofFile
   echo "$KMOS_CALIB/kmos_oh_spec_$gratingLower.fits    OH_SPEC" >> $sofFile
   
   echo ""
   echo "${bb}-------------------- easySPARK_reconstruct --------------------${nn}"
   echo "${bb}INPUT${nn}"
   echo "filename:  "$file
   echo "with "
   echo "GRATING:   "$gratingUpper
   echo ""
   echo "${bb}OUTPUT${nn}"
   echo $sofFile" with:"
   cat $sofFile
   echo ""

   # execute kmo_reconstruct
   if [ $sofOnly = 0 ]; then
      echo "${bb}NOW START RECONSTRUCTION:${nn}"
      echo "esorex kmo_reconstruct "$imethodString $sofFile
      
      esorex kmo_reconstruct $imethodString $sofFile
      
      if [ $? = 0 ]; then
         # move output to unique name
         if [ -z "${imethod}" ]; then
            if [ $tplId = "KMOS_spec_cal_dark" ]; then
               mv "cube_dark.fits"  "cube_"$obsId".fits"
            else
               mv "cube_object.fits"  "cube_"$obsId".fits"
            fi
         else
            if [ $tplId = "KMOS_spec_cal_dark" ]; then
               mv "cube_dark.fits"  "cube_"$obsId"_"$imethod".fits"
            else
               mv "cube_object.fits"  "cube_"$obsId"_"$imethod".fits"
            fi
         fi
         echo "SUCCESS"
      else
         echo "FAILURE"
	 exit
      fi      
   fi
   echo "${bb}----------------------------------------------------------${nn}"
done  # for (allFiles)
