#!/bin/csh

# Set up the environment you will use for the running
source /work/halld/home/mstaib/builds/sim-recon/Linux_CentOS6-x86_64-gcc4.4.7/setenv.csh
setenv JANA_RESOURCE_DIR `pwd`

# Set up correct python version
setenv PATH  /apps/python/bin/:$PATH
setenv LD_LIBRARY_PATH ${LD_LIBRARY_PATH}:/apps/python/lib/

#The following arguments are specified at runtime
# $1 -> Plugin names
# $2 -> Options
# $3 -> Run Number
# $4 -> Number of threads

# The list of local filenames will be passed as first argument to this script
#
#set options="-PEVIO:ENABLE_DISENTANGLING=0 -PJANA:BATCH_MODE=1 -PNTHREADS=4 -PHLDETECTORTIMING:DO_FITS=0 "

# Copy over the CCDB (Use the automatically created one as a default) 
#wget --no-check-certificate -nc https://halldweb1.jlab.org/dist/ccdb.sqlite
echo "Copying CCDB sqlite"
#cp /work/halld/home/mstaib/TimingJobs/ccdb.sqlite .
cp /group/halld/www/halldweb/html/dist/ccdb.sqlite .
#setenv CCDB_CONNECTION sqlite:///`pwd`/ccdb.sqlite
#setenv JANA_CALIB_URL sqlite:///`pwd`/ccdb.sqlite

echo "Copying input File"
# Copy the input file locally
set evioFilename=`ls *.evio`
rm $evioFilename
cp `find /cache/mss/halld/ -name "*$evioFilename"` ./$evioFilename 
echo "Copy completed, running hd_root"

set Complete=0
set Counter=0
while ( $Complete == 0 && $Counter < 2 ) # Counter allows there to be one relaunch in case the first attempt crashes and fails horribly
    @ Counter += 1
    hd_root -PPLUGINS=$1 $2 -PNTHREADS=$4 $evioFilename
    if ( `stat -c %s hd_root.root` > 2000 ) then
        echo Step completed
        set Complete=1
    else
        echo Step failed...Trying again
    endif
end

exit
