#!/bin/sh
#
# ========================================================================
#
# *
# * This file is part of MARS, the MAGIC Analysis and Reconstruction
# * Software. It is distributed to you in the hope that it can be a useful
# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
# * It is distributed WITHOUT ANY WARRANTY.
# *
# * Permission to use, copy, modify and distribute this software and its
# * documentation for any purpose is hereby granted without fee,
# * provided that the above copyright notice appear in all copies and
# * that both that copyright notice and this permission notice appear
# * in supporting documentation. It is provided "as is" without express
# * or implied warranty.
# *
#
#
#   Author(s): Daniela Dorner  10/2006 <mailto:dorner@astro.uni-wuerzburg.de>
#
#   Copyright: MAGIC Software Development, 2000-2006
#
#
# ========================================================================
#
#
#
##############################################################################
#
# This script can be used to run the following steps for one sequence:
#  - callisto
#  - merppupdate
#  - star
#
# You have to set the path, where your Mars version can be found, the outpath,
# where you want to store the output and the sequencenumber of the sequence
# you want to process
# 
##############################################################################

#to be set by the user (if you don't use the command-line options)
#path of your output directory
#outpath=/home/dorner/ToO
outpath=
#give either sequence number or sequence file (including path)
sequence=
sequfile=""

function usage()
{
   echo "Usage: $0 [options]"
   echo "options:"
   echo -n "  --sequ sequence#       "
   echo " giving number of sequence which shall be processed "
   echo -n "  --sequ-file sequfile   "
   echo " giving sequencfile (including path) of sequence which shall be processed "
   echo -n "  --out outpath          "
   echo " giving the path where all outputfiles are stored "
   echo -n "  -cal                   "
   echo " running only calibration"
   echo -n "  -b                     "
   echo " running in non-interactive mode (i.e. you are not asked if the paths are ok)"
   echo -n "  -star                  "
   echo " running only star"
   echo ""
   echo "Remarks: "
   echo    " - you can set the variables (or part of it) also in the script "
   echo    " - you have to set the outpath and either the sequence number or the sequence file"
   echo    "    (if both is set, the sequence given by the sequencefile is processed)"
   echo "" 
   exit
}

interactive="yes"

while [ "$1" ]
do 
   case $1 in 
           --sequ)  shift
                    sequence=$1
                    ;;
           --mars)  shift
                    mars=$1
                    ;;
            --out)  shift
                    outpath=$1
                    ;;
               -b)  interactive='no'
                    ;;
             -cal)  cal='yes'
                    ;;
            -star)  star='yes'
                    ;;
      --sequ-file)  shift
                    sequfile=$1
                    ;;
               -h)  usage
                    ;;
      *)      echo "unknown option $1 "
              usage
              exit
              ;;
   esac
   shift
done

if [ "$outpath" = "" ]
then
   echo "WARNING outpath has not been set"
   echo ""
   usage
fi

if [ "$sequence" = "" ] && [ "$sequfile" = "" ]
then
   echo "WARNING neither sequ nor sequfile has been set"
   echo ""
   usage
fi

echo ""
echo "You have set the variables to: "
echo " outpath:  "$outpath

if [ "$sequfile" = "" ]
then 
   if ! n8=`printf %08d $sequence`
   then
      echo "your sequence number is not valid"
      usage
      exit
   fi
   no=`echo $n8 | cut -c 1-4`
   sequfile="/magic/sequences/"$no"/sequence$n8.txt"
   echo " sequence: "$sequence
   echo " sequfile: "$sequfile
   if ! [ "$star" = "yes" ] || [ "$cal" = "yes" ]
   then 
      calpath=$outpath"/callisto/$n8"
      echo " path where calibration files are stored : "$calpath
   fi
   if ! [ "$cal" = "yes" ] || [ "$star" = "yes" ]
   then 
      starpath=$outpath"/star/$n8"
      echo " path where star files are stored        : "$starpath
   fi
else
   echo " sequfile: "$sequfile
   if ! [ "$star" = "yes" ] || [ "$cal" = "yes" ]
   then 
      calpath=$outpath"/callisto"
      echo " path where calibration files are stored : "$calpath
   fi
   if ! [ "$cal" = "yes" ] || [ "$star" = "yes" ]
   then 
      starpath=$outpath"/star"
      echo " path where star files are stored        : "$starpath
   fi
fi


if [ "$interactive" = "yes" ]
then 
   echo ""
   echo "paths ok? continue?"
   echo "please insert y, if you want continue"
   echo "              n, if you want quit"

   answer=`head -n 1`
   case $answer in
      y) echo "continue processing sequence"
         ;;
      n) exit
         ;;
      *) echo "your answer is not clear -> exit"
         exit
         ;;
   esac
