################################################  EventBuilder
RUN=$1
EventBld=$2

rawDataPath=${SOLARISANADIR}/data_raw
rootDataPath=${SOLARISANADIR}/root_data

rawDataPattern="${rawDataPath}/${expName}_${RUN}_"
rootDataName="${rootDataPath}/run${RUN}.root"

dir=$(pwd)
cd ${SOLARISANADIR}/armory
make 
cd ${dir}

#==== check raw data exist
isRawDataExist=`ls -1 ${rawDataPattern}* 2>/dev/null | wc -l`

if [ ! $isRawDataExist -gt 0 ]; then
  echo -e "${LRED}################# Run Data not exist. Abort ${NC}"
  exit
fi

echo -e "${CYAN} ============== list of files ${NC}"
\du -h ${rawDataPattern}*

totSize=$(\du -hc ${rawDataPattern}* | tail -n 1 | awk '{print $1}')
echo -e "${CYAN} ============== total file size : ${totSize}${NC}"


#==== check raw data timeStamp
if [ ${Arch} == "Linux" ]; then
  rawDataTime=`stat -c "%Z"  ${rawDataPattern}* | sort -rn | head -1`    
else
  rawDataTime=`stat -f "%Sm" -t "%Y%m%d%H%M%S" ${rawDataPattern}* | sort -rn | head -1`    
fi

#==== check if root data exist
isRootDataExist=`ls -1 $rootDataName 2>/dev/null | wc -l`

#==== if merged data exist, check timeStamp
if [ ${isRootDataExist} -gt 0 ]; then
  if [ ${Arch} == "Linux" ]; then
    rootDataTime=`stat -c "%Z" $rootDataName | sort -rn | head -1`
  else
    rootDataTime=`stat -f "%Sm" -t "%Y%m%d%H%M%S" $rootDataName | sort -rn | head -1`
  fi
else
  rootDataTime=0
fi


if [ ${EventBld} -eq 0 ]; then

  echo -e "${LRED}>>>>>>>>>>>>>>>>>>>>> Event Building Skipped by user. ${NC}"

elif [ ${EventBld} -ge 1 ]; then

  if [ ${rawDataTime} -ge ${rootDataTime} ]; then
      
    echo -e "${LRED}>>>>>>>>>>>>>>>>>>>>> Event Building $(date) ${NC}"
    if [ ${EventBld} -eq 1 ]; then
      EventBuilder $rootDataName ${timeWin} 0 `ls -1 ${rawDataPattern}*`
    elif [ ${EventBld} -eq 2 ]; then
      EventBuilder $rootDataName ${timeWin} 1 `ls -1 ${rawDataPattern}*`
    fi
    echo -e "${LRED}<<<<<<<<<<<<<<<< Done Event Building $(date) ${NC}"

  else
      echo -e "${GREEN}Merged data are newer than raw data. No need to merged again.${NC}"
      echo -e "${GREEN}You can Force merging using option -${EventBld}, ${ORANGE} see ./process_run.sh -help${NC}"
  fi

else

    echo -e "${LRED}>>>>>>>>>>>>>>> Force Event Building $(date) ${NC}"
    if [ ${EventBld} -eq -1 ]; then
      EventBuilder $rootDataName ${timeWin} 0 `ls -1 ${rawDataPattern}*`
    elif [ ${EventBld} -eq -2 ]; then
      EventBuilder $rootDataName ${timeWin} 1 `ls -1 ${rawDataPattern}*`
    fi
    echo -e "${LRED}<<<<<<<<<<<<<<<< Done Event Building $(date) ${NC}"

fi