#!/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_flat-recipe and executes it.${nn}"
   echo " "
   echo "${bb}IMPORTANT:${nn} Files can be searched as well in folders from +/- 1 day!"
   echo "           (if toplevel directories are e.g. named YYYY-MM-DD)"
   echo " "
   echo "- If a BADPIXEL_DARK frame isn't existing in the working directory"
   echo "  the environment variable ${bb}KMOS_CALIB${nn} pointing to a path has to be"
   echo "  set in order to find it."
   echo "  Otherwise the execution of this script will fail!"
   echo "- As argument an arbitrary exposure of an executed "
   echo "  ${bb}KMOS_spec_cal_calunitflat${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_flat.sh <filename with full path>"
   echo "    or"
   echo "  easySPARK_flat.sh <filename with full path> sof"
   echo " "
   echo "Version: "$EASY_VERSION
   echo "${bb}-------------------------------------------------------------------${nn}"
   exit
fi

howmany() {
   echo $#;
}

# return absolute pathname
my_realpath()
{
    local myresult=
    if [[ ! -e $1 && -h $1 ]]; then
        myresult=$(readlink $1)
    else
        myresult=$1
    fi

   echo "$myresult"
}

getdark()
{
    local __resultvar=$1
    local mydir=$2
    local auto_mode=$3

    local fn_BadPixelDark=
    local input=


    local all_darks=$(ls $mydir/badpixel_dark*)
    declare -a all_darks_arr=($all_darks)
    local size=$(howmany $all_darks)

    if [ $size == 0 ]; then
        echo "ERROR: Couldn't find any badpixel_dark*.fits in '$myDir'!"
        exit
    elif [ $size == 1 ]; then
        fn_BadPixelDark=$all_darks
    else
        if [ $auto_mode = 0 ]; then
            # no automode --> interactive
            echo "${bb}ATTENTION:${nn}"
            echo "Several badpixel_dark-frames have been found in directory '$mydir'!"
            echo "Select the one you want to use for calibration (normally EXPTIME = 10s and"
            echo "at least 3 exposures per set)"

            # print available badpixel_dark*.fits
            local setNr=1
            for i in $all_darks; do
               echo -e "$setNr\t"$i
               echo ""
               setNr=$[$setNr+1]
            done
            setNr=$[$setNr-1]

            # ask user which one to use
            read -p "Enter ID (1 to $setNr): " input
            while [[ $input -lt 1 || $input -gt $setNr ]]; do
                read -p "Enter ID (1 to $setNr): " input
            done

            fn_BadPixelDark=${all_darks_arr[$input-1]}
            unset all_darks_arr
        else
            # automode
            local arrsize=${#all_darks_arr[*]}
            local exptime=
            local st1=
            local st2=
            local found=0
            local ind=0

            while [[ $found = 0 && $ind -le $size ]]; do
                exptime=$(dfits ${all_darks_arr[$ind]} | fitsort -d det.seq1.dit | gawk '{print $2}')
                st1=`echo "$exptime <= 100" | bc`
                st2=`echo "$exptime >= 10" | bc`

                if [[ $found = 0 && $st1 = 1 && $st2 = 1 ]]; then
                    found=1
                else
                    ind=$[$ind+1]
                fi
            done
            fn_BadPixelDark=${all_darks_arr[$ind]}
        fi
    fi

    eval $__resultvar="'$fn_BadPixelDark'"
}

#init
sofOnly=0
automode=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 == auto ]]; then
            automode=1
        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

# 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

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

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

# analyze path, extract dates for today and yesterday            fileName:     # /<bla>/<blo>/2013-01-20/KMOS<xxx>
dataDir_today=$(dirname "$fileName")                                           # /<bla>/<blo>/2013-01-20
dataDir=${dataDir_today%/*}                                                    # /<bla>/<blo>/
today=${dataDir_today##*/}                                                     # 2013-01-20
matchingFiles=

date -d $today > /dev/null 2>&1
if [ $? = 0 ]; then
    # we have a directory like 2013-06-10
    yesterday=$(date --date=@$(( $(date --date=$today +%s) - 86400 )) +'%Y-%m-%d') # 2013-01-19
    dataDir_yesterday=$dataDir"/"$yesterday                                        # /<bla>/<blo>/2013-01-19
    tomorrow=$(date --date=@$(( $(date --date=$today +%s) + 86400 )) +'%Y-%m-%d')  # 2013-01-21
    dataDir_tomorrow=$dataDir"/"$tomorrow                                          # /<bla>/<blo>/2013-01-21

    # get all files with matching tplStartTime and FLAT_OFF from yesterday
    matchingFiles_yesterday=
    if [ -e $dataDir_yesterday ]; then
        matchingFiles_yesterday=$(dfits $dataDir_yesterday/KMOS*.fits | \
                                  fitsort -d tpl.start dpr.type |\
                                  grep $tplStartTime |\
                                  grep FLAT,OFF |\
                                  gawk '{print $1}' |\
                                  tr "\n" " ")
    fi

    # get all files with matching tplStartTime and FLAT_OFF from tomorrow
    matchingFiles_tomorrow=
    if [ -e $dataDir_tomorrow ]; then
        matchingFiles_tomorrow=$(dfits $dataDir_tomorrow/KMOS*.fits | \
                                 fitsort -d tpl.start dpr.type |\
                                 grep $tplStartTime |\
                                 grep FLAT,OFF |\
                                 gawk '{print $1}' |\
                                 tr "\n" " ")
    fi

    matchingFiles=$matchingFiles_yesterday$matchingFiles_tomorrow
