]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - PWGPP/benchmark/benchmark.sh
when will it end??
[u/mrichter/AliRoot.git] / PWGPP / benchmark / benchmark.sh
index 6ddf4e5efdebf8c95f8033340a72090557dd250d..f7a8e7395f0f4357eef59084d4fafdaa4f261310 100755 (executable)
@@ -14,7 +14,7 @@ main()
       echo "uses a batch system (SGE):"
       echo " ${0} \"submit\" productionID inputList configFile [extraOpts]"
       echo "extraOpts if non-empty override the config file, e.g.:"
-      echo " ${0} submit benchmark.list test1 benchmark.config runNumber=169123 nEvents=10"
+      echo " ${0} submit test1 benchmark.list benchmark.config runNumber=169123 nEvents=10"
     fi
     return
   fi
@@ -40,9 +40,10 @@ main()
     "WaitForOutput") goWaitForOutput "$@";;
     "Merge") goMerge "$@";;
     *) 
-      eval ${runMode} $@
+      ${runMode} "$@"
     ;;
   esac
+  return 0
 }
 
 generateMC()
@@ -54,6 +55,7 @@ generateMC()
   OCDBpath=${2}
   nEventsim=${3}
   if [[ -n ${pretend} ]]; then
+    sleep ${pretendDelay}
     touch galice.root
   else
     if [[ -f sim.C && -f Config.C ]] ; then
@@ -64,7 +66,7 @@ generateMC()
 }
 
 goCPass0()
