#!/bin/bash

######## default time window = 100 tick
timeWin=100

if [ -z $SOLARISANADIR ]; then
  echo "###### env variable SOLARISANADIR not defined. Abort. Please run the SOLARIS.sh."
  echo "better add \"source <path_to_SOLARIS.sh>\" into .bashrc"
  exit 
fi


if [ $# -eq 0 ] || [ $1 == "-help"  ]; then
  echo "$ Process_Run [RunNum] [EventBuild] [GeneralSort] [TraceMethod] [Monitor]"
  echo "        RunNum = run number / \"lastRun\" "
  echo "      EventBld = 2/1/0/-1/-2   || 2 = with Trace"  
  echo "   GeneralSort = n/0/-n        || n = number of worker"  
  echo "   TraceMethod = -1/0/1/2      || -1 no trace, 0 save trace, 1 fit, 2 trapezoid(not implemented)"  
  echo "       Monitor = 2/1/0         || 1 = single run,  2 = using the list in ChainMonitors.C"
  echo ""
  echo "       * negative option = force (except for TraceMethod and Monitor)."
  echo "       * Defult timeWindow for Event builder is 100 tick = 800 ns."
  echo ""
  exit 1
fi;

RUN=$1
runNum=$1
EventBld=2
nWorker=1
TraceMethod=-1
isMonitor=1

if [ $# -ge 2 ]; then EventBld=$2; fi
if [ $# -ge 3 ]; then nWorker=$3; fi
if [ $# -ge 4 ]; then TraceMethod=$4; fi
if [ $# -ge 5 ]; then isMonitor=$5; fi

if [ "$RUN" == "lastRun" ]; then
  RUN=$runID
fi

RUN=${RUN##*(0)} #remove zero
RUN=$(printf '%03d' $RUN) ##add back the zero

################################### Setting display
echo "#################################################"
echo "###           Process_Run                   #####"
echo "#################################################"
echo "###          RunID : ${RUN}"
echo "###  Event Builder : $EventBld"
echo "###   General Sort : $nWorker  worker(s)"
echo "###   Trace Method : $TraceMethod"
echo "###        Monitor : $isMonitor"
echo "#################################################"

source ${SOLARISANADIR}/armory/Process_BasicConfig
source ${SOLARISANADIR}/working/expName.sh

if [ "$PWD" != "${SOLARISANADIR}/working" ]; then
  echo "============= go to the Working directory"
  cd "${SOLARISANADIR}/working"
fi


#################################### CHECK IS RUN DATA EXIST
isRunDataExist=true

#################################### EVENT BUILDER
source Process_Download $RUN
  
if [ $isRunDataExist ]; then
  source Process_EventBuilder $RUN $EventBld $timeWin
fi

#################################### GeneralSort

if [ $isRunDataExist ]; then
  source Process_Sort $RUN $nWorker $TraceMethod
fi
#################################### Monitor

if [ $isMonitor -eq 0 ]; then
  echo -e "${LRED}>>>>>>>>>>>>>>>>>>>>> Monitor Skipped by user. ${NC}"
elif [  $isMonitor -eq 1 ]; then
  root -l "ChainMonitors.C($RUN)"
elif [  $isMonitor -eq 2 ]; then
  root -l "ChainMonitors.C"
fi