#!/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  12/2005 <mailto:dorner@astro.uni-wuerzburg.de>
#
#   Copyright: MAGIC Software Development, 2000-2007
#
#
# ========================================================================
#
# This script is an intermediate solution to process the montecarlo files.
# As soon as the montecarlo database is running, this script shall be 
# exchanged. 
# 
# The script is building one sequence per directory. As the files are 
# structured by condition, the files in one directory and such in one 
# sequence have the same observation mode, psf, zbin, ... 
# 

source `dirname $0`/sourcefile
printprocesslog "INFO starting $0"
program=mcsequences

set -C

scriptlog=$runlogpath/$program-$datetime.log
date >> $scriptlog 2>&1

# check if script is already running
lockfile=$lockpath/lock-$program.txt
checklock  >> $scriptlog 2>&1

# find montecarlo directories, build one sequence per directory and write sequence file
printprocesslog "INFO building one sequence per mcdirectory and epoch"

user="test"
db="TestMonteCarlo"
pw="Ics+eaTD"

dirs=`find $mcrawpath -type d`
for dir in ${dirs[@]}
do 
   cont=`echo $dir | cut -d/ -f6`
#   cont=`echo $dir | cut -d/ -f10`
   if [ "$cont" == "" ]
   then
      continue
   fi
   echo $dir >> $scriptlog 2>&1
   
   epochs=`ls -l $mcpath/camera | cut -c 52-70`
   for epoch in ${epochs[@]}
   do
      echo $epoch >> $scriptlog 2>&1
      calfile=`find $dir -lname *${epoch}/*.root | grep "_C_"`
      pedfile=`find $dir -lname *${epoch}/*.root | grep "_P_"`
      
      calrun=`echo $calfile | cut -d_ -f2`
      pedrun=`echo $pedfile | cut -d_ -f2`
      
      modes=("Gamma" "GammaW1" "GammaW2" "GammaFW" "GammaDiff" "GammaHE" "GammaHEW1" "GammaHEW2" "GammaHEFW" "GammaHEDiff" "ProtonDiff" "ProtonHEDiff" "MuonDiff" "MuonHEDiff")
      for mode in ${modes[@]}
      do
         datruns=`find $dir -lname *${epoch}/*.root | grep ${mode}_ | grep "_D_" | cut -d_ -f2 | tr "\n" " "`
      	 if [ "$datruns" != "" ]
         then
      	    firstrun=`echo $datruns | cut -c 0-8`
            date=`echo $dir | cut -c 28-37 | sed -e 's/\//-/g'`
            #date=`echo $dir | cut -c 57-66 | sed -e 's/\//-/g'`
            zbin=`echo $date | cut -c 3,4`
   	    
            for datrun in ${datruns[@]}
            do
               update=" update MCRunData set fSequenceFirst=\"$firstrun\" where fRunNumber=\"$datrun\" "
   	       mysql -ss -u $user --password=$pw --host=vela $db -e " $update "
            done   

            query=" select fSpectrumKEY, fPSFKEY, fAmplFadcKEY, fAtmosphericModelKEY, fObservationModeKEY, fMCParticleKEY, fReflectorVersionKEY, fCorsikaVersionKEY, fCameraVersionKEY, fViewConeAngleOKEY from MCRunData where fRunNumber=\"$firstrun\" "
            values=`mysql -ss -u $user --password=$pw --host=vela $db -e " $query "`
            spec=`echo $values | cut -d" " -f1`
            psf=`echo $values | cut -d" " -f2`
            amplfadc=`echo $values | cut -d" " -f3`
            atmo=`echo $values | cut -d" " -f4`
            obs=`echo $values | cut -d" " -f5`
            part=`echo $values | cut -d" " -f6`
            refl=`echo $values | cut -d" " -f7`
            cors=`echo $values | cut -d" " -f8`
            cam=`echo $values | cut -d" " -f9`
            view=`echo $values | cut -d" " -f10`
   	    query1=" select fSequenceFirst from MCSequenceProcessStatus where fSequenceFirst=\"$firstrun\" "
   	    query2=" select fSequenceFirst from MCSequences where fSequenceFirst=\"$firstrun\" "
   	    check1=`mysql -ss -u $user --password=$pw --host=vela $db -e " $query1 "`
   	    check2=`mysql -ss -u $user --password=$pw --host=vela $db -e " $query2 "`
   	    insert1=" insert MCSequenceProcessStatus set fSequenceFirst=\"$firstrun\", fSequenceFileWritten=Now() "
   	    insert2=" insert MCSequences set fSequenceFirst=\"$firstrun\", fRunStart=\"$date\", fZBin=\"$zbin\", fSpectrumKEY=\"$spec\", fPSFKEY=\"$psf\", fAmplFadcKEY=\"$amplfadc\", fAtmosphericModelKEY=\"$atmo\", fObservationModeKEY=\"$obs\", fMCParticleKEY=\"$part\", fReflectorVersionKEY=\"$refl\", fCorsikaVersionKEY=\"$cors\", fCameraVersionKEY=\"$cam\", fViewConeAngleOKEY=\"$view\" "
            update2=" update MCSequences set fRunStart=\"$date\", fZBin=\"$zbin\", fSpectrumKEY=\"$spec\", fPSFKEY=\"$psf\", fAmplFadcKEY=\"$amplfadc\", fAtmosphericModelKEY=\"$atmo\", fObservationModeKEY=\"$obs\", fMCParticleKEY=\"$part\", fReflectorVersionKEY=\"$refl\", fCorsikaVersionKEY=\"$cors\", fCameraVersionKEY=\"$cam\", fViewConeAngleOKEY=\"$view\" where fSequenceFirst=\"$firstrun\" "
            if [ "$check1" == "" ]
            then
               mysql -ss -u $user --password=$pw --host=vela $db -e " $insert1 "
            fi
            if [ "$check2" == "" ]
            then
   	       mysql -ss -u $user --password=$pw --host=vela $db -e " $insert2 "
            else
   	       mysql -ss -u $user --password=$pw --host=vela $db -e " $update2 "
            fi
            
            no=`echo $firstrun | cut -c 0-4`
            sequpath=$mcsequpath/$no
            makedir $sequpath >> $scriptlog 2>&1
            sequfile=$sequpath/sequence$firstrun.txt
            echo "writing sequfile "$sequfile >> $scriptlog 2>&1
            printprocesslog "INFO writing sequencefile $sequfile"
   
            echo "Sequence:        $firstrun" >| $sequfile
            echo "Night:           $date" >> $sequfile
            echo "Epoch:           $epoch" >> $sequfile
            echo "Mode:            $mode" >> $sequfile
            echo "" >> $sequfile
            echo "CalRuns:         $calrun" >> $sequfile
            echo "PedRuns:         $pedrun" >> $sequfile
            echo "DatRuns:         $datruns" >> $sequfile
 	    echo "" >> $sequfile
            echo "MonteCarlo: Yes" >> $sequfile
   	    echo "" >> $sequfile
         fi
      done
   done
done

finish >> $scriptlog 2>&1