-{
+(
   umask 0002
   
   targetDirectory=${1}
@@ -75,7 +77,10 @@ goCPass0()
   runNumber=${6}
   jobindex=${7}
   shift 7
-  parseConfig ${configFile} $@
+  if ! parseConfig ${configFile} "$@"; then return 1; fi
+
+  #record the working directory provided by the batch system
+  batchWorkingDirectory=${PWD}
 
   #use the jobindex only if set and non-negative
   if [[ -z ${jobindex} || ${jobindex} -lt 0 ]]; then
@@ -112,11 +117,15 @@ goCPass0()
   
   #runpath=${PWD}/rundir_cpass0_${runNumber}_${jobindex}
   runpath=${outputDir}
-  [[ ${reconstructInTemporaryDir} -eq 1 && -n ${TMPDIR} ]] && runpath=${TMPDIR}
-  [[ ${reconstructInTemporaryDir} -eq 1 && -z ${TMPDIR} ]] && runpath=$(mktemp -d)
+  #[[ ${reconstructInTemporaryDir} -eq 1 && -n ${TMPDIR} ]] && runpath=${TMPDIR}
+  [[ ${reconstructInTemporaryDir} -eq 1 ]] && runpath=$(mktemp -d -t cpass0.XXXXXX)
   mkdir -p ${runpath}
   [[ ! -d ${runpath} ]] && echo "cannot make runpath ${runpath}" && touch ${doneFile} && return 1
-  cd ${runpath}
+  if ! cd ${runpath}; then
+    echo "PWD=$PWD is not the runpath=${runpath}"
+    touch ${doneFile}
+    return 1
+  fi
 
   #runCPassX/C expects the raw chunk to be linked in the run dir
   #despite it being accessed by the full path
@@ -127,31 +136,32 @@ goCPass0()
     olddir=${PWD}
     outputDirMC=${commonOutputPath}/000${runNumber}/sim/${jobindex}
     simrunpath=${outputDirMC}
-    [[ ${simulateInTemporaryDir} -eq 1 && -n ${TMPDIR} ]] && simrunpath=${TMPDIR}
-    [[ ${simulateInTemporaryDir} -eq 1 && -z ${TMPDIR} ]] && simrunpath=$(mktemp -d)
+    #[[ ${simulateInTemporaryDir} -eq 1 && -n ${TMPDIR} ]] && simrunpath=${TMPDIR}
+    [[ ${simulateInTemporaryDir} -eq 1 ]] && simrunpath=$(mktemp -d -t cpass0MC.XXXXXX)
     mkdir -p ${outputDirMC}
     mkdir -p ${simrunpath}
-    cd ${simrunpath}
-
-    filesMC=( 
-              "${commonOutputPath}/sim.C"
-              "${commonOutputPath}/rec.C"
-              "${commonOutputPath}/Config.C"
-              "${commonOutputPath}/OCDB_*.root"
-    )
-    for file in ${filesMC[*]}; do
-      [[ ! -f ${file##*/} && -f ${file} ]] && echo "copying ${file}" && cp -f ${file} .
-    done
+    if cd ${simrunpath}; then
 
-    generateMC ${runNumber} ${ocdbPath} ${nEvents}
+      filesMC=( 
+      "${batchWorkingDirectory}/sim.C"
+      "${batchWorkingDirectory}/rec.C"
+      "${batchWorkingDirectory}/Config.C"
+      "${batchWorkingDirectory}/OCDB_*.root"
+      )
+      for file in ${filesMC[*]}; do
+        [[ ! -f ${file##*/} && -f ${file} ]] && echo "copying ${file}" && cp -f ${file} .
+      done
 
-    [[ ! "${simrunpath}" =~ "${outputDirMC}" ]] && mv * ${outputDirMC} #TODO check if it works
-    cd ${olddir}
-    
-    ln -s ${outputDirMC}/* ${runpath}/ 
-    
-    inputList=${outputDirMC}/galice.root #TODO not valid outside shell !!!
-    infile=""
+      generateMC ${runNumber} ${ocdbPath} ${nEvents}
+
+      [[ ! "${simrunpath}" =~ "${outputDirMC}" ]] && mv * ${outputDirMC} #TODO check if it works
+      cd ${olddir}
+
+      ln -s ${outputDirMC}/* ${runpath}/ 
+
+      inputList=${outputDirMC}/galice.root #TODO not valid outside shell !!!
+      infile=""
+    fi
   fi
   ######
   
@@ -159,8 +169,8 @@ goCPass0()
 
   logOutputDir=${runpath}
   [[ -n ${logToFinalDestination} ]] && logOutputDir=${outputDir}
-  [[ -z ${dontRedirectStdOutToLog} ]] && exec 1> ${logOutputDir}/stdout
-  [[ -z ${dontRedirectStdOutToLog} ]] && exec 2> ${logOutputDir}/stderr
+  [[ -z ${dontRedirectStdOutToLog} ]] && exec &> ${logOutputDir}/stdout
+  #[[ -z ${dontRedirectStdOutToLog} ]] && exec 2> ${logOutputDir}/stderr
   echo "${0} $*"
 
   echo "#####################"
@@ -185,11 +195,11 @@ goCPass0()
   alirootInfo > ALICE_ROOT.log
 
   filesCPass0=( 
-               "${commonOutputPath}/runCPass0.sh"
-               "${commonOutputPath}/recCPass0.C"
-               "${commonOutputPath}/runCalibTrain.C"
-               "${commonOutputPath}/localOCDBaccessConfig.C"
-               "${commonOutputPath}/OCDB.root"
+               "${batchWorkingDirectory}/runCPass0.sh"
+               "${batchWorkingDirectory}/recCPass0.C"
+               "${batchWorkingDirectory}/runCalibTrain.C"
+               "${batchWorkingDirectory}/localOCDBaccessConfig.C"
+               "${batchWorkingDirectory}/OCDB.root"
                "${ALICE_ROOT}/PWGPP/CalibMacros/CPass0/runCPass0.sh"
                "${ALICE_ROOT}/PWGPP/CalibMacros/CPass0/recCPass0.C" 
                "${ALICE_ROOT}/PWGPP/CalibMacros/CPass0/runCalibTrain.C"
@@ -197,6 +207,7 @@ goCPass0()
 
   for file in ${filesCPass0[*]}; do
     [[ ! -f ${file##*/} && -f ${file} ]] && echo "copying ${file}" && cp -f ${file} .
+    [[ ${file##*/} =~ .*\.sh ]] && chmod +x ${file##*/}
   done
 
   echo "this directory (${PWD}) contents:"
@@ -214,6 +225,7 @@ goCPass0()
   #run CPass0
   echo "${runpath}/runCPass0.sh ${infile} ${nEvents} ${runNumber} ${ocdbPath} ${recoTriggerOptions}"
   if [[ -n ${pretend} ]]; then
+    sleep ${pretendDelay}
     touch AliESDs.root
     touch AliESDfriends.root
     touch AliESDfriends_v1.root
@@ -231,25 +243,26 @@ goCPass0()
 
   echo rm -f ./${chunkName}
   rm -f ./${chunkName}
-  echo "cp --recursive ${runpath}/* ${outputDir}"
-  cp -p --recursive ${runpath}/* ${outputDir}
+  echo "cp -R ${runpath}/* ${outputDir}"
+  cp -p -R ${runpath}/* ${outputDir}
   echo
   
   #validate CPass0
   cd ${outputDir}
   touch ${doneFile}
-  [[ -f ${outputDirMC}/galice.root ]] && echo "sim ${outputDirMC}/galice.root" >> ${doneFile}
-  [[ -f AliESDfriends_v1.root ]] && echo "calibfile ${outputDir}/AliESDfriends_v1.root" >> ${doneFile}
-  [[ -f AliESDs.root ]] && echo "esd ${outputDir}/AliESDs.root" >> ${doneFile}
   echo "dir ${outputDir}" >> ${doneFile}
-  summarizeLogs >> ${doneFile}
+  if summarizeLogs >> ${doneFile}; then
+    [[ -f ${outputDirMC}/galice.root ]] && echo "sim ${outputDirMC}/galice.root" >> ${doneFile}
+    [[ -f AliESDfriends_v1.root ]] && echo "calibfile ${outputDir}/AliESDfriends_v1.root" >> ${doneFile}
+    [[ -f AliESDs.root ]] && echo "esd ${outputDir}/AliESDs.root" >> ${doneFile}
+  fi
 
-  [[ "${runpath}" != "${outputDir}" ]] && rm -rf ${runpath}
+  [[ "${runpath}" != "${outputDir}" ]] && rm -rf ${runpath} && echo "removing ${runpath}"
   return 0
-}
+)
 
 goCPass1()
-{
+(
   umask 0002
   
   targetDirectory=${1}
@@ -260,7 +273,11 @@ goCPass1()
   runNumber=${6}
   jobindex=${7}
   shift 7
-  parseConfig ${configFile} $@
+  extraOpts=("$@")
+  if ! parseConfig ${configFile} "$@"; then return 1; fi
+
+  #record the working directory provided by the batch system
+  batchWorkingDirectory=${PWD}
 
   #use the jobindex only if set and non-negative
   if [[ -z ${jobindex} || ${jobindex} -lt 0 ]]; then
@@ -298,8 +315,8 @@ goCPass1()
   
   #runpath=${PWD}/rundir_cpass1_${runNumber}_${jobindex}
   runpath=${outputDir}
-  [[ ${reconstructInTemporaryDir} -eq 1 && -n ${TMPDIR} ]] && runpath=${TMPDIR}
-  [[ ${reconstructInTemporaryDir} -eq 1 && -z ${TMPDIR} ]] && runpath=$(mktemp -d)
+  #[[ ${reconstructInTemporaryDir} -eq 1 && -n ${TMPDIR} ]] && runpath=${TMPDIR}
+  [[ ${reconstructInTemporaryDir} -eq 1 ]] && runpath=$(mktemp -d -t cpass1.XXXXXX)
 
   #MC
   if [[ "${infile}" =~ galice\.root ]]; then
@@ -310,15 +327,19 @@ goCPass1()
   #init the running path
   mkdir -p ${runpath}
   [[ ! -d ${runpath} ]] && echo "cannot make runpath ${runpath}" && touch ${doneFile} && return 1
-  cd ${runpath}
+  if ! cd ${runpath}; then
+    echo "PWD=$PWD is not the runpath=${runpath}"
+    touch ${doneFile}
+    return 1
+  fi
 
   #this is needed for runCPass1.sh
   ln -s ${infile} ${runpath}/${chunkName}
 
   logOutputDir=${runpath}
   [[ -n ${logToFinalDestination} ]] && logOutputDir=${outputDir}
-  [[ -z ${dontRedirectStdOutToLog} ]] && exec 1> ${logOutputDir}/stdout
-  [[ -z ${dontRedirectStdOutToLog} ]] && exec 2> ${logOutputDir}/stderr
+  [[ -z ${dontRedirectStdOutToLog} ]] && exec &> ${logOutputDir}/stdout
+  #[[ -z ${dontRedirectStdOutToLog} ]] && exec 2> ${logOutputDir}/stderr
   echo "${0} $*"
 
   echo "#####################"
@@ -336,6 +357,7 @@ goCPass1()
   echo doneFile      ${doneFile}
   echo runpath            ${runpath}  
   echo outputDir          ${outputDir}
+  echo batchWorkingDirectory ${batchWorkingDirectory}
   echo ALICE_ROOT         ${ALICE_ROOT}
   echo PWD                ${PWD}
   echo "########## ###########"
@@ -343,14 +365,15 @@ goCPass1()
   alirootInfo > ALICE_ROOT.log
 
   filesCPass1=( 
-               "${commonOutputPath}/runCPass1.sh"
-               "${commonOutputPath}/recCPass1.C"
-               "${commonOutputPath}/recCPass1_OuterDet.C"
-               "${commonOutputPath}/runCalibTrain.C"
-               "${commonOutputPath}/QAtrain_duo.C"
-               "${commonOutputPath}/localOCDBaccessConfig.C"
+               "${batchWorkingDirectory}/runCPass1.sh"
+               "${batchWorkingDirectory}/recCPass1.C"
+               "${batchWorkingDirectory}/recCPass1_OuterDet.C"
+               "${batchWorkingDirectory}/runCalibTrain.C"
+               "${batchWorkingDirectory}/QAtrain_duo.C"
+               "${batchWorkingDirectory}/localOCDBaccessConfig.C"
+               "${batchWorkingDirectory}/${configFile}"
                "${commonOutputPath}/meta/cpass0.localOCDB.${runNumber}.tgz"
-               "${commonOutputPath}/OCDB.root"
+               "${batchWorkingDirectory}/OCDB.root"
                "${trustedQAtrainMacro}"
                "${ALICE_ROOT}/PWGPP/CalibMacros/CPass1/runCPass1.sh"
                "${ALICE_ROOT}/PWGPP/CalibMacros/CPass1/recCPass1.C" 
@@ -359,14 +382,16 @@ goCPass1()
                "${ALICE_ROOT}/ANALYSIS/macros/QAtrain_duo.C"
   )
 
-  for file in ${filesCPass1[*]}; do
+  for file in "${filesCPass1[@]}"; do
     [[ ! -f ${file##*/} && -f ${file} ]] && echo "copying ${file}" && cp -f ${file} .
+    [[ ${file##*/} =~ .*\.sh ]] && echo "making ${file##*/} executable" && chmod +x ${file##*/}
   done
 
   echo "this directory (${PWD}) contents:"
   /bin/ls
   echo
 
+  #remove spaces around commas from calls to root
   sed -i '/.*root .*\.C/ s|\s*,\s*|,|g' *.sh
 
   if [[ -n ${postSetUpActionCPass1} ]]; then
@@ -392,14 +417,28 @@ goCPass1()
   #create the Barrel and OuterDet directories for CPass1 and link the local OCDB directory
   #there to make the localOCDBaccessConfig.C file work, since it may point to the OCDB
   #entries using a relative path, e.g. local://./OCDB
+  echo "linking the OCDB/ for Barrel and OuterDet directories"
   mkdir Barrel OuterDet
+  ls -l
   ln -s ../OCDB Barrel/OCDB
   ln -s ../OCDB OuterDet/OCDB
 
+  #setup the filtering
+  #the following option enables the filtering task inside the QAtrain_duo.C
+  [[ -n $runESDfiltering ]] && export QA_TaskFilteredTree=1
+  #set the downscaling factors during the filtering fro expert QA (overrides the previous values)
+  if [[ -n ${filteringFactorHighPt} ]]; then
+    export AliAnalysisTaskFilteredTree_fLowPtTrackDownscaligF=${filteringFactorHighPt}
+  fi
+  if [[ -n ${filteringFactorV0s} ]]; then
+    export AliAnalysisTaskFilteredTree_fLowPtV0DownscaligF=${filteringFactorV0s} 
+  fi
+
   #run CPass1
   chmod u+x runCPass1.sh
   echo "${runpath}/runCPass1.sh ${infile} ${nEvents} ${runNumber} ${ocdbPath} ${recoTriggerOptions}"
   if [[ -n ${pretend} ]]; then
+    sleep ${pretendDelay}
     touch AliESDs_Barrel.root
     touch AliESDfriends_Barrel.root
     touch AliESDfriends_v1.root
@@ -413,8 +452,27 @@ goCPass1()
     touch rec.log
     touch calib.log
     touch qa.log
+    touch filtering.log FilterEvents_Trees.root
   else
     ./runCPass1.sh "${infile}" "${nEvents}" "${runNumber}" "${ocdbPath}" "${recoTriggerOptions}"
+    
+    [[ ! -f AliESDs_Barrel.root && -f Barrel/AliESDs.root ]] && mv Barrel/AliESDs.root AliESDs_Barrel.root
+    [[ ! -f AliESDfriends_Barrel.root && -f Barrel/AliESDfriends.root ]] && mv Barrel/AliESDfriends.root AliESDfriends_Barrel.root
+    [[ ! -f AliESDfriends_v1.root && -f Barrel/AliESDfriends_v1.root ]] && mv Barrel/AliESDfriends_v1.root .
+    [[ ! -f QAresults_barrel.root && -f Barrel/QAresults_barrel.root ]] && mv Barrel/QAresults_barrel.root .
+    [[ ! -f AliESDs_Outer.root && -f OuterDet/AliESDs.root ]] && mv OuterDet/AliESDs.root AliESDs_Outer.root
+    [[ ! -f AliESDfriends_Outer.root && -f OuterDet/AliESDfriends.root ]] && mv OuterDet/AliESDfriends.root AliESDfriends_Outer.root
+    [[ ! -f QAresults_outer.root && -f OuterDet/QAresults_outer.root ]] && mv OuterDet/QAresults_outer.root .
+    [[ ! -f FilterEvents_Trees.root && -f Barrel/FilterEvents_Trees.root ]] && mv Barrel/FilterEvents_Trees.root .
+
+    #make the filtered tree (if requested and not already produced by QA
+    [[ -f AliESDs_Barrel.root ]] && echo "AliESDs_Barrel.root" > filtered.list
+    if [[ -n ${runESDfiltering} && ! -f FilterEvents_Trees.root && -f filtered.list ]]; then 
+      goMakeFilteredTrees ${PWD} ${runNumber} "${PWD}/filtered.list" ${filteringFactorHighPt} ${filteringFactorV0s} ${ocdbPath} 1000000 0 10000000 0 ${configFile} AliESDs_Barrel.root "${extraOpts[@]}" >filtering.log
+    else
+      echo ""
+    fi
+
   fi
 
   ##handle possible crashes in QA (happens often in trunk)
@@ -438,40 +496,49 @@ goCPass1()
   #  time aliroot -b -q "QAtrain_duo.C(\"_barrel\",${runNumber},\"wn.xml\",0,\"${ocdbPath}\")" &> ../qa_barrel_trusted.log
   #  cd ../
   #fi
-  [[ ! -f AliESDs_Barrel.root && -f Barrel/AliESDs.root ]] && mv Barrel/AliESDs.root AliESDs_Barrel.root
-  [[ ! -f AliESDfriends_Barrel.root && -f Barrel/AliESDfriends.root ]] && mv Barrel/AliESDfriends.root AliESDfriends_Barrel.root
-  [[ ! -f AliESDfriends_v1.root && -f Barrel/AliESDfriends_v1.root ]] && mv Barrel/AliESDfriends_v1.root .
-  [[ ! -f QAresults_barrel.root && -f Barrel/QAresults_barrel.root ]] && mv Barrel/QAresults_barrel.root .
-  [[ ! -f AliESDs_Outer.root && -f OuterDet/AliESDs.root ]] && mv OuterDet/AliESDs.root AliESDs_Outer.root
-  [[ ! -f AliESDfriends_Outer.root && -f OuterDet/AliESDfriends.root ]] && mv OuterDet/AliESDfriends.root AliESDfriends_Outer.root
-  [[ ! -f QAresults_outer.root && -f OuterDet/QAresults_outer.root ]] && mv OuterDet/QAresults_outer.root .
 
   #move stuff to final destination
   echo "this directory (${PWD}) contents:"
   /bin/ls
   echo rm -f ./${chunkName}
   rm -f ./${chunkName}
-  echo "cp --recursive ${runpath}/* ${outputDir}"
-  cp -pf --recursive ${runpath}/* ${outputDir}
+  echo "cp -R ${runpath}/* ${outputDir}"
+  cp -pf -R ${runpath}/* ${outputDir}
   echo
 
   #validate CPass1
   cd ${outputDir}
   touch ${doneFile}
-  [[ -f AliESDs_Barrel.root ]] && echo "esd ${outputDir}/AliESDs_Barrel.root" >> ${doneFile}
-  [[ -f AliESDfriends_v1.root ]] && echo "calibfile ${outputDir}/AliESDfriends_v1.root" >> ${doneFile}
-  [[ -f QAresults_Barrel.root ]] && echo "qafile ${outputDir}/QAresults_Barrel.root" >> ${doneFile}
-  [[ -f QAresults_Outer.root ]] && echo "qafile ${outputDir}/QAresults_Outer.root" >> ${doneFile}
   echo "dir ${outputDir}" >> ${doneFile}
-  summarizeLogs >> ${doneFile}
-  
+  if summarizeLogs >> ${doneFile}; then
+    [[ -f AliESDs_Barrel.root ]] && echo "esd ${outputDir}/AliESDs_Barrel.root" >> ${doneFile}
+    [[ -f AliESDfriends_v1.root ]] && echo "calibfile ${outputDir}/AliESDfriends_v1.root" >> ${doneFile}
+    [[ -f QAresults_Barrel.root ]] && echo "qafile ${outputDir}/QAresults_Barrel.root" >> ${doneFile}
+    [[ -f QAresults_Outer.root ]] && echo "qafile ${outputDir}/QAresults_Outer.root" >> ${doneFile}
+    [[ -f QAresults_barrel.root ]] && echo "qafile ${outputDir}/QAresults_barrel.root" >> ${doneFile}
+    [[ -f QAresults_outer.root ]] && echo "qafile ${outputDir}/QAresults_outer.root" >> ${doneFile}
+    [[ -f FilterEvents_Trees.root ]] && echo "filteredTree ${outputDir}/FilterEvents_Trees.root" >> ${doneFile}
+  else
+    if grep "qa_outer.log.*OK" ${doneFile} > /dev/null; then
+      [[ -f QAresults_Outer.root ]] && echo "qafile ${outputDir}/QAresults_Outer.root" >> ${doneFile}
+      [[ -f QAresults_outer.root ]] && echo "qafile ${outputDir}/QAresults_outer.root" >> ${doneFile}
+    fi
+    if grep "qa_barrel.log.*OK" ${doneFile} > /dev/null; then
+      [[ -f QAresults_Barrel.root ]] && echo "qafile ${outputDir}/QAresults_Barrel.root" >> ${doneFile}
+      [[ -f QAresults_barrel.root ]] && echo "qafile ${outputDir}/QAresults_barrel.root" >> ${doneFile}
+    fi
+    if grep "filtering.log.*OK" ${doneFile} > /dev/null; then
+      [[ -f FilterEvents_Trees.root ]] && echo "filteredTree ${outputDir}/FilterEvents_Trees.root" >> ${doneFile}
+    fi
+  fi
+
   [[ "${runpath}" != "${outputDir}" ]] && rm -rf ${runpath}
   return 0
-}
+)
 
 
 goMergeCPass0()
-{
+(
   #
   # find the output files and merge them
   #
@@ -482,7 +549,10 @@ goMergeCPass0()
   runNumber=${4}
   calibrationFilesToMerge=${5}  #can be a non-existent file, will then be produced on the fly
   shift 5
-  parseConfig ${configFile} $@
+  if ! parseConfig ${configFile} "$@"; then return 1; fi
+
+  #record the working directory provided by the batch system
+  batchWorkingDirectory=${PWD}
 
   [[ -z ${commonOutputPath} ]] && commonOutputPath=${PWD}
   doneFile="${commonOutputPath}/meta/merge.cpass0.run${runNumber}.done"
@@ -494,12 +564,16 @@ goMergeCPass0()
 
   #runpath=${PWD}/rundir_cpass0_Merge_${runNumber}
   runpath=${outputDir}
-  [[ ${reconstructInTemporaryDir} -eq 1 && -n ${TMPDIR} ]] && runpath=${TMPDIR}
-  [[ ${reconstructInTemporaryDir} -eq 1 && -z ${TMPDIR} ]] && runpath=$(mktemp -d)
+  #[[ ${reconstructInTemporaryDir} -eq 1 && -n ${TMPDIR} ]] && runpath=${TMPDIR}
+  [[ ${reconstructInTemporaryDir} -eq 1 ]] && runpath=$(mktemp -d -t mergeCPass0.XXXXXX)
 
   mkdir -p ${runpath}
   [[ ! -d ${runpath} ]] && echo "not able to make the runpath ${runpath}" && touch ${doneFile} && return 1
-  cd ${runpath}
+  if ! cd ${runpath}; then 
+    echo "PWD=$PWD is not the runpath=${runpath}"
+    touch ${doneFile}
+    return 1
+  fi
 
   logOutputDir=${runpath}
   [[ -n ${logToFinalDestination} ]] && logOutputDir=${outputDir}
@@ -519,9 +593,9 @@ goMergeCPass0()
   
   # copy files in case they are not already there
   filesMergeCPass0=(
-                    "${commonOutputPath}/${calibrationFilesToMerge}"
-                    "${commonOutputPath}/OCDB.root"
-                    "${commonOutputPath}/localOCDBaccessConfig.C"
+                    "${batchWorkingDirectory}/${calibrationFilesToMerge}"
+                    "${batchWorkingDirectory}/OCDB.root"
+                    "${batchWorkingDirectory}/localOCDBaccessConfig.C"
                     "${ALICE_ROOT}/PWGPP/CalibMacros/CPass0/mergeMakeOCDB.byComponent.sh"
                     "${ALICE_ROOT}/PWGPP/CalibMacros/CPass0/mergeByComponent.C"
                     "${ALICE_ROOT}/PWGPP/CalibMacros/CPass0/makeOCDB.C"
@@ -530,6 +604,7 @@ goMergeCPass0()
   )
   for file in ${filesMergeCPass0[*]}; do
     [[ ! -f ${file##*/} && -f ${file} ]] && echo "copying ${file}" && cp -f ${file} .
+    [[ ${file##*/} =~ .*\.sh ]] && chmod +x ${file##*/}
   done
   
   sed -i '/.*root .*\.C/ s|\s*,\s*|,|g' *.sh
@@ -553,31 +628,33 @@ goMergeCPass0()
   
   echo "${mergingScript} ${calibrationFilesToMerge} ${runNumber} local://./OCDB ${ocdbStorage}"
   if [[ -n ${pretend} ]]; then
+    sleep ${pretendDelay}
     touch CalibObjects.root
     touch ocdb.log
     touch merge.log
+    touch dcsTime.root
     mkdir -p ./OCDB/TPC/Calib/TimeGain/
     mkdir -p ./OCDB/TPC/Calib/TimeDrift/
     touch ./OCDB/TPC/Calib/TimeGain/someCalibObject_0-999999_cpass0.root
     touch ./OCDB/TPC/Calib/TimeDrift/otherCalibObject_0-999999_cpass0.root
   else
     ./${mergingScript} ${calibrationFilesToMerge} ${runNumber} "local://./OCDB" ${ocdbStorage}
-  fi
 
+    #produce the calib trees for expert QA (dcsTime.root)
+    goMakeLocalOCDBaccessConfig ./OCDB
+    echo aliroot -b -q "${ALICE_ROOT}/PWGPP/TPC/macros/CalibSummary.C(${runNumber},\"${ocdbStorage}\")"
+    aliroot -b -q "${ALICE_ROOT}/PWGPP/TPC/macros/CalibSummary.C(${runNumber},\"${ocdbStorage}\")"
+  fi
+  
   ### produce the output
   #tar the produced OCDB for reuse
   tar czf ${commonOutputPath}/meta/cpass0.localOCDB.${runNumber}.tgz ./OCDB
 
-  #produce the calib trees for expert QA (dcsTime.root)
-  goMakeLocalOCDBaccessConfig ./OCDB
-  echo aliroot -b -q "${ALICE_ROOT}/PWGPP/TPC/macros/CalibSummary.C(${runNumber},\"${ocdbStorage}\")"
-  aliroot -b -q "${ALICE_ROOT}/PWGPP/TPC/macros/CalibSummary.C(${runNumber},\"${ocdbStorage}\")"
-
   /bin/ls
 
   #copy all to output dir
-  cp -pf --recursive ${runpath}/* ${outputDir}
-  
+  cp -pf -R ${runpath}/* ${outputDir}
+
   if [[ -n ${generateMC} ]]; then
     goPrintValues sim ${commonOutputPath}/meta/sim.run${runNumber}.list ${commonOutputPath}/meta/cpass0.job*.run${runNumber}.done
   fi
@@ -585,17 +662,18 @@ goMergeCPass0()
   #validate merging cpass0
   cd ${outputDir}
   touch ${doneFile}
-  [[ -f CalibObjects.root ]] && echo "calibfile ${outputDir}/CalibObjects.root" >> ${doneFile}
-  [[ -f dcsTime.root ]] && echo "dcsTree ${outputDir}/dcsTime.root" >> ${doneFile}
   echo "dir ${outputDir}" >> ${doneFile}
-  summarizeLogs >> ${doneFile}
+  if summarizeLogs >> ${doneFile}; then
+    [[ -f CalibObjects.root ]] && echo "calibfile ${outputDir}/CalibObjects.root" >> ${doneFile}
+    [[ -f dcsTime.root ]] && echo "dcsTree ${outputDir}/dcsTime.root" >> ${doneFile}
+  fi
 
   [[ "${runpath}" != "${outputDir}" ]] && rm -rf ${runpath}
   return 0
-}
+)
 
 goMergeCPass1()
-{
+(
   #
   # find the output files and merge them
   #
@@ -606,8 +684,12 @@ goMergeCPass1()
   runNumber=${4}
   calibrationFilesToMerge=${5}
   qaFilesToMerge=${6}
-  shift 6
-  parseConfig ${configFile} $@
+  filteredFilesToMerge=${7}
+  shift 7
+  if ! parseConfig ${configFile} "$@"; then return 1; fi
+
+  #record the working directory provided by the batch system
+  batchWorkingDirectory=${PWD}
 
   [[ -z ${commonOutputPath} ]] && commonOutputPath=${PWD}
   doneFile="${commonOutputPath}/meta/merge.cpass1.run${runNumber}.done"
@@ -624,12 +706,16 @@ goMergeCPass1()
 
   #runpath=${PWD}/rundir_cpass1_Merge_${runNumber}
   runpath=${outputDir}
-  [[ ${reconstructInTemporaryDir} -eq 1 && -n ${TMPDIR} ]] && runpath=${TMPDIR}
-  [[ ${reconstructInTemporaryDir} -eq 1 && -z ${TMPDIR} ]] && runpath=$(mktemp -d)
+  #[[ ${reconstructInTemporaryDir} -eq 1 && -n ${TMPDIR} ]] && runpath=${TMPDIR}
+  [[ ${reconstructInTemporaryDir} -eq 1 ]] && runpath=$(mktemp -d -t mergeCPass1.XXXXXX)
 
   mkdir -p ${runpath}
   [[ ! -d ${runpath} ]] && echo "not able to make the runpath ${runpath}" && touch ${doneFile} && return 1
-  cd ${runpath}
+  if ! cd ${runpath}; then 
+    echo "PWD=$PWD is not the runpath=${runpath}"
+    touch ${doneFile}
+    return 1
+  fi
 
   logOutputDir=${runpath}
   [[ -n ${logToFinalDestination} ]] && logOutputDir=${outputDir}
@@ -654,12 +740,12 @@ goMergeCPass1()
   
   # copy files in case they are not already there
   filesMergeCPass1=(
-                    "${commonOutputPath}/${calibrationFilesToMerge}"
-                    "${commonOutputPath}/${qaFilesToMerge}"
-                    "${commonOutputPath}/OCDB.root"
-                    "${commonOutputPath}/localOCDBaccessConfig.C"
+                    "${batchWorkingDirectory}/${calibrationFilesToMerge}"
+                    "${batchWorkingDirectory}/${qaFilesToMerge}"
+                    "${batchWorkingDirectory}/OCDB.root"
+                    "${batchWorkingDirectory}/localOCDBaccessConfig.C"
                     "${commonOutputPath}/meta/cpass0.localOCDB.${runNumber}.tgz"
-                    "${commonOutputPath}/QAtrain_duo.C"
+                    "${batchWorkingDirectory}/QAtrain_duo.C"
                     "${ALICE_ROOT}/PWGPP/CalibMacros/CPass1/mergeMakeOCDB.byComponent.sh"
                     "${ALICE_ROOT}/PWGPP/CalibMacros/CPass1/mergeByComponent.C"
                     "${ALICE_ROOT}/PWGPP/CalibMacros/CPass1/makeOCDB.C"
@@ -670,6 +756,7 @@ goMergeCPass1()
   )
   for file in ${filesMergeCPass1[*]}; do
     [[ ! -f ${file##*/} && -f ${file} ]] && echo "copying ${file}" && cp -f ${file} .
+    [[ ${file##*/} =~ .*\.sh ]] && chmod +x ${file##*/}
   done
 
   sed -i '/.*root .*\.C/ s|\s*,\s*|,|g' *.sh
@@ -690,78 +777,99 @@ goMergeCPass1()
   #merge calibration
   chmod u+x ${mergingScript}  
   mkdir -p OCDB
-  if [[ ! -f ${calibrationFilesToMerge} ]]; then
-    echo "/bin/ls -1 ${outputDir}/*/${calibrationOutputFileName} > ${calibrationFilesToMerge}"
-    /bin/ls -1 ${outputDir}/*/${calibrationOutputFileName} 2>/dev/null > ${calibrationFilesToMerge}
-  fi
   
-  echo "${mergingScript} ${calibrationFilesToMerge} ${runNumber} local://./OCDB ${ocdbStorage}"
-  if [[ -n ${pretend} ]]; then
-    touch CalibObjects.root
-    touch ocdb.log
-    touch merge.log
-    touch cpass1.localOCDB.${runNumber}.tgz
-  else
-    ./${mergingScript} ${calibrationFilesToMerge} ${runNumber} "local://./OCDB" ${ocdbStorage}
+  #if not provided, create the lists of files to merge
+  if [[ ! -f ${filteredFilesToMerge} ]]; then
+    echo "/bin/ls -1 ${outputDir}/*/FilterEvents_Trees.root > ${filteredFilesToMerge}"
+    /bin/ls -1 ${outputDir}/*/FilterEvents_Trees.root 2>/dev/null > ${filteredFilesToMerge}
+  fi
+  if [[ ! -f ${calibrationFilesToMerge} ]]; then
+    echo "/bin/ls -1 ${outputDir}/*/AliESDfriends_v1.root > ${calibrationFilesToMerge}"
+    /bin/ls -1 ${outputDir}/*/AliESDfriends_v1.root 2>/dev/null > ${calibrationFilesToMerge}
   fi
-
-  tar czf ${commonOutputPath}/meta/cpass1.localOCDB.${runNumber}.tgz ./OCDB
-
-  #merge QA
-  [[ -n ${AliAnalysisTaskFilteredTree_fLowPtTrackDownscaligF} ]] && export AliAnalysisTaskFilteredTree_fLowPtTrackDownscaligF
-  [[ -n ${AliAnalysisTaskFilteredTree_fLowPtV0DownscaligF} ]] && export AliAnalysisTaskFilteredTree_fLowPtV0DownscaligF
-
   if [[ ! -f ${qaFilesToMerge} ]]; then
     #find the files, but only store the directories (QAtrain_duo.C requires this)
-    echo "/bin/ls -1 ${outputDir}/*/${qaOutputFileName} | while read x; do echo ${x%/*}; done | sort | uniq > ${qaFilesToMerge}"
-    eval "/bin/ls -1 ${outputDir}/*/${qaOutputFileName}" | while read x; do echo ${x%/*}; done | sort | uniq > ${qaFilesToMerge}
+    echo "/bin/ls -1 ${outputDir}/*/QAresults*.root | while read x; do echo ${x%/*}; done | sort | uniq > ${qaFilesToMerge}"
+    /bin/ls -1 ${outputDir}/*/QAresults*.root | while read x; do echo ${x%/*}; done | sort | uniq > ${qaFilesToMerge}
   fi
   
-  #do the merge
-  #echo aliroot -l -b -q "merge.C(\"${qaFilesToMerge}\",\"\",kFALSE,\"${qaMergedOutputFileName}\")"
-  echo aliroot -b -q "QAtrain_duo.C(\"_barrel\",${runNumber},\"${qaFilesToMerge}\",1,\"${ocdbStorage}\")"
+  echo "${mergingScript} ${calibrationFilesToMerge} ${runNumber} local://./OCDB ${ocdbStorage}"
   if [[ -n ${pretend} ]]; then
+    sleep ${pretendDelay}
+    touch ocdb.log
+    touch cpass1.localOCDB.${runNumber}.tgz
     touch ${qaMergedOutputFileName}
     touch merge.log
     touch trending.root
+    touch FilterEvents_Trees.root
+    touch CalibObjects.root
+    touch dcsTime.root
+    touch ${qaMergedOutputFileName}
+    mkdir -p OCDB
   else
+    ./${mergingScript} ${calibrationFilesToMerge} ${runNumber} "local://./OCDB" ${ocdbStorage}
+
+    #merge QA (and filtered trees)
+    [[ -n ${AliAnalysisTaskFilteredTree_fLowPtTrackDownscaligF} ]] && export AliAnalysisTaskFilteredTree_fLowPtTrackDownscaligF
+    [[ -n ${AliAnalysisTaskFilteredTree_fLowPtV0DownscaligF} ]] && export AliAnalysisTaskFilteredTree_fLowPtV0DownscaligF
+
+    #echo aliroot -l -b -q "merge.C(\"${qaFilesToMerge}\",\"\",kFALSE,\"${qaMergedOutputFileName}\")"
+    echo aliroot -b -q "QAtrain_duo.C(\"_barrel\",${runNumber},\"${qaFilesToMerge}\",1,\"${ocdbStorage}\")"
     #aliroot -l -b -q "merge.C(\"${qaFilesToMerge}\",\"\",kFALSE,\"${qaMergedOutputFileName}\")"
     aliroot -b -q "QAtrain_duo.C(\"_barrel\",${runNumber},\"${qaFilesToMerge}\",1,\"${ocdbStorage}\")" > mergeQA.log
     mv QAresults_barrel.root ${qaMergedOutputFileName}
     mv trending_barrel.root trending.root
+
+    #merge filtered trees
+    echo aliroot -l -b -q "merge.C(\"${qaFilesToMerge}\",\"\",kFALSE,\"${qaMergedOutputFileName}\")"
+    aliroot -l -b -q "merge.C(\"${filteredFilesToMerge}\",\"\",kFALSE,\"FilterEvents_Trees.root\")" > mergeFilteredTrees.log
+
+    #produce the calib trees for expert QA
+    echo aliroot -b -q "${ALICE_ROOT}/PWGPP/TPC/macros/CalibSummary.C(${runNumber},\"${ocdbStorage}\")"
+    aliroot -b -q "${ALICE_ROOT}/PWGPP/TPC/macros/CalibSummary.C(${runNumber},\"${ocdbStorage}\")" > calibTree.log
   fi
-  
-  #produce the calib trees for expert QA
-  echo aliroot -b -q "${ALICE_ROOT}/PWGPP/TPC/macros/CalibSummary.C(${runNumber},\"${ocdbStorage}\")"
-  aliroot -b -q "${ALICE_ROOT}/PWGPP/TPC/macros/CalibSummary.C(${runNumber},\"${ocdbStorage}\")"
+
+  tar czf ${commonOutputPath}/meta/cpass1.localOCDB.${runNumber}.tgz ./OCDB
 
   /bin/ls
 
   #copy all to output dir
-  cp -pf --recursive ${runpath}/* ${outputDir}
+  cp -pf -R ${runpath}/* ${outputDir}
   
   #validate merge cpass1
   cd ${outputDir}
   touch ${doneFile}
-  [[ -f CalibObjects.root ]] && echo "calibfile ${outputDir}/CalibObjects.root" >> ${doneFile}
-  [[ -f ${qaMergedOutputFileName} ]] && echo "qafile ${outputDir}/${qaMergedOutputFileName}" >> ${doneFile}
-  [[ -f trending.root ]] && echo "trendingfile ${outputDir}/trending.root" >> ${doneFile}
-  [[ -f dcsTime.root ]] && echo "dcsTree ${outputDir}/dcsTime.root" >> ${doneFile}
   echo "dir ${outputDir}" >> ${doneFile}
-  summarizeLogs >>  ${doneFile}
+  if summarizeLogs >>  ${doneFile}; then
+    [[ -f CalibObjects.root ]] && echo "calibfile ${outputDir}/CalibObjects.root" >> ${doneFile}
+    [[ -f ${qaMergedOutputFileName} ]] && echo "qafile ${outputDir}/${qaMergedOutputFileName}" >> ${doneFile}
+    [[ -f trending.root ]] && echo "trendingfile ${outputDir}/trending.root" >> ${doneFile}
+    [[ -f dcsTime.root ]] && echo "dcsTree ${outputDir}/dcsTime.root" >> ${doneFile}
+    [[ -f FilterEvents_Trees.root ]] && echo "filteredTree ${outputDir}/FilterEvents_Trees.root" >> ${doneFile}
+  else
+    if grep "mergeQA.log.*OK" ${doneFile} > /dev/null; then
+      [[ -f ${qaMergedOutputFileName} ]] && echo "qafile ${outputDir}/${qaMergedOutputFileName}" >> ${doneFile}
+    fi
+    if grep "mergeFilteredTrees.log.*OK" ${doneFile} > /dev/null; then
+      [[ -f FilterEvents_Trees.root ]] && echo "filteredTree ${outputDir}/FilterEvents_Trees.root" >> ${doneFile}
+    fi
+  fi
       
   [[ "${runpath}" != "${outputDir}" ]] && rm -rf ${runpath}
   return 0
-}
+)
 
 goMerge()
-{
+(
   #generic root merge using CPass1 merge.C script
   inputList=${1}
   outputFile=${2}  
-  configFile=${3-"becnhmark.config"}
+  configFile=${3-"benchmark.config"}
   shift 3
-  parseConfig ${configFile} $@
+  if ! parseConfig ${configFile} "$@"; then return 1; fi
+  
+  #record the working directory provided by the batch system
+  batchWorkingDirectory=${PWD}
 
   [[ ! -f ${inputList} ]] && echo "inputList ${inputList} does not exist!" && return 1
   [[ ! -f ${configFile} ]] && echo "configFile ${configFile} does not exist!" && return 1
@@ -770,7 +878,7 @@ goMerge()
   rm -f ${outputFile}
   aliroot -b -q "${ALICE_ROOT}/PWGPP/CalibMacros/CPass0/merge.C(\"${inputList}\",\"\",kFALSE,\"${outputFile}\")" > merge_${inputList}.log
   return 0
-}
+)
 
 goSubmitMakeflow()
 {
@@ -779,25 +887,43 @@ goSubmitMakeflow()
   inputFileList=${2}
   configFile=${3}
   shift 3
-  extraOpts="$@"
-  parseConfig ${configFile} ${extraOpts}
+  extraOpts=("$@")
+  if ! parseConfig ${configFile} "${extraOpts[@]}"; then return 1; fi
+  #record the working directory provided by the batch system
+  batchWorkingDirectory=${PWD}
 
   [[ -z ${configFile} ]] && configFile="benchmark.config"
   [[ ! -f ${configFile} ]] && echo "no config file found (${configFile})" && return 1
 
-  #create the directopry for the metadata
-  mkdir meta
-
   if [[ ! $(which makeflow &>/dev/null) && -n ${makeflowPath} ]]; then
     echo "setting the makflow path from the config: "
     echo "  export PATH=${makeflowPath}:${PATH}"
     export PATH=${makeflowPath}:${PATH}
   fi
 
+  #create the common output dir and the meta dir
+  commonOutputPath=${baseOutputDirectory}/${productionID}
+  if [[ -d ${commonOutputPath} ]]; then
+    echo "output dir ${commonOutputPath} exists!"
+    #return 1
+  else
+    mkdir -p ${commonOutputPath}
+  fi
+  mkdir -p ${commonOutputPath}/meta
+  
+  self=${0}
+  #if which greadlink; then self=$(greadlink -f "${0}"); fi
+  
+  #for reference copy the setup to the output dir
+  cp ${self} ${commonOutputPath}
+  cp ${configFile} ${commonOutputPath}
+  cp ${inputList} ${commonOutputPath}
+
   #submit - use makeflow if available, fall back to old stuff when makeflow not there
   if which makeflow; then
     
-    goGenerateMakeflow ${productionID} ${inputFileList} ${configFile} "${extraOpts}" > benchmark.makeflow
+    goGenerateMakeflow ${productionID} ${inputFileList} ${configFile} "${extraOpts[@]}" commonOutputPath=${commonOutputPath} > benchmark.makeflow
 
     makeflow ${makeflowOptions} benchmark.makeflow
     cd ../
@@ -808,20 +934,35 @@ goSubmitMakeflow()
 }
 
 goGenerateMakeflow()
-{
+(
   #generate the makeflow file
+  [[ $# -lt 3 ]] && echo "args: id inputFileList configFile" && return 1
   productionID=${1}
   inputFileList=${2}
   configFile=${3}
   shift 3
-  extraOpts="$@"
-  parseConfig ${configFile} ${extraOpts}
+  extraOpts=("$@")
+  
+  #batch systems/makeflow sometimes handle spaces in arguments poorly, so encode them
+  for (( i=0;i<${#extraOpts[@]};i++ )); do 
+    extraOpts[i]=$(encSpaces "${extraOpts[i]}")
+  done
+  extraOpts+=("encodedSpaces=1")
+
+  if ! parseConfig ${configFile} "${extraOpts[@]}" &>/dev/null; then return 1; fi
+  #extra safety
+  if [[ -z ${commonOutputPath} ]]; then
+    commonOutputPath=${baseOutputDirectory}/${productionID}
+    extraOpts=( "${extraOpts[@]}" "commonOutputPath=${commonOutputPath}" )
+  fi
+
+  #record the working directory provided by the batch system
+  batchWorkingDirectory=${PWD}
 
   [[ -z ${configFile} ]] && configFile="benchmark.config"
   [[ ! -f ${configFile} ]] && echo "no config file found (${configFile})" && return 1
 
-  commonOutputPath=${baseOutputDirectory}/${productionID}
-
   #these files will be made a dependency - will be copied to the working dir of the jobs
   declare -a copyFiles
   inputFiles=(
@@ -841,20 +982,24 @@ goGenerateMakeflow()
 
   #create the makeflow file
   [[ -n ${batchFlags} ]] && echo "BATCH_OPTIONS = ${batchFlags}"
-  declare -a arr_cpass1_final
-  listOfRuns[0]=${runNumber}
-  [[ -z ${runNumber} ]] && listOfRuns=($(while read x; do guessRunNumber ${x}; done < ${inputFileList} | sort | uniq))
-  runindex=0
-  for runNumber in ${listOfRuns[*]}; do
+  declare -A arr_cpass0_merged arr_cpass1_merged
+  declare -A arr_cpass0_calib_list arr_cpass1_calib_list 
+  declare -A arr_cpass1_QA_list arr_cpass1_ESD_list arr_cpass1_filtered_list
+  declare -A arr_cpass0_profiled_outputs
+  declare -A listOfRuns
+  [[ -n ${runNumber} ]] && listOfRuns[${runNumber}]=1
+  while read x; do tmpRun=$(guessRunNumber ${x}); [[ -n ${tmpRun} ]] && listOfRuns[${tmpRun}]=1; done < ${inputFileList}
+  for runNumber in "${!listOfRuns[@]}"; do
     [[ -z ${runNumber} ]] && continue
     [[ ! ${runNumber} =~ ^[0-9]*[0-9]$ ]] && continue
 
-    unset arr_cpass0_outputs_onerun
-    unset arr_cpass1_outputs_onerun
-    declare -a arr_cpass0_outputs_onerun
-    declare -a arr_cpass1_outputs_onerun
+    unset arr_cpass0_outputs
+    unset arr_cpass1_outputs
+    declare -a arr_cpass0_outputs
+    declare -a arr_cpass1_outputs
 
     jobindex=0
+    inputFile=""
     while read inputFile; do
       currentDefaultOCDB=${defaultOCDB}
       [[ -z ${autoOCDB} ]] && autoOCDB=1
@@ -863,74 +1008,80 @@ goGenerateMakeflow()
       fi
 
       #CPass0
-      arr_cpass0_outputs_onerun[${jobindex}]="meta/cpass0.job${jobindex}.run${runNumber}.done"
-      echo "${arr_cpass0_outputs_onerun[${jobindex}]} : benchmark.sh ${configFile} ${copyFiles[@]}"
-      echo " ${alirootEnv} ./benchmark.sh CPass0 ${commonOutputPath}/000${runNumber}/cpass0 ${inputFile} ${nEvents} ${currentDefaultOCDB} ${configFile} ${runNumber} ${jobindex} ${extraOpts}"
-      echo
+      arr_cpass0_outputs[${jobindex}]="${commonOutputPath}/meta/cpass0.job${jobindex}.run${runNumber}.done"
+      echo "${arr_cpass0_outputs[${jobindex}]} : benchmark.sh ${configFile} ${copyFiles[@]}"
+      echo " ${alirootEnv} ./benchmark.sh CPass0 ${commonOutputPath}/000${runNumber}/cpass0 ${inputFile} ${nEvents} ${currentDefaultOCDB} ${configFile} ${runNumber} ${jobindex} ${extraOpts[@]}"" "
 
       #CPass1
-      arr_cpass1_outputs_onerun[${jobindex}]="meta/cpass1.job${jobindex}.run${runNumber}.done"
-      echo "${arr_cpass1_outputs_onerun[${jobindex}]} : benchmark.sh ${configFile} meta/cpass0.localOCDB.${runNumber}.tgz ${copyFiles[@]}"
-      echo " ${alirootEnv} ./benchmark.sh CPass1 ${commonOutputPath}/000${runNumber}/cpass1 ${inputFile} ${nEvents} ${currentDefaultOCDB} ${configFile} ${runNumber} ${jobindex} ${extraOpts}"
-      echo
+      arr_cpass1_outputs[${jobindex}]="${commonOutputPath}/meta/cpass1.job${jobindex}.run${runNumber}.done"
+      echo "${arr_cpass1_outputs[${jobindex}]} : benchmark.sh ${configFile} ${commonOutputPath}/meta/cpass0.localOCDB.${runNumber}.tgz ${copyFiles[@]}"
+      echo " ${alirootEnv} ./benchmark.sh CPass1 ${commonOutputPath}/000${runNumber}/cpass1 ${inputFile} ${nEvents} ${currentDefaultOCDB} ${configFile} ${runNumber} ${jobindex} ${extraOpts[@]}"" "
       ((jobindex++))
 
     done< <(grep "/000${runNumber}/" ${inputFileList})
     
     #CPass0 list of Calib files to merge
-    arr_cpass0_calib_list[${runindex}]="meta/cpass0.calib.run${runNumber}.list"
-    echo "${arr_cpass0_calib_list[${runindex}]} : benchmark.sh ${arr_cpass0_outputs_onerun[*]}"
-    echo "  ./benchmark.sh PrintValues calibfile ${arr_cpass0_calib_list[${runindex}]} ${arr_cpass0_outputs_onerun[*]}"
+    arr_cpass0_calib_list[${runNumber}]="${commonOutputPath}/meta/cpass0.calib.run${runNumber}.list"
+    echo "${arr_cpass0_calib_list[${runNumber}]} : benchmark.sh ${arr_cpass0_outputs[*]}"
+    echo "  ./benchmark.sh PrintValues calibfile ${arr_cpass0_calib_list[${runNumber}]} ${arr_cpass0_outputs[*]}"
     echo
 
     #CPass0 merging
-    arr_cpass0_final[${runindex}]="meta/merge.cpass0.run${runNumber}.done"
-    echo "meta/cpass0.localOCDB.${runNumber}.tgz ${arr_cpass0_final[${runindex}]} : benchmark.sh ${configFile} ${arr_cpass0_calib_list[${runindex}]} ${copyFiles[@]}"
-    echo " ${alirootEnv} ./benchmark.sh MergeCPass0 ${commonOutputPath}/000${runNumber}/cpass0 ${currentDefaultOCDB} ${configFile} ${runNumber} ${arr_cpass0_calib_list[${runindex}]} ${extraOpts}"
-    echo
+    arr_cpass0_merged[${runNumber}]="${commonOutputPath}/meta/merge.cpass0.run${runNumber}.done"
+    echo "${commonOutputPath}/meta/cpass0.localOCDB.${runNumber}.tgz ${arr_cpass0_merged[${runNumber}]} : benchmark.sh ${configFile} ${arr_cpass0_calib_list[${runNumber}]} ${copyFiles[@]}"
+    echo " ${alirootEnv} ./benchmark.sh MergeCPass0 ${commonOutputPath}/000${runNumber}/cpass0 ${currentDefaultOCDB} ${configFile} ${runNumber} ${arr_cpass0_calib_list[${runNumber}]} ${extraOpts[@]}"" "
 
-    #CPass1 list of Calib/QA files to merge
-    # the trick is to have the string "Stage.txt" in the file name of the list of directories with QA output to trigger
-    # the production of the trending tree (only then the task->Finish() will be called in QAtrain_duo.C, on the grid
+    #CPass1 list of Calib/QA/ESD/filtered files
+    # the trick with QA is to have the string "Stage.txt" in the file name of the list of directories with QA output to trigger
+    # the production of the QA trending tree (only then the task->Finish() will be called in QAtrain_duo.C, on the grid
     # this corresponds to the last merging stage)
-    arr_cpass1_calib_list[${runindex}]="meta/cpass1.calib.run${runNumber}.list"
-    echo "${arr_cpass1_calib_list[${runindex}]} : benchmark.sh ${arr_cpass1_outputs_onerun[*]}"
-    echo "  ./benchmark.sh PrintValues calibfile ${arr_cpass1_calib_list[${runindex}]} ${arr_cpass1_outputs_onerun[*]};"
+    arr_cpass1_QA_list[${runNumber}]="${commonOutputPath}/meta/cpass1.QA.run${runNumber}.lastMergingStage.txt.list"
+    echo "${arr_cpass1_QA_list[${runNumber}]}: benchmark.sh ${arr_cpass1_outputs[*]}"
+    echo "  ./benchmark.sh PrintValues dir ${arr_cpass1_QA_list[${runNumber}]} ${arr_cpass1_outputs[*]}"
     echo
-    arr_cpass1_QA_list[${runindex}]="meta/cpass1.QA.run${runNumber}.lastMergingStage.txt.list"
-    echo "${arr_cpass1_QA_list[${runindex}]}: benchmark.sh ${arr_cpass1_outputs_onerun[*]}"
-    echo "  ./benchmark.sh PrintValues dir ${arr_cpass1_QA_list[${runindex}]} ${arr_cpass1_outputs_onerun[*]}"
+    arr_cpass1_calib_list[${runNumber}]="${commonOutputPath}/meta/cpass1.calib.run${runNumber}.list"
+    echo "${arr_cpass1_calib_list[${runNumber}]} : benchmark.sh ${arr_cpass1_outputs[*]}"
+    echo "  ./benchmark.sh PrintValues calibfile ${arr_cpass1_calib_list[${runNumber}]} ${arr_cpass1_outputs[*]};"
     echo
-
-    #CPass1 merging
-    arr_cpass1_final[${runindex}]="meta/merge.cpass1.run${runNumber}.done"
-    echo "meta/cpass1.localOCDB.${runNumber}.tgz ${arr_cpass1_final[${runindex}]} :  benchmark.sh ${configFile} ${arr_cpass1_calib_list[${runindex}]} ${arr_cpass1_QA_list[${runindex}]} ${copyFiles[@]}"
-    echo " ${alirootEnv} ./benchmark.sh MergeCPass1 ${commonOutputPath}/000${runNumber}/cpass1 ${currentDefaultOCDB} ${configFile} ${runNumber} ${arr_cpass1_calib_list[${runindex}]} ${arr_cpass1_QA_list[${runindex}]} ${extraOpts}"
+    arr_cpass1_ESD_list[${runNumber}]="${commonOutputPath}/meta/cpass1.ESD.run${runNumber}.list"
+    echo "${arr_cpass1_ESD_list[${runNumber}]} : benchmark.sh ${arr_cpass1_outputs[*]}"
+    echo "  ./benchmark.sh PrintValues esd ${arr_cpass1_ESD_list[${runNumber}]} ${arr_cpass1_outputs[*]}"
     echo
-
-    arr_cpass1_ESD_list[${runindex}]="meta/cpass1.ESD.run${runNumber}.list"
-    echo "${arr_cpass1_ESD_list[${runindex}]} : benchmark.sh ${arr_cpass1_outputs_onerun[*]}"
-    echo "  ./benchmark.sh PrintValues esd ${arr_cpass1_ESD_list[${runindex}]} ${arr_cpass1_outputs_onerun[*]}"
-    
-    if [ ${runESDfiltering} -eq 1 ]; then
-      arr_cpass1_filtering[${runindex}]="meta/filtering.cpass1.run${runNumber}.done"
-      echo "${arr_cpass1_filtering[${runindex}]} : benchmark.sh ${configFile} ${arr_cpass1_ESD_list[${runindex}]}"
-      echo "  ${alirootEnv} ./benchmark.sh MakeFilteredTrees ${commonOutputPath}/000${runNumber}/cpass1 ${runNumber} ${arr_cpass1_ESD_list[${runindex}]} ${filteringFactorHighPt} ${filteringFactorV0s} ${currentDefaultOCDB} 1000000 0 10000000 0 ${configFile} AliESDs_Barrel.root ${extraOpts}"
+    arr_cpass1_filtered_list[${runNumber}]="${commonOutputPath}/meta/cpass1.filtered.run${runNumber}.list"
+    echo "${arr_cpass1_filtered_list[${runNumber}]} : benchmark.sh ${arr_cpass1_outputs[*]}"
+    echo "  ./benchmark.sh PrintValues filteredTree ${arr_cpass1_filtered_list[${runNumber}]} ${arr_cpass1_outputs[*]}"
+    echo
+  
+    #CPass1 merging
+    arr_cpass1_merged[${runNumber}]="${commonOutputPath}/meta/merge.cpass1.run${runNumber}.done"
+    echo "${commonOutputPath}/meta/cpass1.localOCDB.${runNumber}.tgz ${arr_cpass1_merged[${runNumber}]} :  benchmark.sh ${configFile} ${arr_cpass1_calib_list[${runNumber}]} ${arr_cpass1_QA_list[${runNumber}]} ${copyFiles[@]}"
+    echo " ${alirootEnv} ./benchmark.sh MergeCPass1 ${commonOutputPath}/000${runNumber}/cpass1 ${currentDefaultOCDB} ${configFile} ${runNumber} ${arr_cpass1_calib_list[${runNumber}]} ${arr_cpass1_QA_list[${runNumber}]} ${arr_cpass1_filtered_list[${runNumber}]} ${extraOpts[@]}"" "
+
+    #CPass0 wrapped in a profiling tool (valgrind,....)
+    if [[ -n ${profilingCommand} ]]; then
+      inputFile=$(grep -m1 "${runNumber}/" ${inputFileList})
+      [[ -z ${nEventsProfiling} ]] && nEventsProfiling=2
+      currentDefaultOCDB=$(setYear ${inputFile} ${defaultOCDB})
+      jobindex="profiling"
+
+      arr_cpass0_profiled_outputs[${runNumber}]="${commonOutputPath}/meta/cpass0.job${jobindex}.run${runNumber}.done"
+      echo "${arr_cpass0_profiled_outputs[${runNumber}]} : benchmark.sh ${configFile} ${copyFiles[@]}"
+      profilingCommand=$(encSpaces "${profilingCommand}")
+      echo " ${alirootEnv} ./benchmark.sh CPass0 ${commonOutputPath}/000${runNumber}/${jobindex} ${inputFile} ${nEventsProfiling} ${currentDefaultOCDB} ${configFile} ${runNumber} ${jobindex} ${extraOpts[@]} useProfilingCommand=${profilingCommand}"
     fi
 
-    ((runindex++))
-  done
+  done #runs
 
   #Summary
-  echo "summary.log : benchmark.sh ${configFile} ${arr_cpass1_final[*]} ${arr_cpass1_filtering[*]}"
-  echo " LOCAL ./benchmark.sh MakeSummary ${configFile}"
+  echo "${commonOutputPath}/summary.log : benchmark.sh ${configFile} ${arr_cpass1_merged[*]}"
+  echo "  ${alirootEnv} ./benchmark.sh MakeSummary ${configFile} ${extraOpts[@]}"
   echo
 
   return 0
-}
+)
 
 goPrintValues()
-{
+(
   #print the values given the key from any number of files (store in output file on second argument)
   if [[ $# -lt 3 ]]; then
     echo "goPrintValues key outputFile inputFiles"
@@ -943,48 +1094,45 @@ goPrintValues()
   shift 2 #remove 2 first arguments from arg list to only pass the input files to awk
   awk -v key=${key} '$0 ~ key" " {print $2}' "$@" | tee ${outputFile}
   return 0
-}
+)
 
 goCreateQAplots()
-{
+(
   umask 0002
   mergedQAfileList=${1}
   productionID=${2}
   outputDir=${3}
   configFile=${4}
   shift 4
-  parseConfig ${configFile} ${@}
+  if ! parseConfig ${configFile} ${@}; then return 1; fi
   
+  #record the working directory provided by the batch system
+  batchWorkingDirectory=${PWD}
+
   [[ -f ${alirootSource} && -z ${ALICE_ROOT} ]] && source ${alirootSource}
 
   [[ -z ${logOutputDir} ]] && logOutputDir=${PWD}
-  [[ -z ${dontRedirectStdOutToLog} ]] && exec 2>&1 > ${logOutputDir}/makeQAplots.log
+  [[ -z ${dontRedirectStdOutToLog} ]] && exec &> ${logOutputDir}/makeQAplots.log
   echo "${0} $*"
 
   olddir=${PWD}
   mkdir -p ${outputDir}
   cd ${outputDir}
-  [[ ! "${PWD}" = "${outputDir}" ]] && echo "cannot make ${outputDir}... exiting" && return 1
+  [[ ! "${PWD}" =~ "${outputDir}" ]] && echo "PWD is not equal to outputDir=${outputDir}" && cd ${olddir} && return 1
 
-  echo ${ALICE_ROOT}/PWGPP/QA/scripts/runQA.sh inputList=${mergedQAfileList}
-  ${ALICE_ROOT}/PWGPP/QA/scripts/runQA.sh inputList=${mergedQAfileList}
+  ${ALICE_ROOT}/PWGPP/QA/scripts/runQA.sh inputList="${mergedQAfileList}" inputListHighPtTrees="${filteringList}"
 
   cd ${olddir}
   return 0
-}
+)
 
 goTest()
-{
-  umask 0002
-  exec 2>&1
-  exec > >(tee test.log)
-  echo "$@"
-  echo something
-  return 0
-}
+(
+  echo AA
+)
 
 alirootInfo()
-{
+(
   umask 0002
   # save aliroot repository info
   [[ -z "${ALICE_ROOT}" ]] && return 1
@@ -993,10 +1141,10 @@ alirootInfo()
   echo "\${ROOTSYS}=${ROOTSYS}"
   echo "\${PATH}=${PATH}"
   echo "\${LD_LIBRARY_PATH}=${LD_LIBRARY_PATH}"
+  echo
   
   pushd ${PWD}
   cd ${ALICE_ROOT}
-  echo
 
   currentBranch=$(git rev-parse --abbrev-ref HEAD)
   git status
@@ -1005,10 +1153,10 @@ alirootInfo()
   git diff ${currentBranch}
   popd
   return 0
-}
+)
 
 setYear()
-{
+(
   #set the year
   #  ${1} - year to be set
   #  ${2} - where to set the year
@@ -1018,10 +1166,10 @@ setYear()
   [[ ${year1} -ne ${year2} && -n ${year2} && -n ${year1} ]] && path=${2/\/${year2}\//\/${year1}\/}
   echo ${path}
   return 0
-}
+)
 
 guessPeriod()
-{
+(
   #guess the period from the path, pick the rightmost one
   local IFS="/"
   declare -a path=( ${1} )
@@ -1032,10 +1180,10 @@ guessPeriod()
   done
   echo ${period}
   return 0
-}
+)
 
 guessYear()
-{
+(
   #guess the year from the path, pick the rightmost one
   local IFS="/"
   declare -a path=( ${1} )
@@ -1046,10 +1194,10 @@ guessYear()
   done
   echo ${year}
   return 0
-}
+)
 
 guessRunNumber()
-{
+(
   #guess the run number from the path, pick the rightmost one
   #works for /path/foo/000123456/bar/...
   #and       /path/foo.run123456.bar
@@ -1059,14 +1207,14 @@ guessRunNumber()
   for ((x=${dirDepth}-1;x>=0;x--)); do
     local field=${path[${x}]}
     field=${field/run/000}
-    [[ ${field} =~ ^000[0-9][0-9][0-9][0-9][0-9][0-9]$ ]] && runNumber=${field#000} && break
+    [[ ${field} =~ [0-9][0-9][0-9][0-9][0-9][0-9]$ ]] && runNumber=${field#000} && break
   done
   echo ${runNumber}
   return 0
-}
+)
 
 validateLog()
-{
+(
   log=${1}
   errorConditions=(
                     'There was a crash'
@@ -1078,6 +1226,7 @@ validateLog()
                     'AliFatal'
                     'core dumped'
                     '\.C.*error:.*\.h: No such file'
+                    'line.*Aborted'
   )
 
   warningConditions=(
@@ -1112,10 +1261,10 @@ validateLog()
   fi
 
   return 0
-}
+)
 
 summarizeLogs()
-{
+(
   #print a summary of logs
   logFiles=(
             "*.log"
@@ -1133,12 +1282,14 @@ summarizeLogs()
     if [[ ${validationStatus} -eq 0 ]]; then 
       #in pretend mode randomly report an error in rec.log some cases
       if [[ -n ${pretend} && "${log}" == "rec.log" ]]; then
-        [[ $(( ${RANDOM}%2 )) -ge 1 ]] && echo "${finallog} BAD random error" || echo "${finallog} OK"
+        #[[ $(( ${RANDOM}%2 )) -ge 1 ]] && echo "${finallog} BAD random error" || echo "${finallog} OK"
+        echo "${finallog} OK"
       else
         echo "${finallog} OK"
       fi
     elif [[ ${validationStatus} -eq 1 ]]; then
       echo "${finallog} BAD ${errorSummary}"
+      logstatus=1
     elif [[ ${validationStatus} -eq 2 ]]; then
       echo "${finallog} OK MWAH ${errorSummary}"
     fi
@@ -1152,7 +1303,7 @@ summarizeLogs()
   done < <(/bin/ls ${PWD}/*/core 2>/dev/null; /bin/ls ${PWD}/core 2>/dev/null)
   
   return ${logstatus}
-}
+)
 
 spitOutLocalOCDBaccessConfig()
 {
@@ -1189,7 +1340,7 @@ goMakeLocalOCDBaccessConfig()
 
   local tempLocalOCDB=""
   if [[ -f localOCDBaccessConfig.C ]]; then
-    tempLocalOCDB=$(mktemp)
+    tempLocalOCDB=$(mktemp -t tempLocalOCDB.XXXXXX)
     echo "egrep "SetSpecificStorage" localOCDBaccessConfig.C > ${tempLocalOCDB}"
     egrep "SetSpecificStorage" localOCDBaccessConfig.C > ${tempLocalOCDB}
   fi
@@ -1212,7 +1363,7 @@ goMakeLocalOCDBaccessConfig()
 }
 
 goMakeFilteredTrees()
-{
+(
   outputDir=${1}
   runNumber=${2}
   #get path to input list
@@ -1234,20 +1385,14 @@ goMakeFilteredTrees()
   configFile=${11-"benchmark.config"}
   esdFileName=${12-"AliESDs_Barrel.root"}
   shift 12
-  parseConfig ${configFile} $@
+  if ! parseConfig ${configFile} "$@"; then return 1; fi
+  
+  #record the working directory provided by the batch system
+  batchWorkingDirectory=${PWD}
 
-  commonOutputPath=${PWD}
+  [[ -z ${commonOutputPath} ]] && commonOutputPath=${PWD}
   doneFile=${commonOutputPath}/meta/filtering.cpass1.run${runNumber}.done
 
-  runpath=${commonOutputPath}/rundir_filtering_run${runNumber}
-
-  [[ -f ${alirootSource} && -z ${ALICE_ROOT} ]] && source ${alirootSource}
-
-  mkdir -p ${outputDir}
-  mkdir -p ${runpath}
-
-  cd ${runpath}
-  
   cat > filtering.log << EOF
   goMakeFilteredTrees config:
   runpath=${runpath}
@@ -1258,35 +1403,57 @@ goMakeFilteredTrees()
   offsetEvent=$offsetEvent
   configFile=$configFile
   esdFileName=$esdFileName
+  inputListfiles=$inputListfiles
+  doneFile=$doneFile
 EOF
 
+  #runpath=${outputDir}
+  #[[ ${reconstructInTemporaryDir} -eq 1 && -n ${TMPDIR} ]] && runpath=${TMPDIR}
+  #[[ ${reconstructInTemporaryDir} -eq 1 ]] && runpath=$(mktemp -d -t goMakeFilteredTrees.XXXXXX)
+  #mkdir -p ${outputDir}
+  #mkdir -p ${runpath}
+  #if ! cd ${runpath}; then 
+  #  echo "PWD=$PWD is not the runpath=${runpath}"
+  #  touch ${doneFile}
+  #  return 1
+  #fi
+  
   if [[ -z ${pretend} ]];then
     aliroot -l -b -q "${ALICE_ROOT}/PWGPP/macros/runFilteringTask.C(\"${inputListfiles}\",${filterT},${filterV},\"${OCDBpath}\",${maxFiles},${offsetFile},${maxEvents},${offsetEvent},\"${esdFileName}\")" &>> filtering.log
   else
+    sleep ${pretendDelay}
     touch filtering.log FilterEvents_Trees.root
   fi
   pwd
   /bin/ls
   touch ${doneFile}
   summarizeLogs >>  ${doneFile}
-  echo mv -f * ${outputDir}
-  mv -f * ${outputDir}
-  [[ -f ${outputDir}/FilterEvents_Trees.root ]] && echo "filteredTree ${outputDir}/FilterEvents_Trees.root" >> ${doneFile}
-  cd ${commonOutputPath}
-  [[ "${runpath}" != "${outputDir}" ]] && rm -rf ${runpath}
+  
+  #echo mv -f * ${outputDir}
+  #mv -f * ${outputDir}
+  #[[ -f ${outputDir}/FilterEvents_Trees.root ]] && echo "filteredTree ${outputDir}/FilterEvents_Trees.root" >> ${doneFile}
+  #cd ${commonOutputPath}
+  #[[ "${runpath}" != "${outputDir}" ]] && rm -rf ${runpath}
+  
   return 0
-}
+)
 
 submit()
 {
   umask 0002
-  [[ $# -ne 6 ]] && echo "6 args needed, you supplied $#" && return 1
+  [[ $# -lt 5 ]] && echo "at least 5 args needed, you supplied $#" && return 1
   JobID=${1}
   startID=${2}
   endID=${3}
   waitForJOBID=${4}
   command=${5}
-  commandArgs=${6}
+  shift 5
+  local commandArgs=("$@")
+
+  #add quote strings around the extra arguments
+  for ((i=0; i<${#commandArgs[@]}; i++)); do 
+    commandArgs[i]=\"${commandArgs[i]}\"
+  done
 
   [[ -z ${waitForJOBID} ]] && waitForJOBID=0
 
@@ -1317,11 +1484,11 @@ submit()
   else 
     #new SGE farm
     if [[ ${waitForJOBID} =~ "000" ]]; then
-      echo ${batchCommand} ${batchFlags} -wd ${commonOutputPath} -b y -v commonOutputPath -N "${JobID}" -t "${startID}-${endID}" -e "${commonOutputPath}/logs/" -o "${commonOutputPath}/logs/" "${command}" ${commandArgs}
-      ${batchCommand} ${batchFlags} -wd ${commonOutputPath} -b y -v commonOutputPath -N "${JobID}" -t "${startID}-${endID}" -e "${commonOutputPath}/logs/" -o "${commonOutputPath}/logs/" "${command}" ${commandArgs}
+      echo ${batchCommand} ${batchFlags} -wd ${commonOutputPath} -b y -v commonOutputPath -N "${JobID}" -t "${startID}-${endID}" -e "${commonOutputPath}/logs/" -o "${commonOutputPath}/logs/" "${command}" "${commandArgs[@]}"
+      ${batchCommand} ${batchFlags} -wd ${commonOutputPath} -b y -v commonOutputPath -N "${JobID}" -t "${startID}-${endID}" -e "${commonOutputPath}/logs/" -o "${commonOutputPath}/logs/" "${command}" "${commandArgs[@]}"
     else
-      echo ${batchCommand} ${batchFlags} -wd ${commonOutputPath} -b y -v commonOutputPath -N "${JobID}" -t "${startID}-${endID}" -hold_jid "${waitForJOBID}" -e "${commonOutputPath}/logs/" -o "${commonOutputPath}/logs/" "${command}" ${commandArgs}
-      ${batchCommand} ${batchFlags} -wd ${commonOutputPath} -b y -v commonOutputPath -N "${JobID}" -t "${startID}-${endID}" -hold_jid "${waitForJOBID}" -e "${commonOutputPath}/logs/" -o "${commonOutputPath}/logs/" "${command}" ${commandArgs}
+      echo ${batchCommand} ${batchFlags} -wd ${commonOutputPath} -b y -v commonOutputPath -N "${JobID}" -t "${startID}-${endID}" -hold_jid "${waitForJOBID}" -e "${commonOutputPath}/logs/" -o "${commonOutputPath}/logs/" "${command}" "${commandArgs[@]}"
+      ${batchCommand} ${batchFlags} -wd ${commonOutputPath} -b y -v commonOutputPath -N "${JobID}" -t "${startID}-${endID}" -hold_jid "${waitForJOBID}" -e "${commonOutputPath}/logs/" -o "${commonOutputPath}/logs/" "${command}" "${commandArgs[@]}"
     fi
   fi
   return 0
@@ -1338,10 +1505,19 @@ goSubmitBatch()
   productionID=${1}
   inputList=${2}
   configFile=${3:-"benchmark.config"}
-  configFile=$(readlink -f ${configFile})
+  #if which greadlink; then configFile=$(greadlink -f ${configFile}); fi
   shift 3
-  extraOpts="$@"
-  parseConfig ${configFile} ${extraOpts}
+  extraOpts=("$@")
+  if ! parseConfig ${configFile} "${extraOpts[@]}"; then return 1; fi
+  
+  #batch systems/makeflow sometimes handle spaces in arguments poorly, so encode them
+  for (( i=0;i<${#extraOpts[@]};i++ )); do 
+    extraOpts[i]=$(encSpaces "${extraOpts[i]}")
+  done
+  extraOpts+=("encodedSpaces=1")
+
+  #record the working directory provided by the batch system
+  batchWorkingDirectory=${PWD}
 
   #redirect all output to submit.log
   echo "redirecting all output to ${PWD}/submit_${productionID//"/"/_}.log"
@@ -1366,11 +1542,11 @@ goSubmitBatch()
     echo "Using Config File: '${configFile}'"
   fi
 
-  # and print the configuration
-  [[ -f ${alirootSource} && -z ${ALICE_ROOT} ]] && source ${alirootSource}
+  [[ ! -f ${alirootEnv} ]] && echo "alirootEnv script ${alirootEnv} not found!..." && return 1
 
   #move the script, config and some other stuff to ${commonOutputPath} first, then use them from there
-  self=$(readlink -f "${0}")
+  self=${0}
+  #if which greadlink; then self=$(greadlink -f "${0}"); fi
   configPath=$(dirname ${configFile})
   export commonOutputPath=${baseOutputDirectory}/${productionID}
   
@@ -1387,7 +1563,7 @@ goSubmitBatch()
   inputList=${commonOutputPath}/${inputList##*/}
 
   #convert to absolut pathnames
-  inputList=$(readlink -f "${inputList}")
+  #if which greadlink; then inputList=$(greadlink -f "${inputList}"); fi
   #make list of runs
   if [[ -z ${runNumber} ]]; then
     listOfRuns=($(while read x; do guessRunNumber ${x}; done < ${inputList} | sort | uniq))
@@ -1395,7 +1571,7 @@ goSubmitBatch()
     listOfRuns=${runNumber}
   fi
 
-  alirootSource=$(readlink -f "${alirootSource}")
+  #if which greadlink; then alirootSource=$(greadlink -f "${alirootSource}"); fi
 
   echo ""
   echo "### BEGIN CONFIGURATION ###"
@@ -1405,9 +1581,9 @@ goSubmitBatch()
   echo "    productionID:    ${productionID}"
   echo "    batchCommand:    ${batchCommand}"
   echo "    batchFlags:      ${batchFlags}"
-  echo "    alirootSource:   ${alirootSource}"
-  echo "    ALICE_ROOT:      ${ALICE_ROOT}"
-  echo "    ALIROOT_RELEASE: ${ALICE_RELEASE}"
+  echo "    alirootEnv:   ${alirootEnv}"
+  ${alirootEnv} echo '    ALICE_ROOT:      ${ALICE_ROOT}'
+  ${alirootEnv} echo '    ALIROOT_RELEASE: ${ALICE_RELEASE}'
   echo "    inputList:       ${inputList}"
   echo "    configPath:      ${configPath}"
   echo "    commonOutputPath:      ${commonOutputPath}"
@@ -1475,7 +1651,7 @@ goSubmitBatch()
     JOBfilterESDcpass1="fp1_${JOBpostfix}"
     LASTJOB="000"
 
-    oneInputFile=$(egrep -m1 "${runNumber}\/" ${inputList})
+    oneInputFile=$(egrep -m1 "${runNumber}/" ${inputList})
 
     currentDefaultOCDB=${defaultOCDB}
     [[ -z ${autoOCDB} ]] && autoOCDB=1
@@ -1487,10 +1663,10 @@ goSubmitBatch()
 
     ###############################################################################
     #run one chunk with valgrind:
-    if [[ -n ${runValgrind} ]]; then
-      [[ -z ${nEventsValgrind} ]] && nEventsValgrind=2
-      [[ -z ${valgrindCommand} ]] && valgrindCommand="/usr/bin/valgrind --tool=callgrind --num-callers=40 -v --trace-children=yes"
-      submit "valgrind" 1 1 000 "${alirootEnv} ${self}" "CPass0 ${commonOutputPath}/000${runNumber}/valgrind ${oneInputFile} ${nEventsValgrind} ${currentDefaultOCDB} ${configFile} ${runNumber} valgrind valgrindCommand=${valgrindCommand} ${extraOpts}"
+    if [[ -n ${profilingCommand} ]]; then
+      [[ -z ${nEventsProfiling} ]] && nEventsProfiling=2
+      [[ -z ${profilingCommand} ]] && profilingCommand="/usr/bin/valgrind --tool=callgrind --num-callers=40 -v --trace-children=yes"
+      submit "valgrind" 1 1 000 "${alirootEnv} ${self}" CPass0 ${commonOutputPath}/000${runNumber}/valgrind ${oneInputFile} ${nEventsProfiling} ${currentDefaultOCDB} ${configFile} ${runNumber} valgrind useProfilingCommand=${profilingCommand} "${extraOpts[@]}"
     fi 
 
     ################################################################################
@@ -1540,10 +1716,10 @@ goSubmitBatch()
       echo "requested success rate is ${percentProcessedFilesToContinue}%"
       echo "merging will start after ${nFilesToWaitFor} jobs are done"
 
-      submit ${JOBID1} 1 ${nFiles} 000 "${alirootEnv} ${self}" "CPass0 ${targetDirectory} ${localInputList} ${nEvents} ${currentDefaultOCDB} ${configFile} ${runNumber} -1 ${extraOpts}"
+      submit ${JOBID1} 1 ${nFiles} 000 "${alirootEnv} ${self}" CPass0 ${targetDirectory} ${localInputList} ${nEvents} ${currentDefaultOCDB} ${configFile} ${runNumber} -1 "${extraOpts[@]}"
 
       ## submit a monitoring job that will run until a certain number of jobs are done with reconstruction
-      submit "${JOBID1wait}" 1 1 000 "${alirootEnv} ${self}" "WaitForOutput ${commonOutputPath} 'meta/cpass0.job*.run${runNumber}.done' ${nFilesToWaitFor} ${maxSecondsToWait} '-maxdepth 1'"
+      submit "${JOBID1wait}" 1 1 000 "${alirootEnv} ${self}" WaitForOutput ${commonOutputPath} "meta/cpass0.job*.run${runNumber}.done" ${nFilesToWaitFor} ${maxSecondsToWait} '-maxdepth 1'
       LASTJOB=${JOBID1wait}
 
     fi #end running CPass0
@@ -1576,11 +1752,11 @@ goSubmitBatch()
         [[ -f ${file} ]] && echo "copying ${file}" && cp -f ${file} ${commonOutputPath}
       done
   
-      submit ${JOBID2} 1 1 "${LASTJOB}" "${alirootEnv} ${self}" "MergeCPass0 ${targetDirectory} ${currentDefaultOCDB} ${configFile} ${runNumber} cpass0.calib.run${runNumber}.list ${extraOpts}"
+      submit ${JOBID2} 1 1 "${LASTJOB}" "${alirootEnv} ${self}" MergeCPass0 ${targetDirectory} ${currentDefaultOCDB} ${configFile} ${runNumber} cpass0.calib.run${runNumber}.list "${extraOpts[@]}"
       LASTJOB=${JOBID2}
 
       if [[ -n ${generateMC} ]]; then
-        submit "mrl${JOBpostfix}" 1 1 "${LASTJOB}" "${alirootEnv} ${self}" "PrintValues sim ${commonOutputPath}/meta/sim.run${runNumber}.list ${commonOutputPath}/meta/cpass0.job*.run${runNumber}.done"
+        submit "mrl${JOBpostfix}" 1 1 "${LASTJOB}" "${alirootEnv} ${self}" PrintValues sim ${commonOutputPath}/meta/sim.run${runNumber}.list ${commonOutputPath}/meta/cpass0.job*.run${runNumber}.done
         LASTJOB="mrl${JOBpostfix}"
       fi
 
@@ -1644,11 +1820,11 @@ goSubmitBatch()
       echo "requested success rate is ${percentProcessedFilesToContinue}%"
       echo "merging will start after ${nFilesToWaitFor} jobs are done"
 
-      submit ${JOBID4} 1 ${nFiles} "${LASTJOB}" "${alirootEnv} ${self}" "CPass1 ${targetDirectory} ${localInputList} ${nEvents} ${currentDefaultOCDB} ${configFile} ${runNumber} -1 ${extraOpts}"
+      submit ${JOBID4} 1 ${nFiles} "${LASTJOB}" "${alirootEnv} ${self}" CPass1 ${targetDirectory} ${localInputList} ${nEvents} ${currentDefaultOCDB} ${configFile} ${runNumber} -1 "${extraOpts[@]}"
 
       ################################################################################
       ## submit a monitoring job that will run until a certain number of jobs are done with reconstruction
-      submit "${JOBID4wait}" 1 1 "${LASTJOB}" "${alirootEnv} ${self}" "WaitForOutput ${commonOutputPath} 'meta/cpass1.job*.run${runNumber}.done' ${nFilesToWaitFor} ${maxSecondsToWait} '-maxdepth 1'"
+      submit "${JOBID4wait}" 1 1 "${LASTJOB}" "${alirootEnv} ${self}" WaitForOutput ${commonOutputPath} "meta/cpass1.job*.run${runNumber}.done" ${nFilesToWaitFor} ${maxSecondsToWait} '-maxdepth 1'
       LASTJOB=${JOBID4wait}
       ################################################################################
 
@@ -1682,32 +1858,32 @@ goSubmitBatch()
         [[ -f ${file} ]] && echo "copying ${file}" && cp -f ${file} ${commonOutputPath}
       done
 
-      submit "${JOBID5}" 1 1 "${LASTJOB}" "${alirootEnv} ${self}" "MergeCPass1 ${targetDirectory} ${currentDefaultOCDB} ${configFile} ${runNumber} cpass0.calib.run${runNumber}.list cpass1.QA.run${runNumber}.lastMergingStage.txt.list ${extraOpts}"
+      submit "${JOBID5}" 1 1 "${LASTJOB}" "${alirootEnv} ${self}" MergeCPass1 ${targetDirectory} ${currentDefaultOCDB} ${configFile} ${runNumber} cpass1.calib.run${runNumber}.list cpass1.QA.run${runNumber}.lastMergingStage.txt.list cpass1.filtered.run${runNumber}.list "${extraOpts[@]}"
       LASTJOB=${JOBID5}
       echo
     fi
 
-    ##############################
-    if [ ${runESDfiltering} -eq 1 ]; then
-      rm -f ${commonOutputPath}/cpass1.ESD.run${runNumber}.list
-      rm -f ${commonOutputPath}/meta/filtering.cpass1.run*.done
-      echo
-      echo submitting filtering for run ${runNumber}
-      echo
-      submit "${JOBmakeESDlistCPass1}" 1 1 "${LASTJOB}" "${self}" "PrintValues esd ${commonOutputPath}/meta/cpass1.ESD.run${runNumber}.list ${commonOutputPath}/meta/cpass1.job*.run${runNumber}.done "
-      submit "${JOBfilterESDcpass1}" 1 1 "${JOBmakeESDlistCPass1}" "${alirootEnv} ${self}" "MakeFilteredTrees ${commonOutputPath}/000${runNumber}/cpass1 ${runNumber} ${commonOutputPath}/meta/cpass1.ESD.run${runNumber}.list ${filteringFactorHighPt} ${filteringFactorV0s} ${currentDefaultOCDB} 1000000 0 10000000 0 ${configFile} AliESDs_Barrel.root ${extraOpts}"
-      LASTJOB=${JOBfilterESDcpass1}
-    fi
+    ###############################
+    #if [ ${runESDfiltering} -eq 1 ]; then
+    #  rm -f ${commonOutputPath}/cpass1.ESD.run${runNumber}.list
+    #  rm -f ${commonOutputPath}/meta/filtering.cpass1.run*.done
+    #  echo
+    #  echo submitting filtering for run ${runNumber}
+    #  echo
+    #  submit "${JOBmakeESDlistCPass1}" 1 1 "${LASTJOB}" "${self}" PrintValues esd ${commonOutputPath}/meta/cpass1.ESD.run${runNumber}.list ${commonOutputPath}/meta/cpass1.job*.run${runNumber}.done 
+    #  submit "${JOBfilterESDcpass1}" 1 1 "${JOBmakeESDlistCPass1}" "${alirootEnv} ${self}" MakeFilteredTrees ${commonOutputPath}/000${runNumber}/cpass1 ${runNumber} ${commonOutputPath}/meta/cpass1.ESD.run${runNumber}.list ${filteringFactorHighPt} ${filteringFactorV0s} ${currentDefaultOCDB} 1000000 0 10000000 0 ${configFile} AliESDs_Barrel.root "${extraOpts[@]}"
+    #  LASTJOB=${JOBfilterESDcpass1}
+    #fi
 
   done
 
   #################################################################################
   #################################################################################
-  if [ ${runESDfiltering} -eq 1 ]; then
-    submit "${JOBID5wait}" 1 1 "${LASTJOB}" "${self}" "WaitForOutput ${commonOutputPath} 'meta/filtering.cpass1.run*.done' ${#listOfRuns[@]} ${maxSecondsToWait}"
-  else
-    submit "${JOBID5wait}" 1 1 "${LASTJOB}" "${self}" "WaitForOutput ${commonOutputPath} 'meta/merge.cpass1.run*.done' ${#listOfRuns[@]} ${maxSecondsToWait}"
-  fi
+  #if [ ${runESDfiltering} -eq 1 ]; then
+  #  submit "${JOBID5wait}" 1 1 "${LASTJOB}" "${self}" WaitForOutput ${commonOutputPath} "meta/filtering.cpass1.run*.done" "${#listOfRuns[@]}" ${maxSecondsToWait}
+  #else
+    submit "${JOBID5wait}" 1 1 "${LASTJOB}" "${self}" WaitForOutput ${commonOutputPath} "meta/merge.cpass1.run*.done" ${#listOfRuns[@]} ${maxSecondsToWait}
+  #fi
   LASTJOB=${JOBID5wait}
 
   #################################################################################
@@ -1715,7 +1891,7 @@ goSubmitBatch()
   echo "submit make a summary"
   echo
 
-  submit "${JOBID6}" 1 1 "${LASTJOB}" "${alirootEnv} ${self}" "MakeSummary ${configFile}"
+  submit "${JOBID6}" 1 1 "${LASTJOB}" "${alirootEnv} ${self}" MakeSummary ${configFile}
   LASTJOB=${JOBID6}
   #################################################################################
   
@@ -1726,7 +1902,7 @@ goSubmitBatch()
 }
 
 goWaitForOutput()
-{
+(
   umask 0002
   [[ $# -lt 3 ]] && echo "goWaitForOutput() wrong number of arguments, exiting.." && return 1
   echo searchPath=${1}
@@ -1750,10 +1926,10 @@ goWaitForOutput()
   done
   echo "DONE! exiting..."
   return 0
-}
+)
 
 mergeSysLogs()
-{
+(
   outputFile=${1}
   shift
   inputFiles="$@"
@@ -1766,10 +1942,10 @@ mergeSysLogs()
     (( i++ ))
   done < <(ls -1 ${inputFiles}) > ${outputFile}
   return 0
-}
+)
 
 goMakeMergedSummaryTree()
-{
+(
   # create list of calibration entries
   # takes no arguments, just run it in the base output
   # directory with the following files in the working directory
@@ -1783,7 +1959,7 @@ goMakeMergedSummaryTree()
   #       summary_pass0.tree
   #       summary_pass1.tree
   #    
+
   [[ ! -f cpass0.dcsTree.list ]] && echo "no cpass0.dcsTree.list" && return 1
   [[ ! -f cpass1.dcsTree.list ]] && echo "no cpass1.dcsTree.list" && return 1
   [[ ! -f trending.root ]] && echo "no trending.root" && return 1
@@ -1811,14 +1987,18 @@ goMakeMergedSummaryTree()
     //
     // Calibration values dump
     //
+    //Printf("MakeTreeFromList cpass0.dcsTree.list");
     AliXRDPROOFtoolkit::MakeTreeFromList("Calib.TPC.CPass0.root", "dcs","dcs","cpass0.dcsTree.list",1);
+    //Printf("MakeTreeFromList cpass1.dcsTree.list");
     AliXRDPROOFtoolkit::MakeTreeFromList("Calib.TPC.CPass1.root", "dcs","dcs","cpass1.dcsTree.list",1);
     //
     // Calibration status dump
     //
     TFile *fprod = TFile::Open("fproduction.root","recreate");
     TTree  tree0, tree1;
+    //Printf("reading summary_pass0.tree");
     tree0.ReadFile("summary_pass0.tree");
+    //Printf("reading summary_pass1.tree");
     tree1.ReadFile("summary_pass1.tree");
     tree0.Write("CPass0");
     tree1.Write("CPass1");
@@ -1834,36 +2014,48 @@ goMakeMergedSummaryTree()
     stringSetup+="1#CPass0#runnumber#CPass0#fproduction.root+";  // 
     stringSetup+="1#CPass1#runnumber#CPass1#fproduction.root+";  // 
     //
+    //Printf("stringSetup: %s", stringSetup.Data());
     AliXRDPROOFtoolkit::JoinTreesIndex("outAll.root","joinAll","run",stringSetup.Data(), 1);
   }
 EOF
 
   aliroot -b -q "mergeTree.C" > mergeTrees.log
   return $?
-}
+)
 
 goMakeSummary()
-{
+(
   #all the final stuff goes in here for ease of use:
   # summary logs
   # qa plot making
   # final file lists
+  #some defaults:
+  log="summary.log"
+  productionID="qa"
 
   configFile=${1}
   shift 1
-  extraOpts="$@"
-  log="summary.log"
-  productionID="qa"
-  parseConfig ${configFile} ${extraOpts}
+  extraOpts=("$@")
+  if ! parseConfig ${configFile} "${extraOpts[@]}"; then return 1; fi
+  
+  #if which greadlink; then configFile=$(greadlink -f ${configFile}); fi
+  
+  #record the working directory provided by the batch system
+  batchWorkingDirectory=${PWD}
   
   [[ -f ${alirootSource} && -z ${ALICE_ROOT} ]] && source ${alirootSource}
 
-  exec &> >(tee ${log})
-
   [[ ! -f ${configFile} ]] && echo "no config file ${configFile}!" && return
 
   [[ -z ${commonOutputPath} ]] && commonOutputPath=${PWD}
 
+  #copy some useful stuff
+  #and go to the commonOutputPath
+  cp ${configFile} ${commonOutputPath}
+  cd ${commonOutputPath}
+
+  exec &> >(tee ${log})
+
   #summarize the global stuff
   echo "env script: ${alirootSource} ${alirootEnv}"
   echo "\$ALICE_ROOT=${ALICE_ROOT}"
@@ -1997,22 +2189,20 @@ done
   rm -f trending.list
   goPrintValues trendingfile trending.list ${commonOutputPath}/meta/merge.cpass1.run*.done &>/dev/null
   rm -f filtering.list
-  goPrintValues filteredTree filtering.list ${commonOutputPath}/meta/filtering.cpass1.run*.done &>/dev/null
-  #/bin/ls ${commonOutputPath}/*/cpass0/dcs* > cpass0.dcsTree.list
+  goPrintValues filteredTree filtering.list ${commonOutputPath}/meta/merge.cpass1.run*.done &>/dev/null
   rm -f cpass0.dcsTree.list
   goPrintValues dcsTree cpass0.dcsTree.list ${commonOutputPath}/meta/merge.cpass0.run*.done &>/dev/null
-  #/bin/ls ${commonOutputPath}/*/cpass1/dcs* > cpass1.dcsTree.list
   rm -f cpass1.dcsTree.list
   goPrintValues dcsTree cpass1.dcsTree.list ${commonOutputPath}/meta/merge.cpass1.run*.done &>/dev/null
  
   #merge trending
   rm -f ${commonOutputPath}/trending_merged.root
-  goMerge trending.list ${commonOutputPath}/trending.root ${configFile} ${extraOpts} &> mergeTrending.log
+  goMerge trending.list ${commonOutputPath}/trending.root ${configFile} "${extraOpts[@]}" &> mergeTrending.log
 
   goMakeSummaryTree ${commonOutputPath} 0
   goMakeSummaryTree ${commonOutputPath} 1
 
-  goCreateQAplots qa.list ${productionID} QAplots ${configFile} ${extraOpts} &>createQAplots.log
+  goCreateQAplots "${PWD}/qa.list" "${productionID}" "QAplots" "${configFile}" "${extraOpts[@]}" filteringList="${PWD}/filtering.list" &>createQAplots.log
 
   #make a merged summary tree out of the QA trending, dcs trees and log summary trees
   goMakeMergedSummaryTree
@@ -2021,10 +2211,10 @@ done
   [[ -n ${MAILTO} ]] && cat ${log} | mail -s "benchmark ${productionID} done" ${MAILTO}
 
   return 0
-}
+)
 
 goMakeSummaryTree()
-{
+(
   if [[ $# -lt 1 ]] ; then
     return
   fi
@@ -2123,48 +2313,103 @@ goMakeSummaryTree()
   done
 
   return 0
-}
+)
 
 parseConfig()
 {
   configFile=${1}
   shift
+  args=("$@")
+
+
+  #some defaults
+  #autoOCDB=0
+  defaultOCDB="raw://"
+  #runNumber=167123
+  #makeflowPath="/hera/alice/aux/cctools/bin"
+  #makeflowOptions="-T wq -N alice -d all -C ali-copilot.cern.ch:9097"
+  #makeflowOptions="-T wq -N alice -C ali-copilot.cern.ch:9097"
+  makeflowOptions=""
+  #batchCommand="/usr/bin/qsub"
+  batchFlags="-b y -cwd -l h_rt=24:0:0,h_rss=4G "
+  baseOutputDirectory="$PWD/output"
+  #alirootEnv="/cvmfs/alice.cern.ch/bin/alienv setenv AliRoot/v5-04-34-AN -c"
+  #alirootEnv="/home/mkrzewic/alisoft/balice_master.sh"
+  #trustedQAtrainMacro='/hera/alice/mkrzewic/gsisvn/Calibration/QAtrain_duo.C'
+  reconstructInTemporaryDir=0
+  recoTriggerOptions="\"\""
+  percentProcessedFilesToContinue=100
+  maxSecondsToWait=$(( 3600*24 ))
+  nEvents=-1
+  nMaxChunks=0
+  postSetUpActionCPass0=""
+  postSetUpActionCPass1=""
+  runCPass0reco=1
+  runCPass0MergeMakeOCDB=1
+  runCPass1reco=1
+  runCPass1MergeMakeOCDB=1
+  runESDfiltering=1
+  filteringFactorHighPt=1e2
+  filteringFactorV0s=1e1
+  MAILTO=""
+  #pretend=1
+  #dontRedirectStdOutToLog=1
+  logToFinalDestination=1
+  ALIROOT_FORCE_COREDUMP=1
+  pretendDelay=0
 
   #first, source the config file
   if [ -f ${configFile} ]; then
     source ${configFile}
   else
-    echo "config file ${configFile} not found!, skipping..."
+    echo "config file ${configFile} not found!"
+    return 1
   fi
 
-  #then, parse the options as theya override the optionf from file
-  while [[ -n ${1} ]]; do
-    var="${1#--}"
-    echo "extraOpts: exporting ${var}"
-    eval "export ${var}"
-    shift
+  unset encodedSpaces
+  for opt in "${args[@]}"; do
+    [[ "${opt}" =~ encodedSpaces=.* ]] && encodedSpaces=1 && echo "encodedSpaces!" && break
   done
 
+  #then, parse the options as they override the options from file
+  for opt in "${args[@]}"; do
+    [[ -z ${opt} ]] && continue
+    [[ -n ${encodedSpaces} ]] && opt="$(decSpaces ${opt})"
+    [[ "${opt}" =~ ^[[:space:]]*$ ]] && continue
+    if [[ ! "${opt}" =~ .*=.* ]]; then
+      echo "badly formatted option \"${opt}\" should be: option=value, stopping..."
+      return 1
+    fi
+    local var="${opt%%=*}"
+    local value="${opt#*=}"
+    echo "${var} = ${value}"
+    export ${var}="${value}"
+  done
+
+  #do some checking
+  [[ -z ${alirootEnv} ]] && echo "alirootEnv not defined!" && return 1
+
   #export the aliroot function if defined to override normal behaviour
   [[ $(type -t aliroot) =~ "function" ]] && export -f aliroot
+
   return 0
 }
 
 aliroot()
 {
   args="$@"
-  if [[ -n ${valgrindCommand} ]]; then
+  if [[ -n ${useProfilingCommand} ]]; then
     valgrindLogFile="cpu.txt"
     [[ "${args}" =~ rec ]] && valgrindLogFile="cpu_rec.txt"
     [[ "${args}}" =~ Calib ]] && valgrindLogFile="cpu_calib.txt"
-    [[ -n ${valgrindCommand} ]] && valgrindCommand="${valgrindCommand} --log-file=${valgrindLogFile}"
-    echo running ${valgrindCommand} aliroot ${args}
-    ${valgrindCommand} aliroot ${args}
+    [[ -n ${useProfilingCommand} ]] && useProfilingCommand="${useProfilingCommand} --log-file=${valgrindLogFile}"
+    echo running ${useProfilingCommand} aliroot ${args}
+    ${useProfilingCommand} aliroot ${args}
   else
     #to prevent an infinite recursion use "command aliroot" to disable
     #aliases and functions
     echo running command aliroot ${args}
-    command aliroot ${args}
+    command aliroot "$@"
   fi
   return 0
 }
@@ -2215,4 +2460,10 @@ guessRunData()
   return 0
 }
 
+#these functions encode strings to and from a space-less form
+#use when spaces are not well handled (e.g. in arguments to 
+#commands in makeflow files, etc.
+encSpaces()(echo "${1// /@@@@}")
+decSpaces()(echo "${1//@@@@/ }")
+
 main "$@"