#!/bin/tcsh

# This job will use the particle gun built in to hdgeant to thrown
# 10k single pi+ events at several discrete momenta over a range
# of angles in theta and phi.

# Setup working directory on Hall-D work disk
if ( -e /work/halld/NightlyTests ) then
	cd /work/halld/NightlyTests
else
	echo "/work/halld/NightlyTests not found. Using current directory."
endif
rm -rf Test2.previous
if( -e Test2 ) then
	mv Test2 Test2.previous
endif
mkdir Test2
cd Test2
cp -r /group/halld/Software/scripts/NightlyTest2/* .


# Create output.log file
echo "Output for" `date` > output.log
echo " " >> output.log
hostname >> output.log
test -r /proc/cpuinfo && cat /proc/cpuinfo > cpuinfo.log


# Dump environment 
env > env.log

# Confirm required executables exist
set HDGEANT=${HALLD_HOME}/bin/${OSNAME}/hdgeant
set HDROOT=${HALLD_HOME}/bin/${OSNAME}/hd_root
if( ! -e ${HDGEANT} ) then
	echo "${HDGEANT} does not exist \!\!" >> output.log
	exit
endif
if( ! -e ${HDROOT} ) then
	echo "${HDROOT} does not exist \!\!" >> output.log
	exit
endif

# Link resolution file that will be used by hd_root below
ln -s ${HALLD_HOME}/src/programs/Simulation/HDParSim/hd_res_charged.root .

# Loop over momenta
foreach s (0.2 0.5 1.0 2.0 3.0)

	# Copy the control.in.tmpl file to control.in replacing the
	# XXX string with the momentum for this loop
	rm -f control.in
	cat control.in.tmpl | sed -e s/XXX/$s/g > control.in

	# Run hdgeant
	set cmd="${HDGEANT}"
	echo "Running hdgeant ..." >> output.log
	echo "$cmd" >> output.log
	echo " " >> output.log
	$cmd >& hdgeant.log

	# Run HDROOT
	unsetenv JANA_PLUGIN_DIR
	setenv JANA_PLUGIN_PATH ${HALLD_HOME}/lib/${OSNAME}
	set cmd="${HDROOT} --plugin=trackeff_hists2 hdgeant_p${s}.hddm -o hd_root_p${s}.root"
	echo "Running hd_root ..." >> output.log
	echo "$cmd" >> output.log
	echo " " >> output.log
	$cmd >& hd_root_p${s}.log

end # end loop over momenta

# Run ROOT macro to create gif files
set cmd="root -b -q nightly2.C"
echo "Running root ..." >> output.log
echo "$cmd" >> output.log
echo " " >> output.log
$cmd >& root.log

# Put all GIF files in an e-mail and send it
set uucmds=""
foreach s (*.gif)
	set tmp="${uucmds}"
	set uucmds="${tmp} uuencode ${s} ${s}; "
end
set tmp="${cmd}"
set cmd="( echo "'"'"Auto-generated plots from NightlyTest2"'"'"; ${uucmds} ) | mail -s "'"'"Testing..."'"'" davidl@jlab.org"
eval $cmd >> output.log

echo " Done." >> output.log