fi

# get all files with matching tplStartTime and FLAT_OFF from today
if [ -e $dataDir_today ]; then
    if ls $dataDir_today/KMOS*.fits &> /dev/null; then
        matchingFiles_today=$(dfits $dataDir_today/KMOS*.fits | \
                              fitsort -d tpl.start dpr.type |\
                              grep $tplStartTime |\
                              grep FLAT,OFF |\
                              gawk '{print $1}' |\
                              tr "\n" " ")
        matchingFiles=$matchingFiles$matchingFiles_today
    fi
fi

# populate sof-file with FLAT_OFF frames
sofFile="flat_$tplStartTime.sof"
cat > $sofFile </dev/null
for file in $matchingFiles; do
    echo "$file   FLAT_OFF" >> $sofFile
done

# get all files with matching tplStartTime and FLAT_LAMP from yesterday
matchingFiles=
matchingFiles_yesterday=
matchingFiles_tomorrow=
matchingFiles_today=
date -d $today > /dev/null 2>&1
if [ $? = 0 ]; then
    # we have a directory like 2013-06-10
    if [ -e $dataDir_yesterday ]; then
        matchingFiles_yesterday=$(dfits $dataDir_yesterday/KMOS*.fits | \
                                  fitsort -d tpl.start dpr.type |\
                                  grep $tplStartTime |\
                                  grep FLAT,LAMP |\
                                  gawk '{print $1}' |\
                                  tr "\n" " ")
    fi

    # get all files with matching tplStartTime and FLAT_LAMP from tomorrow
    if [ -e $dataDir_tomorrow ]; then
        matchingFiles_tomorrow=$(dfits $dataDir_tomorrow/KMOS*.fits | \
                                 fitsort -d tpl.start dpr.type |\
                                 grep $tplStartTime |\
                                 grep FLAT,LAMP |\
                                 gawk '{print $1}' |\
                                 tr "\n" " ")
    fi

    matchingFiles=$matchingFiles_yesterday$matchingFiles_today$matchingFiles_tomorrow
fi

# get all files with matching tplStartTime and FLAT_LAMP  from today
if [ -e $dataDir_today ]; then
    if ls $dataDir_today/KMOS*.fits &> /dev/null; then
        matchingFiles_today=$(dfits $dataDir_today/KMOS*.fits | \
                              fitsort -d tpl.start dpr.type |\
                              grep $tplStartTime |\
                              grep FLAT,LAMP |\
                              gawk '{print $1}' |\
                              tr "\n" " ")
        matchingFiles=$matchingFiles$matchingFiles_today
    fi
fi

# get grating id of first FLAT_ON frame
gratingUpper=$(dfits $matchingFiles |\
               fitsort -d ins.grat1.id |\
               head -n1 |\
               gawk '{print $2}')
	       
# populate sof-file with FLAT_ON frames
for file in $matchingFiles; do
    echo "$file   FLAT_ON" >> $sofFile
done

# add BADPIXEL_DARK frame
fnBadPixelDark=
myDir="."

if ls $myDir"/"badpixel_dark* &> /dev/null; then
    # ./badpixel_dark*.fits existing
    getdark fnBadPixelDark $myDir $automode
else
    # no ./badpixel_dark*.fits existing
    myDir=$KMOS_CALIB
    if ls $myDir"/"badpixel_dark* &> /dev/null; then
        getdark fnBadPixelDark $myDir $automode
    else
        if [ -z "${KMOS_CALIB}" ]; then
           echo "ERROR: No badpixel_dark*.fits found!"
           echo "       Environment variable KMOS_CALIB is not defined! (see help,"
           echo "       this path could be searched as well)"
           exit
        else
            # just add badpixel_dark.fits as default
            fnBadPixelDark=badpixel_dark.fits
        fi
    fi
    fnBadPixelDark=$fnBadPixelDark
fi

#if [ ! -e $fnBadPixelDark ]; then
#    echo "ERROR: in $myDir no badpixel_dark*.fits could be found!"
#    exit
#fi

# readlink -f doesn't work on MacOS, but my_realpath() does exactly this?!?
#echo $(readlink -f $(my_realpath $fnBadPixelDark))"      BADPIXEL_DARK" >> $sofFile
echo $(my_realpath $fnBadPixelDark)"      BADPIXEL_DARK" >> $sofFile


echo ""
echo "${bb}---------------------- easySPARK_flat -------------------------${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_flat
if [ $sofOnly = 0 ]; then
   echo "${bb}NOW CALCULATING FLAT:${nn}"
   echo "esorex --suppress-prefix=TRUE kmo_flat "$sofFile

   esorex --suppress-prefix=TRUE kmo_flat $sofFile
fi    
echo "${bb}----------------------------------------------------------${nn}"
