#!/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  05/2007 <mailto:dorner@astro.uni-wuerzburg.de>
#
#   Copyright: MAGIC Software Development, 2000-2008
#
#
# ========================================================================
#
# This script runs corsika.
# 

source `dirname $0`/sourcefile
printprocesslog "INFO starting $0"
program=corsika
column=fCorsikaFileAvail

set -C

export FLUPRO=$corsikapath'/fluka2008_3'

# printing input card to stdout
function printinputcard()
{
   # Run number
   echo "RUNNR "$corsikarunno
   # Starting event number
   echo "EVTNR 1"
   # Number of simulated events
   echo "NSHOW "$numevts
   # Seed values for simulation
   echo "SEED "$seed1" 0 0 "
   echo "SEED "$seed2" 0 0 "
   echo "SEED "$seed3" 0 0 "
   # Primary particle
   echo "PRMPAR "$primparticle
   echo "ERANGE "$erange
   echo "ESLOPE "$slope
   # Simulation range (theta, phi, view cone, starting altitude)
   echo "THETAP "$zdrange
   echo "PHIP "$azrange
   echo "VIEWCONE 0. "$viewconemax
   echo "FIXCHI "$startalt
   # Observation level, magnetic field, atmosphere
   echo "OBSLEV 2200.E2"
   # From www.noaa.gov/geomagmodels roughly for January 2009. (was 29.5 and 23.0)
   # MAGNET BX BZ (BX is the horizontal component (muT) to the x-direction of
   # the detector, BZ is the vertical component (muT) downwards)
   echo "MAGNET 30.3 24.1"
   # Rotation angle between array x-direction and magnetic north direction
   # positive if array x-direction points to the west
   echo "ARRANG -7.0"
   # Atmosphere (model, true/false for atmospheric refraction of cer-photons)
   # Atmosphere read from atmprof11.dat
   # My current understanding is that only refraction (bending of light
   # but no absorption of photons is taken into account) setting T.
   echo "ATMOSPHERE 11 T"
   # Other parameters
   echo "RADNKG 200.E2"
   echo "ECUTS 0.3 0.3 0.02 0.02"
   echo "ECTMAP 1.E4"
   echo "STEPFC 0.1"
   # Don't add muon particle data to output
   echo "MUADDI F"
   # Enable muon multiple scattering
   echo "MUMULT T"
   # Cherenkov telescope options
   echo "CWAVLG 290. 600."
   echo "CSCAT "$reuse" 0. "$impactmax
   echo "CERSIZ 1."
   echo "CERFIL T"
   echo "CERTEL 1"
   echo " 0. 0. 0. 0. 0. "$diameter" 1700."
   # How the longitudinal shower development is sampled
   # echo "LONGI T 10. T F"
   echo "LONGI F 20 0 F F"
   # Maximum number of detailed particles to print
   echo "MAXPRT 0"
   # Suppress file with partciles reaching ground (DATnnnnnn)
   # FIXME: Should we make this switchable by the database?
   echo "PAROUT F F"
   # Don't write a database file
   echo "DATBAS F"
   # Switch off all debugging output
   echo "DEBUG F 6 F 1000000"
   # Output path
   echo "DIRECT "$outpath
   # User and host (for convinience)
   echo "USER "`whoami`
   echo "HOST "`hostname`
   # End of input card
   echo "EXIT"
}


# get sequence # 
gettodo "1" 
run=${primaries[0]}
# get corsika runno
query="SELECT fCorsikaRunNumber FROM MCRunData where fMCRunNumber="$run
# to be changed later again, when additional tables are available
#corsikarunno=`sendquery`
corsikarunno=$run

# lock sequ
lockfile=$lockpath/lock-$table-$column-$corsikarunno.txt
checklock 

printprocesslog "INFO starting $program for run $run"

setstatus "start" 

printprocesslog "INFO run $program for run $run " 
printprocesslog "INFO create input card... " 

# get values for inputcard
query="SELECT fParticleTypeKEY FROM MCCorsikaRunData where fCorsikaRunNumber="$corsikarunno
primparticle=`sendquery`
query="SELECT fEnergyMin, fEnergyMax FROM MCCorsikaRunData where fCorsikaRunNumber="$corsikarunno
erange=`sendquery`
query="SELECT fNumEvents FROM MCCorsikaRunData where fCorsikaRunNumber="$corsikarunno
numevts=`sendquery`
query="SELECT fEnergySlope FROM MCCorsikaRunData where fCorsikaRunNumber="$corsikarunno
slope=`sendquery`
query="SELECT fZenithDistanceMin, fZenithDistanceMax FROM MCCorsikaRunData where fCorsikaRunNumber="$corsikarunno
zdrange=`sendquery`
# Change from the MARS definition (Az=90 -> East) to Corsika (Az=90 -> West)
query="SELECT 180-fAzimuthMin, 180-fAzimuthMax FROM MCCorsikaRunData where fCorsikaRunNumber="$corsikarunno
azrange=`sendquery`
query="SELECT DATE_FORMAT(fRunStart, '%Y/%m/%d') FROM MCCorsikaRunData where fCorsikaRunNumber="$corsikarunno
date=`sendquery`
outpath=$mcpath"/"$program"/"$date
query="SELECT fCorsikaSeed FROM MCCorsikaRunData where fCorsikaRunNumber="$corsikarunno
seed1=`sendquery`
query="SELECT fCorsikaSeed+1 FROM MCCorsikaRunData where fCorsikaRunNumber="$corsikarunno
seed2=`sendquery`
query="SELECT fCorsikaSeed+2 FROM MCCorsikaRunData where fCorsikaRunNumber="$corsikarunno
seed3=`sendquery`
query="SELECT fImpactMax FROM MCCorsikaRunData where fCorsikaRunNumber="$corsikarunno
impactmax=`sendquery`
query="SELECT fViewConeMax FROM MCCorsikaRunData where fCorsikaRunNumber="$corsikarunno
viewconemax=`sendquery`
query="SELECT fNumReUseShower FROM MCCorsikaRunData where fCorsikaRunNumber="$corsikarunno
reuse=`sendquery`
query="SELECT fStartingAltitude FROM MCCorsikaRunData where fCorsikaRunNumber="$corsikarunno
startalt=`sendquery`
query="SELECT fMirrorDiameter FROM MCCorsikaRunData where fCorsikaRunNumber="$corsikarunno
diameter=`sendquery`

logfile=$outpath/$program"-"`printf %06d $corsikarunno`".log"
makedir $outpath 

cd $corsikapath

echo "INPUTCARD:" >| $logfile 2>&1
printinputcard >> $logfile 2>&1
echo "" >> $logfile 2>&1
echo "" >> $logfile 2>&1
printinputcard | ./cc6501p-linux >> $logfile 2>&1

rm -f $outpath/dat`printf %06d $corsikarunno`

check1=$?

case $check1 in
   0)   printprocesslog "INFO $program finished successfully for corsika run number $corsikarunno (check1=$check1)"
        ;;
   *)   printprocesslog "ERROR $program failed for corsika run number $corsikarunno (check1=$check1)"
        com=$Fcorsika
        check=$check1
        ;;
esac

setstatus "stop" 

finish 

