#!/bin/tcsh -f

# This script is to be run by farm jobs. It will produce 
# ROOT files using the event_size and level1_trigger plugins
# to fill in a tree with the number of hits for each detector.
# It also has the number of digitized values for the event.
#
# The JOB_ID environment variable
# is assumed to be set. If it is not, then a default of
# "1234" is used.
#

set workdir=/work/halld/home/davidl/2012.12.06.cpp_acceptance

set Z_TARGET=$1

# If running interactively from the command-line then
# JOB_ID won't be set. Check for this and set it if needed.
if ( ! $?JOB_ID ) then 
	setenv JOB_ID 1234
	mkdir -p tmp${JOB_ID}  # use subdirectory if running from command line
	cd tmp${JOB_ID}
endif
setenv JOB_ID `basename $JOB_ID .farmpbs.jlab.org`

if ( ! $?JOBNAME ) then 
	setenv JOBNAME OUTPUT.1
endif


# Create unique prefix for filenames associated with this job
set prefix=JOB${JOB_ID}

# Setup environment and pointers to specific executables
source ${workdir}/setenv.csh
set genr8_2_hddm=${HALLD_HOME}/bin/${BMS_OSNAME}/genr8_2_hddm
set hdgeant=${HALLD_MY}/bin/${BMS_OSNAME}/hdgeant
set mcsmear=${HALLD_HOME}/bin/${BMS_OSNAME}/mcsmear
set hd_root=${HALLD_HOME}/bin/${BMS_OSNAME}/hd_root

# Output disk to copy files to 
set outdir=${workdir}/${JOBNAME};
mkdir -p $outdir/logs
env > $outdir/logs/${prefix}.env

# Link (symbolic) control.in file
rm -f control.in
ln -s ${workdir}/farm/control.in control.in

# Link (symbolic) jana.conf file
rm -f jana.conf
ln -s ${workdir}/farm/jana.conf jana.conf

# Copy XML geometry and modify it for this job
cp -r ${workdir}/farm/XML_GEOM .
cat XML_GEOM/main_HDDS.xml | sed -e s/Z_TARGET/$Z_TARGET/g > XML_GEOM/tmp.xml
mv XML_GEOM/tmp.xml XML_GEOM/main_HDDS.xml

# Archive geometry
mkdir -p $outdir/geom
tar czf $outdir/geom/geom_${prefix}.tgz XML_GEOM

####################### Run genr8_2_hddm ##################################
#
set logfile=${outdir}/logs/${prefix}_genr8_2_hddm.log
echo "genr8_2_hddm output redirected to log file: $logfile"
${genr8_2_hddm} -V"0 0 $Z_TARGET $Z_TARGET" ${workdir}/2pi.ascii >& $logfile
mv output.hddm 2pi.hddm

####################### Run hdgeant ##################################
#
set logfile=${outdir}/logs/${prefix}_hdgeant.log
echo "hdgeant output redirected to log file: $logfile"
${hdgeant} -xml=$PWD/XML_GEOM/main_HDDS.xml >& $logfile

####################### Run mcsmear ############################
#
set logfile=${outdir}/logs/${prefix}_mcsmear.log
echo "mcsmear output redirected to log file: $logfile"
${mcsmear} hdgeant.hddm >& $logfile

####################### Run hdroot  ############################
#
set logfile=${outdir}/logs/${prefix}_hd_root.log
echo "hd_root output redirected to log file: $logfile"
time ${hd_root} hdgeant_smeared.hddm --config=jana.conf -o z${Z_TARGET}.root >& $logfile
cp z${Z_TARGET}.root $outdir