fi


if ! [ "$star" = "yes" ] || [ "$cal" = "yes" ]
then 
   mkdir -pv $calpath

   echo "run callisto..."
   echo "./callisto -b -q -f --log=$calpath/callisto$sequence.log --out=$calpath $sequfile "
   ./callisto -b -q -f --log=$calpath/callisto$sequence.log --out=$calpath $sequfile 
   check=$?
   case $check in 
      0)  echo "callisto finished sucessfully"
          echo "";;
      *)  echo -n "ERROR: callisto returned $check - please check "
          echo -n "http://www.astro.uni-wuerzburg.de/datacenter/instructions/intern/errorcoding.txt"
          echo " for more details"
          exit;;
   esac


   calfiles=`find $calpath -name [2][0][0-2][0-9][0,1][0-9][0-3][0-9]_*_Y_*.root`

   echo "run merpp update for calibrated files..."
   echo "calibrated data files: "$calfiles

   for calfile in ${calfiles[@]}
   do
      echo "calfile: "$calfile
      outpath=`dirname $calfile`
      echo "outpath: "$outpath

      merpplogpath=$outpath"/merpplogs"
      mkdir -pv $merpplogpath

      runno=`echo $calfile | cut -d_ -f2 | sed -e 's/^0//' | sed -e 's/^0//' | sed -e 's/^0//' `
      ccfile=`find /magic/subsystemdata/cc/ -name [2][0][0-2][0-9][0,1][0-9][0-3][0-9]_*${runno}_[P,D,C,S]_*_S.rep`
      cacofile=`find /magic/subsystemdata/caco/ -name dc_[2][0][0-2][0-9]_[0,1][0-9]_[0-3][0-9]_*${runno}_*.txt`
      echo "runno: "$runno
      echo "ccfile: "$ccfile
      if [ "$ccfile" = "" ]
      then
         echo "no ccfile found for run "$runno
         break
      fi
      echo "cacofile: "$cacofile
      if [ "$cacofile" = "" ]
      then
         echo "no cacofile found for run "$runno
         echo "finding cacofile..."
         for (( i = 0; i <= 10; i++ ))
         do
            newrun=`echo $runno - $i | bc`
     #      echo "$missingcacorun + $i = $newrun"
            path=`dirname $ccfile`
            path=`echo $path | sed -e 's/cc/caco/'`
            echo "path: "$path
            cacofile=`find $path -name *$newrun*`
            if [ "$cacofile" = "" ]
            then
               continue
            else
               break
               echo "cacofile: "$cacofile
            fi
         done
      fi
      
      logfile=$merpplogpath/merppccupdate$runno.log
      echo "./merpp -u --log=$logfile --runfile=$runno $ccfile $calfile "
      ./merpp -u --log=$logfile --runfile=$runno $ccfile $calfile
      check=$?
      case $check in
         0)  ;;
         *)  echo "ERROR: merppccupdate returned $check "
             echo "please check the logfile $logfile "
             exit;;
      esac

      logfile=$merpplogpath/merppcacoupdate$runno.log
      echo "./merpp -u --log=$logfile --auto-time $cacofile $calfile "
      ./merpp -u --log=$logfile --auto-time $cacofile $calfile
      check=$?
      case $check in
         0)  ;;
         *)  echo "ERROR: merppcacoupdate returned $check "
             echo "please check the logfile $logfile "
             exit;;
      esac
   done
   echo "merppupdate is finished"
   echo ""
fi

if ! [ "$cal" = "yes" ] || [ "$star" = "yes" ]
then 
   mkdir -pv $starpath

   echo "run star..."
   logfile=$starpath/star$sequence.log
   if ! ls $calpath
   then 
      echo "couldn't find $calpath => taking standard inpath for star"
      echo "./star -b -q -f --log=$logfile --out=$starpath $sequfile "
      ./star -b -q -f --log=$logfile --out=$starpath $sequfile
   else
      echo "./star -b -q -f --log=$logfile --ind=$calpath --out=$starpath $sequfile "
      ./star -b -q -f --log=$logfile --ind=$calpath --out=$starpath $sequfile
   fi
   check=$?
   case $check in 
      0)  echo "star finished sucessfully"
          echo "";;
      *)  echo "ERROR: star returned $check - please check "
          echo "please check the logfile $logfile "
          exit;;
   esac

   echo "star is finished "
fi

