#!/bin/csh
#usage: g4bl_wrap.csh <G4BLversion> <input deck> <FirstParticle> <LastParticle> <HomeSEID> <RunID>

if ( ${#argv} < 6) then
        echo "Insufficient arguments"
        exit 1
endif

#Arguments
set G4BLVER="$1"
set IN_DECK="$2"
set PRTCL_F=$3
set PRTCL_T=$4
set MICE_HOME_SEID="$5"
set SIML_ID="$6"

# Logging data
echo "Running on `hostname -f`"
echo "as user: ${USER}"
echo "Processor - `cat /proc/cpuinfo |grep 'model name'`"
echo "Physical memory - `cat /proc/meminfo | grep 'MemTotal'`"
set PHYS_MEM=`cat /proc/meminfo | grep "MemTotal:" | cut -c 14-23`
echo "Physical memory (${PHYS_MEM}): `expr ${PHYS_MEM} / 1048576` MB"
echo
#was echo "Grid job: ${EDG_WL_JOBID} "
echo "Grid job: ${GLITE_WMS_JOBID} "
echo "running at: ${SITE_NAME} on CE: ${GLOBUS_CE}"
if ( ${?PBS_JOBID} ) then
	echo "Job spooled by PBS as: ${PBS_JOBID} in queue: ${PBS_QUEUE}"
else if ( ${?SGE_ACCOUNT} ) then
	echo "Job spooled by SGE as: ${JOB_ID}"
else if ( ${?LSB_JOBNAME} ) then
	echo "Job spooled by LSF as: ${LSB_JOBID}/${LSB_JOBNAME} in queue: ${LSB_QUEUE}
else 
	echo "Job spooled by Condor, BQS etc. - no info"
endif
echo ; echo ;
echo "Input deck:"
echo "-----------------------------------------"
cat ${IN_DECK}
echo "-----------------------------------------"
echo ; echo ;

setenv LFC_HOST lfc.gridpp.rl.ac.uk
set MICE_GRID_PWD="/grid/mice/users/Nebrensky/LFCTest"
set CMDLINE="${VO_MICE_SW_DIR}/g4beamline-${G4BLVER}/bin/g4bl ${IN_DECK} first=${PRTCL_F} last=${PRTCL_T} viewer=none"

# G4beamline Setup:
ln -s ${VO_MICE_SW_DIR}/MICE/Magnets Magnets
ln -s ${VO_MICE_SW_DIR}/MICE/Maps Maps
ln -s ${VO_MICE_SW_DIR}/MICE/Windows Windows
#TargetModel

# Run
#setenv ROOTSYS /usr/local
setenv ROOTSYS ${VO_MICE_SW_DIR}/gcc3.2.3/root-5.10.0
echo "Running:" ; echo ${CMDLINE}
echo ; echo ;
echo "Output:"
echo "-----------------------------------------"
${CMDLINE}
echo "-----------------------------------------"
echo ; echo ;


# End and tidy
mv for009.dat.txt for009.dat
gzip -9v for009.dat

#echo
#ls -l for009.dat.gz
echo ; echo "Saving output to lfn:${MICE_GRID_PWD}/${SIML_ID}.for009.dat.gz"
echo ; echo

lcg-cr --vo mice -v -l "${MICE_GRID_PWD}/${SIML_ID}.for009.dat.gz" "file://`pwd`/for009.dat.gz" 
if ( ${status} != 0 ) then
	echo "WARNING: default SE problem"
        lcg-cr --vo mice -v -d ${MICE_HOME_SEID} -l "${MICE_GRID_PWD}/${SIML_ID}.for009.dat.gz" "file://`pwd`/for009.dat.gz"
        if ( ${status} != 0 ) then
                echo "ERROR: Problem uploading output"
        endif
endif


ls -l
rm -f for009.dat.gz
rm -f *.dat 0.root 10.root
echo ; echo ;
ls -l
