#!/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 [ "$PWD" != "${SOLARISANADIR}/working" ]; then
  echo "============= go to the Working directory"
  cd "${SOLARISANADIR}/working"
fi

if [ $# -eq 0 ] || [ $1 == "-help"  ]; then
  echo "$ Process_Run [RunNum] [EventBuild] [GeneralSort] [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 + TraceMethod * 100"  
  echo "                                  TraceMethod =  0 no trace"  
  echo "                                              =  1 save trace"  
  echo "                                              =  2 WS fit"  
  echo "                                              =  3 trapezoid(not implemented)"  
  echo "                                  e.g. 208 = WS trace with 8 workers"  
  echo "       Monitor = 2/1/0         || 1 = single run,  2 = using the list in ChainMonitors.C"
  echo ""
  echo "       * negative option = force."
  echo "       * Defult timeWindow for Event builder is 100 tick = 800 ns."
  echo ""
  exit 1
fi;

RUN=$1
runNum=$1
EventBld=1
nWorker=1
TraceMethod=0
isMonitor=1

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


temp=$((nWorker / 100));
if [ $temp -lt 0 ]; then
  TraceMethod=$((-1 * temp));
fi

nWorker=$((nWorker % 100 ));

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 ${rawDataPath}/expName.sh

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

#################################### 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