Index: /BAORadio/AmasNancay/v5/anacalibmaker.sh
===================================================================
--- /BAORadio/AmasNancay/v5/anacalibmaker.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/anacalibmaker.sh	(revision 596)
@@ -0,0 +1,331 @@
+#!/bin/sh -xvf
+#do calibration
+DATE=/bin/date
+GREP=/bin/grep
+AWK=/bin/awk
+ECHO=/bin/echo
+WC=/usr/bin/wc
+CAT=/bin/cat
+PRINTF=/usr/bin/printf
+FIND=/usr/bin/find
+MKDIR=/bin/mkdir
+XARGS=/usr/bin/xargs
+SORT=/bin/sort
+RM=/bin/rm
+TR=/usr/bin/tr
+CP=/bin/cp
+LS=/bin/ls
+CHMOD=/bin/chmod
+
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+#set Irods environment    
+. /usr/local/shared/bin/irods_env.sh -noverbose
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+#which source to analyse
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+dateSelected=
+freqBAOCalib=1346
+bwBAOCalib=6.25
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=Off
+while [ $# -gt 0 ]
+  do
+  case "$1" in
+      -src)  sourceRadio=$2; shift;;
+      -date) dateSelected=$2;     shift;;
+      -freq) freqBAOCalib=$2; shift;;
+      -bwd)  bwBAOCalib=$2; shift;;
+      -sim)  simulationMode=On;;
+      -h)
+      echo >&2 \
+	  "usage: $0 -src souce -date YYYYMMDD [-freq freq in MHz (default ${freqBAOCalib})] [-bwd bandwidth in MHz (default ${bwBAOCalib})]"
+      exit 1;;
+      *)  break;;	# terminate while loop
+  esac
+  shift
+done
+
+if [ ${simulationMode} = "On" ]; then
+    $ECHO "INFO ${scriptName} running in SIMUL mode"
+fi
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+case ${sourceRadio} in
+    Abell85) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    Abell2440) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    Abell1205) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    *) ECHO "FATAL (${scriptName}): process ${sourceRadio} not yet foreseen"
+    exit 1;;
+esac
+
+srclower=`${ECHO} ${sourceRadio} | ${TR} "[:upper:]" "[:lower:]" `
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+#wakeup the NFS disk
+$LS -l ${tmppublicpath} > /dev/null
+#clean previous spurious files
+$RM -f ${tmppublicpath}/*.finished
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/isInteractive.sh
+isInteractive=$(isInteractive)
+if [ ${isInteractive} == "1" ]; then
+  $ECHO "Usage in INTERACTIVE may be destructive... To be used with great care !!!!"
+   exit 0;
+fi
+
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+localpath="${sourceRadio}"
+$MKDIR -p ./${localpath}
+cd ./${localpath}
+
+#save the top directory
+topDir=`pwd`
+
+#Path of the utility scripts
+scriptpath=${SCRIPTPATH}
+
+#JEC 1/10/11 Use generic baodaqstatus name 
+OUT1=${publicpath}/baodaqstatus-current.txt
+#
+#get the daq current irod status
+#tag=`${DATE} +%F`
+#OUT1=${publicpath}/baodaqstatus-${tag}.txt
+#
+if [ ! -e ${OUT1}  -o ! -r ${OUT1} ]; then
+    $ECHO "FATAL (${scriptName}): ${OUT1} has a problem"
+    exit 1
+fi
+
+
+#Nb: if we want to implement a loop on sources we have to take care of srclower...
+
+$ECHO "You have selected sourceRadio = $sourceRadio[date = ${dateSelected}]"
+tableau=( `$GREP -i "${dateSelected}${srclower}" ${OUT1} | $AWK '( NF==4 ) { print $2 }' ` )
+IFS='
+' 
+tableau=( $( $PRINTF "%s\n" "${tableau[@]}" | $AWK 'x[$0]++ == 0' ) )
+IFS=$DefaultIFS
+
+
+for i in ${tableau[@]}
+  do
+#
+# start a "fresh" session  
+  cd ${topDir}
+  $LS | $XARGS -i $RM -rf {}
+
+  
+  $ECHO "DEBUG: (${scriptName}) irods root dir $i"
+  dateDAQ=`$ECHO ${i} | $AWK '{split($0,a,"/"); print a[6];}' | $AWK "{sub(/${srclower}/,\"\"); print}"`
+
+  $ECHO "DEBUG: (${scriptName}): we are in directory `pwd` the topDir=${topDir}"
+  $LS -lrt
+
+
+#  alreadyDone=`ils ${i} 2>&1 | $GREP -i "calib_.*\.txt" | $WC -l`
+#  if [ ${alreadyDone} -gt 0 ]; then
+#      $ECHO "INFO (${scriptName}): calibration coef files already exist"
+#      continue
+#  fi
+
+  gainDone=`ils ${i} 2>&1 | $GREP -i "gain_.*\.fits" | $WC -l`
+  if [ ! ${gainDone} -gt 0 ]; then
+      $ECHO "FATAL (${scriptName}): gain file DOES NOT exist skip `basename $i` "
+      continue
+  fi
+
+######
+  $ECHO ">>>>>>>>>>>>> ANALYSIS Part of ${sourceRadio} ${dateDAQ}"
+#go to the .../source/date-sourcelowercase directory
+#download Off/calibcycle<> and On/calibcycle<> directories
+  $MKDIR -p ${topDir}/${dateDAQ}${srclower}
+  cd ${topDir}/${dateDAQ}${srclower}
+  aboveOnOffDir=`pwd`
+  $ECHO "DEBUG (${scriptName}): we are in directory: <`pwd`>"
+#
+  mode="Off"
+  $ECHO "DEBUG (${scriptName}): START download the ${mode} calib fits files"
+  inFileDirectory="./${mode}"
+  $MKDIR -p ${inFileDirectory}
+  listOfCalibCycle=( `ils ${i}/${mode} 2>&1 | $GREP -i "calibcycle"|$AWK 'BEGIN{FS="C- "}{print $2}' | $XARGS -i basename {} | $SORT -k1.11n` )
+  IFS='
+'
+  listOfCalibCycle=( $( $PRINTF "%s\n" "${listOfCalibCycle[@]}" | $AWK 'x[$0]++ == 0' ) )
+  IFS=$DefaultIFS
+
+  firstCycleOff=`$ECHO ${listOfCalibCycle[0]} | $AWK '{match($0,"[0-9]+",arr); print arr[0]}'`
+  nCyclesOff=`expr ${#listOfCalibCycle[*]} - 1`
+
+  lastCycleOff=`$ECHO ${listOfCalibCycle[${nCyclesOff}]} | $AWK '{match($0,"[0-9]+",arr); print arr[0]}'`
+
+  listOfCalibCycle=( "${listOfCalibCycle[@]/#/${i}/${mode}/}" )
+
+  
+  for j in ${listOfCalibCycle[@]}
+    do
+    irodsDownDir="${j}"
+    OUT=./getInFits.$$
+    iget -r -f -K ${irodsDownDir} ${inFileDirectory} > ${OUT} 2>&1
+    igetStatus=`$GREP "^ERROR" ${OUT}`
+    if [ "<$igetStatus>" != "<>" ]; then
+	$ECHO "FATAL (${scriptName}): error while iget fits files:"
+	$ECHO $igetStatus
+	$ECHO " ==> skip this run $sourceRadio $dateDAQ"
+	continue
+    fi
+    $RM -f ${OUT}
+  done
+  $ECHO "DEBUG (${scriptName}): END download the ${mode} calib fits files"
+#
+  mode="On"
+  $ECHO "DEBUG (${scriptName}): START download the ${mode} calib fits files"
+  inFileDirectory="./${mode}"
+  $MKDIR -p ${inFileDirectory}
+
+  listOfCalibCycle=( `ils ${i}/${mode} 2>&1 | $GREP -i "calibcycle" |$AWK 'BEGIN{FS="C- "}{print $2}' | $XARGS -i basename {} | $SORT -k1.11n` )
+  IFS='
+  '
+  listOfCalibCycle=( $( $PRINTF "%s\n" "${listOfCalibCycle[@]}" | $AWK 'x[$0]++ == 0' ) )
+  IFS=$DefaultIFS
+
+  firstCycleOn=`$ECHO ${listOfCalibCycle[0]} | $AWK '{match($0,"[0-9]+",arr); print arr[0]}'`
+  nCyclesOn=`expr ${#listOfCalibCycle[*]} - 1`
+
+  lastCycleOn=`$ECHO ${listOfCalibCycle[${nCyclesOn}]} | $AWK '{match($0,"[0-9]+",arr); print arr[0]}'`
+
+  listOfCalibCycle=( "${listOfCalibCycle[@]/#/${i}/${mode}/}" )
+
+
+#
+#Check if there is the same number of cycles in Off and On mode
+#      
+#first cycle = max(firstCycleOn, firstCycleOff)
+#last  cycle = min(lastCycleOn,lastCycleOff)
+
+  if [ ${firstCycleOn} -eq ${firstCycleOff} -a ${lastCycleOn} -eq ${lastCycleOff} ]; then
+      firstCycle=${firstCycleOff}
+      lastCycle=${lastCycleOff}
+  else
+      $ECHO "INFO (${scriptName}): missmatch between Off and On mode"
+      $ECHO "${firstCycleOn} != ${firstCycleOff} OR ${lastCycleOn} != ${lastCycleOff}"
+      firstCycle=${firstCycleOff}
+      if [ ${firstCycleOn} -gt ${firstCycle} ]; then
+	  firstCycle=${firstCycleOn}
+      fi
+      lastCycle=${lastCycleOff}
+      if [ ${lastCycleOn} -lt ${lastCycle} ]; then
+	  lastCycle=${lastCycleOn}
+      fi
+  fi
+  $ECHO "INFO (${scriptName}): use cycles [${firstCycle}, ${lastCycle}]"
+  
+
+  for j in ${listOfCalibCycle[@]}
+    do
+    irodsDownDir="${j}"
+    OUT=./getInFits.$$
+    iget -r -f -K ${irodsDownDir} ${inFileDirectory} > ${OUT} 2>&1
+    igetStatus=`$GREP "^ERROR" ${OUT}`
+    if [ "<$igetStatus>" != "<>" ]; then
+	$ECHO "FATAL (${scriptName}): error while iget fits files:"
+	$ECHO $igetStatus
+	$ECHO " ==> skip this run $sourceRadio $dateDAQ"
+	continue
+    fi
+    $RM -f ${OUT}
+  done
+  $ECHO "DEBUG (${scriptName}): END download the ${mode} calib fits files"
+#Get sca file
+  $ECHO "DEBUG (${scriptName}): START call getscafiles.sh ${sourceRadio} ${dateDAQ}"
+  OUT1=./getScaStatus.$$
+  $RM -f ${tmppublicpath}/getscafiles.finished
+  ${scriptpath}/getscafiles.sh ${sourceRadio} ${dateDAQ} > ${OUT1} 2>&1
+#  while [ ! -f "${tmppublicpath}/getscafiles.finished" ]; do
+#      $ECHO "INFO (${scriptName}): waiting for ${tmppublicpath}/getscafiles.finished"
+#      date +%T
+#      sleep 30
+#  done
+  $RM ${tmppublicpath}/getscafiles.finished
+  $ECHO "DEBUG (${scriptName}): END"
+#
+  getScaStatus=`$GREP "^\(FATAL\|ERROR\)" ${OUT1}`
+#	
+  if [ "<${getScaStatus}>" != "<>" ]; then
+      $ECHO "FATAL (${scriptName}): error to get sca file for $sourceRadio $dateDAQ"
+      $ECHO "DEBUG (${scriptName}): START with cat ${OUT1}"
+      $CAT ${OUT1}
+      $ECHO "DEBUG (${scriptName}): END"
+      continue
+  fi
+  $RM -f ${OUT1}
+
+  scaFile=`$FIND . -name "sca*.sum.trans" | $XARGS -i basename {}`
+  
+#prepare job submission
+  cd ${aboveOnOffDir}
+#the default spectra name is medfiltmtx, otherwise use -specname <a_string>
+
+  logFile="analyse_CALIB_${sourceRadio}_${dateDAQ}.log"
+  $ECHO "DEBUG (${scriptName}): execute the analysis... should not take long. `date`"
+  if [ ${simulationMode} = "On" ]; then
+      $ECHO "SIMUL: ${scriptpath}/Objs/analyse -act calib -inPath ${iojobpath}  -source  ${sourceRadio} -date ${dateDAQ} -sca ${scaFile} -specdir calibcycle -numcycle ${firstCycle},${lastCycle} -calibopt mean  -debug 1 -freqBAOCalib ${freqBAOCalib} -bwBAOCalib ${bwBAOCalib} >& ${logFile}"
+      cat > ${logFile} <<EOF
+      Ok calibration finished
+EOF
+#WARNING: the EOF must start at 1st column overwise the rest of the script is part of the file cat...
+  else
+      ${scriptpath}/Objs/analyse -act calib -inPath ${iojobpath}  -source  ${sourceRadio} -date ${dateDAQ} -sca ${scaFile} -specdir calibcycle  -numcycle ${firstCycle},${lastCycle} -calibopt mean  -debug 1 -freqBAOCalib ${freqBAOCalib} -bwBAOCalib ${bwBAOCalib} >& ${logFile}
+  fi
+#
+  $ECHO "DEBUG (${scriptName}): analysis finished `date`. Look for errors before saving to Irods"
+  rcstatus=`$GREP -i "Ok calibration finished" ${logFile} | $WC -l`
+  if [ ${rcstatus} -eq 0 ]; then
+      $ECHO "INFO (${scriptName}): analysis problem for ${sourceRadio} ${dateDAQ}"
+      $ECHO "                      START logfile"
+      $CAT ${logFile}
+      $ECHO "                      END   logFile"
+#clean and leave
+      cd ${aboveOnOffDir}
+      $LS | $XARGS -i $RM -rf {}
+      continue
+  fi
+#Save into Irods
+  $ECHO "DEBUG (${scriptName}): START save output files"
+  $LS ${aboveOnOffDir}
+#use -f option for iput ONLY to force override
+  if [ ${simulationMode} = "On" ]; then
+      $ECHO "SIMUL: here we look for calib file and put them in Irods"
+  else
+      $LS -lrth
+      $FIND . -name "calib_*" -print | $XARGS -i  iput -f  -v -K {} ${i}
+  fi
+#save analysis logfile
+  $LS -l ${tmppublicpath} > /dev/null
+  $CP ${logFile} ${tmppublicpath}
+  $ECHO "DEBUG (${scriptName}): END save output files"
+#clean up to avoid scratch SIZE EXCEED LIMIT
+  cd ${aboveOnOffDir}
+  $LS | $XARGS -i $RM -rf {}
+
+done
+
+exit 0
Index: /BAORadio/AmasNancay/v5/anagainmaker.sh
===================================================================
--- /BAORadio/AmasNancay/v5/anagainmaker.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/anagainmaker.sh	(revision 596)
@@ -0,0 +1,248 @@
+#!/bin/sh -xvf
+#download SCA file, proceed to introspection, and upload results
+DATE=/bin/date
+GREP=/bin/grep
+AWK=/bin/awk
+ECHO=/bin/echo
+WC=/usr/bin/wc
+CAT=/bin/cat
+PRINTF=/usr/bin/printf
+FIND=/usr/bin/find
+MKDIR=/bin/mkdir
+XARGS=/usr/bin/xargs
+SORT=/bin/sort
+RM=/bin/rm
+TR=/usr/bin/tr
+CP=/bin/cp
+LS=/bin/ls
+CHMOD=/bin/chmod
+
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+#set Irods environment    
+. /usr/local/shared/bin/irods_env.sh -noverbose
+
+scriptName="`basename $0`"
+#$ECHO "Processing script ${scriptName} at `date`"
+
+#$ECHO "SHOULD BE RETUNED FOR THE inPath cmd line of analyse.cc (Sorry...): 21/7/11 by JEC"
+#exit 1
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+dateSelected=
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=Off
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -src)  sourceRadio=$2; shift;;
+      -date) dateSelected=$2; shift;;
+       -sim) simulationMode=On;;
+	-h)
+	    echo >&2 \
+	    "usage: $0 -src souce -date YYYYMMDD [-sim]"
+	    exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+if [ ${simulationMode} = "On" ]; then
+    $ECHO "INFO ${scriptName} running in SIMUL mode"
+fi
+
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+case ${sourceRadio} in
+    Abell85) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    Abell2440) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    Abell1205) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    *) ECHO "FATAL (${scriptName}): process ${sourceRadio} not yet foreseen"
+    exit 1;;
+esac
+
+
+srclower=`${ECHO} ${sourceRadio} | ${TR} "[:upper:]" "[:lower:]" `
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+$LS -l ${tmppublicpath} > /dev/null
+#clean previous spurious files
+$RM -f ${tmppublicpath}/*.finished
+
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/isInteractive.sh
+isInteractive=$(isInteractive)
+if [ ${isInteractive} == "1" ]; then
+  $ECHO "Usage in INTERACTIVE may be destructive... To be used with great care !!!!"
+   exit 0;
+fi
+
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+localpath="${sourceRadio}"
+$MKDIR -p ./${localpath}
+cd ./${localpath}
+
+#save the top directory
+topDir=`pwd`
+
+#Path of the utility scripts
+scriptpath=${SCRIPTPATH}
+
+
+#JEC 1/10/11 Use generic baodaqstatus name 
+#get the daq current irod status
+#tag=`${DATE} +%F`
+#OUT1=${publicpath}/baodaqstatus-${tag}.txt
+OUT1=${publicpath}/baodaqstatus-current.txt
+
+if [ ! -e ${OUT1}  -o ! -r ${OUT1} ]; then
+    $ECHO "FATAL (${scriptName}): ${OUT1} has a problem"
+    exit 1
+fi
+
+#
+$ECHO "You have selected sourceRadio = $sourceRadio [date = ${dateSelected}]"
+tableau=( `$GREP -i "${dateSelected}${srclower}" ${OUT1} | $AWK '( NF==4 ) { print $2 }' ` )
+IFS='
+'
+tableau=( $( $PRINTF "%s\n" "${tableau[@]}" | $AWK 'x[$0]++ == 0' ) )
+IFS=$DefaultIFS
+
+
+for i in ${tableau[@]}
+  do
+# start a "fresh" session  
+  cd ${topDir}
+  $LS | $XARGS -i $RM -rf {}
+
+  $ECHO "DEBUG (${scriptName}): irods root dir $i"
+  dateDAQ=`$ECHO ${i} | $AWK '{split($0,a,"/"); print a[6];}' | $AWK "{sub(/${srclower}/,\"\"); print}"`
+
+  $LS -lrt
+
+######
+  $ECHO ">>>>>>>>>>>>> ANALYSIS Part of ${sourceRadio} ${dateDAQ}"
+#go to the .../source/date-sourcelowercase directory
+  $MKDIR -p ${topDir}/${dateDAQ}${srclower}
+  cd ${topDir}/${dateDAQ}${srclower}
+  aboveOnOffDir=`pwd`
+  $ECHO "DEBUG (${scriptName}): we are in directory: <`pwd`>"
+# So the input files are there, so the fits file can be determined
+  mode="Off"
+
+  input4gainOk1=`ils ${i}/Off 2>&1 | $GREP -i "^ERROR" | $WC -l` 
+  input4gainOk2=`ils ${i}/Off 2>&1 | $GREP -i "gaincycle"` 
+  if [ $input4gainOk1 -eq 0 -a "<${input4gainOk2}>" != "<>"  ]; then
+      gaincycle=`$ECHO ${input4gainOk2} | $AWK '($1 == "C-"){print $2}'| $XARGS -i basename {}`
+  else
+      $ECHO "INFO ${scriptName}: no gaincycle for ${i}"
+      continue
+  fi
+
+  spectraGenDirName=`$ECHO ${gaincycle} | $AWK '{match($0,"[a-zA-Z]+",arr); print arr[0]}'`
+  cycleNumber=`$ECHO ${gaincycle} | $AWK '{match($0,"[0-9]+",arr); print arr[0]}'`
+#care: the gaincycle variable contains the cycle number
+  $ECHO "DEBUG (${scriptName}): START download the fits files"
+  inFileDirectory="./${mode}"
+  $MKDIR -p ${inFileDirectory}
+  irodsDownDir="${i}/${mode}/${gaincycle}"
+  OUT=./getInFits.$$
+  iget -r -f -K ${irodsDownDir} ${inFileDirectory} > ${OUT} 2>&1
+  $LS ${inFileDirectory}/${gaincycle}
+  igetStatus=`$GREP "^ERROR" ${OUT}`
+  if [ "<$igetStatus>" != "<>" ]; then
+      $ECHO "FATAL (${scriptName}): error while iget fits files:"
+      $ECHO $igetStatus
+      continue
+  fi
+  $RM -f ${OUT}
+  $ECHO "DEBUG (${scriptName}): END download the fits files"
+#Get sca files
+  $ECHO "DEBUG (${scriptName}): START call getscafiles.sh ${sourceRadio} ${dateDAQ}"
+  OUT1=./getScaStatus.$$
+  $RM -f ${tmppublicpath}/getscafiles.finished
+  ${scriptpath}/getscafiles.sh ${sourceRadio} ${dateDAQ} > ${OUT1} 2>&1
+# AST 21/10/2011: comment while as it blocks the job
+#  while [ ! -f "${tmppublicpath}/getscafiles.finished" ]; do
+#      $ECHO "INFO (${scriptName}): waiting for ${tmppublicpath}/getscafiles.finished"
+#      date +%T
+#      sleep 30
+#  done
+  $RM ${tmppublicpath}/getscafiles.finished
+  $ECHO "DEBUG (${scriptName}): END"
+#
+  getScaStatus=`$GREP "^\(FATAL\|ERROR\)" ${OUT1}`
+#	
+  if [ "<${getScaStatus}>" != "<>" ]; then
+      $ECHO "FATAL (${scriptName}): error to get sca file for $sourceRadio $dateDAQ"
+      $ECHO "DEBUG (${scriptName}): START with cat ${OUT1}"
+      $CAT ${OUT1}
+      $ECHO "DEBUG (${scriptName}): END"
+      continue
+  fi
+  $RM -f ${OUT1}
+  $ECHO "DEBUG (${scriptName}): where am i `pwd`"
+  $LS -lrt
+  
+  scaFile=`$FIND . -name "sca*.sum.trans" | $XARGS -i basename {}`
+#	
+#the default spectra name is medfiltmtx, otherwise use -specname <a_string>
+  logFile="analyse_GAIN_${sourceRadio}_${dateDAQ}.log"
+  $ECHO "DEBUG (${scriptName}): execute the analysis... should not take long. `date`"
+  if [ ${simulationMode} = "On" ]; then
+      $ECHO "SIMUL: ${scriptpath}/Objs/analyse -act gain  -inPath ${iojobpath} -source  ${sourceRadio} -date ${dateDAQ} -sca ${scaFile} -specdir ${spectraGenDirName} -mode ${mode} -numcycle ${cycleNumber},${cycleNumber} -debug 1 >& ${logFile}"
+      cat > ${logFile} <<EOF
+      Ok gain finished
+EOF
+
+  else
+      ${scriptpath}/Objs/analyse -act gain  -inPath ${iojobpath} -source  ${sourceRadio} -date ${dateDAQ} -sca ${scaFile} -specdir ${spectraGenDirName} -mode ${mode} -numcycle ${cycleNumber},${cycleNumber} -debuglev 1 >& ${logFile}
+  fi
+#
+  $ECHO "DEBUG (${scriptName}): analysis finished `date`. Look for errors before saving to Irods"
+  rcstatus=`$GREP -i "OK gain finished" ${logFile} | $WC -l`
+  if [ ${rcstatus} -eq 0 ]; then
+      $ECHO "INFO (${scriptName}): analysis problem for ${sourceRadio} ${dateDAQ}"
+      $ECHO "                      START logfile"
+      $CAT ${logFile}
+      $ECHO "                      END   logFile"
+#clean and leave
+      cd ${aboveOnOffDir}
+      $RM -rf ./*
+      continue
+  fi
+#Save into Irods
+  $ECHO "DEBUG (${scriptName}): START save output files"
+  $LS ${aboveOnOffDir}
+#use -f option of iput ONLY to force override
+  if [ ${simulationMode} = "On" ]; then
+      $ECHO "SIMUL: here we look for gain file and put them in Irods"
+  else
+      $FIND . -name "gain_*" -print | $XARGS -i  iput -f -v -K {} ${i}
+  fi
+#save analysis logfile
+  $LS -l ${tmppublicpath} > /dev/null
+  $CP ${logFile} ${tmppublicpath}
+  $ECHO "DEBUG (${scriptName}): END save output files"
+#clean
+  cd ${aboveOnOffDir}
+  $LS | $XARGS -i $RM -rf {}
+
+done
+
+exit 0
Index: /BAORadio/AmasNancay/v5/analyse.cc
===================================================================
--- /BAORadio/AmasNancay/v5/analyse.cc	(revision 596)
+++ /BAORadio/AmasNancay/v5/analyse.cc	(revision 596)
@@ -0,0 +1,1870 @@
+//
+// Analyse of Amas@Nancay runs by J.E Campagne (LAL)
+// Version 0: 1/6/2011
+//-----------------------------
+
+// Utilisation de SOPHYA pour faciliter les tests ...
+#include "sopnamsp.h"
+#include "machdefs.h"
+
+#include <stdlib.h>
+#include <dirent.h>
+#include <matharr.h>
+
+// include standard c/c++
+#include <iostream>
+#include <fstream>
+#include <string>
+#include <vector>
+#include <map>
+#include <functional>
+#include <algorithm>
+#include <numeric>
+#include <list>
+#include <exception>
+
+// include sophya mesure ressource CPU/memoire ...
+#include "resusage.h"
+#include "ctimer.h"
+#include "timing.h"
+#include "timestamp.h"
+#include "strutilxx.h"
+#include "ntuple.h"
+#include "fioarr.h"
+#include "tarrinit.h"
+#include "histinit.h"
+#include "fitsioserver.h"
+#include "fiosinit.h"
+#include "ppersist.h"
+
+
+const sa_size_t NUMBER_OF_CHANNELS = 2;
+const sa_size_t  NUMBER_OF_FREQ = 8192;
+const r_4    LOWER_FREQUENCY = 1250.0; //MHz
+const r_4    TOTAL_BANDWIDTH = 250.0; //MHz
+
+//decalration of non class members functions
+extern "C" {
+  int Usage(bool);
+}
+
+
+//----------------------------------------------------------
+//Utility fonctions
+class median_of_empty_list_exception:public std::exception{
+    virtual const char* what() const throw() {
+    return "Attempt to take the median of an empty list of numbers.  "
+      "The median of an empty list is undefined.";
+  }
+};
+template<class RandAccessIter>
+double median(RandAccessIter begin, RandAccessIter end) 
+  throw(median_of_empty_list_exception){
+  if(begin == end){ throw median_of_empty_list_exception(); }
+  std::size_t size = end - begin;
+  std::size_t middleIdx = size/2;
+  RandAccessIter target = begin + middleIdx;
+  std::nth_element(begin, target, end);
+    
+  if(size % 2 != 0){ //Odd number of elements
+    return *target;
+  }else{            //Even number of elements
+    double a = *target;
+    RandAccessIter targetNeighbor= target-1;
+    std::nth_element(begin, targetNeighbor, end);
+    return (a+*targetNeighbor)/2.0;
+  }
+}
+
+//-------------
+
+// Function for deleting pointers in map.
+template<class A, class B>
+struct DeleteMapFntor
+{
+    // Overloaded () operator.
+    // This will be called by for_each() function.
+    bool operator()(pair<A,B> x) const
+    {
+        // Assuming the second item of map is to be
+        // deleted. Change as you wish.
+        delete x.second;
+        return true;
+    }
+};
+//-----
+bool compare(const pair<string,r_4>& i, const pair<string,r_4>& j) {
+  return i.second < j.second;
+}
+//-----
+sa_size_t round_sa(r_4 r) {
+  return static_cast<sa_size_t>((r > 0.0) ? (r + 0.5) : (r - 0.5));
+}
+//-----
+string StringToLower(string strToConvert){
+  //change each element of the string to lower case
+  for(unsigned int i=0;i<strToConvert.length();i++) {
+    strToConvert[i] = tolower(strToConvert[i]);
+  }
+  return strToConvert;//return the converted string
+}
+//-----
+//JEC 22/9/11 comparison, not case sensitive to sort File liste START
+bool stringCompare( const string &left, const string &right ){
+   if( left.size() < right.size() )
+      return true;
+   ////////////POSSIBLY A BUG return false;
+   for( string::const_iterator lit = left.begin(), rit = right.begin(); lit != left.end() && rit != right.end(); ++lit, ++rit )
+      if( tolower( *lit ) < tolower( *rit ) )
+         return true;
+      else if( tolower( *lit ) > tolower( *rit ) )
+         return false;
+   return false; ///////TO BE FIXED
+}//JEC 22/9/11 comparison, not case sensitive to sort File liste END
+//-----
+list<string> ListOfFileInDir(string dir, string filePettern) throw(string) {
+  list<string> theList;
+
+
+  DIR *dip;
+  struct dirent *dit;
+  string msg;  string fileName;
+  string fullFileName;
+  size_t found;
+
+  if ((dip=opendir(dir.c_str())) == NULL ) {
+    msg = "opendir failed on directory "+dir;
+    throw msg;
+  }
+  while ( (dit = readdir(dip)) != NULL ) {
+    fileName = dit->d_name;
+    found=fileName.find(filePettern);
+    if (found != string::npos) {
+      fullFileName = dir + "/";
+      fullFileName += fileName;
+      theList.push_back(fullFileName);
+    }
+  }//eo while
+  if (closedir(dip) == -1) {
+    msg = "closedir failed on directory "+dir;
+    throw msg;
+  }
+  
+  //JEC 22/9/11 START
+  theList.sort(stringCompare);
+  //JEC 22/9/11 END
+
+  return theList;
+}
+
+
+//Declaration of local classes
+//----------------------------------------------
+//Process Interface
+class IProcess {
+public:
+  IProcess() {}
+  virtual ~IProcess() {}
+  virtual int processCmd() throw(string) =0;
+};
+//------------
+//Common Process
+class ProcessBase : public IProcess {
+public:
+  ProcessBase();
+  virtual ~ProcessBase();
+  void SetInputPath(const string& inputPath) {inputPath_ = inputPath;}
+  void SetOutputPath(const string& outputPath) {outputPath_ = outputPath;}
+  void SetSourceName(const string& sourceName) {sourceName_ = sourceName;}
+  void SetDateOfRun(const string& dateOfRun) {dateOfRun_ = dateOfRun;}
+  void SetSpectraDirectory(const string& spectraDirectory) {spectraDirectory_ = spectraDirectory;}
+  void SetTypeOfFile(const string& typeOfFile) { typeOfFile_ = typeOfFile; }
+  void SetNumCycle(const string& numcycle) {numcycle_ = numcycle; }
+  void SetScaFileName(const string& scaFileName) { scaFileName_ =scaFileName; }
+
+  void SetDebugLevel(const string& debuglev) {
+    debuglev_ = atoi(debuglev.c_str());
+  }
+
+  virtual int processCmd() throw(string);
+  
+protected:
+  string inputPath_;
+  string outputPath_;
+  string sourceName_;
+  string dateOfRun_;
+  string spectraDirectory_;
+  string typeOfFile_;
+
+  string numcycle_; //cycle numbers format="first,last"
+  sa_size_t ifirstCycle_;
+  sa_size_t ilastCycle_;
+
+
+  uint_4 debuglev_; 
+  string scaFileName_;
+  NTuple* scaTuple_;
+  map<sa_size_t,sa_size_t> idCycleInTuple_;
+};
+ProcessBase::ProcessBase() {
+  scaTuple_ = 0;
+}
+ProcessBase::~ProcessBase() {
+  if (scaTuple_) delete scaTuple_;
+  scaTuple_ = 0;
+}
+//------------
+//Process ON/OFF data
+//------------
+class ProcessONOFFData : public ProcessBase {
+protected:
+  string  freqBAOCalibration_;//string MHz
+public:
+  ProcessONOFFData(){}
+  virtual ~ProcessONOFFData(){}
+
+  void SetFreqBAOCalibration(const string& freqBAOCalibration) { 
+    freqBAOCalibration_ = freqBAOCalibration; 
+  }
+  
+  virtual int processCmd() throw(string);
+};
+
+
+//------------
+//Process ON/OFF Raw data
+//------------
+class ProcessONOFFRawData : public ProcessBase {
+
+public:
+  ProcessONOFFRawData(){}
+  virtual ~ProcessONOFFRawData(){}
+  
+  virtual int processCmd() throw(string);
+};
+
+//------------
+//Process ON/OFF data treated with the mspec (specmfib) => no filtering at all: paquets & freq.
+//------------
+class ProcessONOFFMeanData : public ProcessBase {
+
+public:
+  ProcessONOFFMeanData(){}
+  virtual ~ProcessONOFFMeanData(){}
+  
+  virtual int processCmd() throw(string);
+};
+
+
+//------------
+//Process Gain
+//------------
+class ProcessGain : public ProcessBase {
+protected:
+  string mode_; //mode of data taken for gain computation On || Off
+public:
+  ProcessGain(){}
+  virtual ~ProcessGain(){}
+
+  void SetMode(const string& mode) {mode_ = mode;}
+  
+  virtual int processCmd() throw(string);
+};
+//------------
+//Process Calibration
+//------------
+class ProcessCalibration : public ProcessBase {
+protected:
+  string option_; //option of calibration procedure
+  string  freqBAOCalibration_;//string MHz
+  r_4 valfreqBAOCalibration_; //value MHz
+  string bandWidthBAOCalibration_;//string MHz
+  r_4 valbandWidthBAOCalibration_;//value MHz
+  
+  sa_size_t lowerFreqBin_;
+  sa_size_t upperFreqBin_;
+
+public:
+  ProcessCalibration() {}
+  virtual ~ProcessCalibration(){}
+
+  void SetOption(const string& option) {option_ = option;}
+  void SetFreqBAOCalibration(const string& freqBAOCalibration) { 
+    freqBAOCalibration_ = freqBAOCalibration; 
+    valfreqBAOCalibration_ = atof(freqBAOCalibration_.c_str());
+  }
+  void SetBandWidthBAOCalibration(const string& bandWidthBAOCalibration) { 
+    bandWidthBAOCalibration_ = bandWidthBAOCalibration; 
+    valbandWidthBAOCalibration_ = atof(bandWidthBAOCalibration_.c_str());
+  }
+
+  void ComputeLowerUpperFreqBin();
+      
+  virtual int processCmd() throw(string);
+};
+void ProcessCalibration::ComputeLowerUpperFreqBin() {
+  sa_size_t c0 = round_sa(NUMBER_OF_FREQ*(valfreqBAOCalibration_-LOWER_FREQUENCY)/TOTAL_BANDWIDTH);
+  sa_size_t dc = round_sa(NUMBER_OF_FREQ*valbandWidthBAOCalibration_/TOTAL_BANDWIDTH);
+  lowerFreqBin_ = c0-dc/2;
+  upperFreqBin_ = c0+dc/2;
+}
+
+
+//----------------------------------------------------
+//----------------------------------------------------
+int main(int narg, char* arg[])
+{
+
+  //Init process types
+  map<string,IProcess*> process;
+  process["meanONOFF"] = new ProcessONOFFMeanData(); //JEC 27/10/11
+  process["rawOnOff"]  = new ProcessONOFFRawData();  
+  process["dataOnOff"] = new ProcessONOFFData();
+  process["gain"]      = new ProcessGain();
+  process["calib"]     = new ProcessCalibration();
+
+  //Init Sophya related modules
+  //  SophyaInit();
+  TArrayInitiator _inia; //nneded for TArray persistancy
+  FitsIOServerInit(); //needed for input file
+
+  //message used in Exceptions
+  string msg;
+
+  //Return code
+  int rc = 0;
+
+  //Arguments managements
+  if ((narg>1)&&(strcmp(arg[1],"-h")==0))  return Usage(false);
+  if (narg<11) return Usage(true);
+
+  string action;
+  string inputPath = "."; 
+  string outputPath = "."; 
+  string sourceName;
+  string scaFile;
+  string dateOfRun;
+  string spectraDirectory;
+  string freqBAOCalib = "";
+  string bandWidthBAOCalib = "";
+  string debuglev = "0";
+  string mode = "";
+  string numcycle;
+  string calibrationOpt = "";  
+
+  string typeOfFile="medfiltmtx";
+  
+
+  //  bool okarg=false;
+  int ka=1;
+  while (ka<(narg-1)) {
+    cout << "Debug arglist: <" << arg[ka] <<">" << endl;
+    if (strcmp(arg[ka],"-debug")==0) {
+      debuglev=arg[ka+1];
+      ka+=2;
+    }
+    else if (strcmp(arg[ka],"-act")==0) {
+      action=arg[ka+1];
+      ka+=2;
+    }
+    else if (strcmp(arg[ka],"-inPath")==0) {
+      inputPath=arg[ka+1];
+      ka+=2;
+    }
+    else if (strcmp(arg[ka],"-outPath")==0) {
+      outputPath=arg[ka+1];
+      ka+=2;
+    }
+    else if (strcmp(arg[ka],"-source")==0) {
+      sourceName=arg[ka+1];
+      ka+=2;
+    }
+    else if (strcmp(arg[ka],"-sca")==0) {
+      scaFile=arg[ka+1];
+      ka+=2;
+    }
+    else if (strcmp(arg[ka],"-date")==0) {
+      dateOfRun=arg[ka+1];
+      ka+=2;
+    }
+    else if (strcmp(arg[ka],"-specdir")==0) {
+      spectraDirectory=arg[ka+1];
+      ka+=2;
+    }
+    else if (strcmp(arg[ka],"-specname")==0) {
+      typeOfFile=arg[ka+1];
+      ka+=2;
+    }    
+    else if (strcmp(arg[ka],"-freqBAOCalib")==0) {
+      freqBAOCalib = arg[ka+1];
+      ka+=2;
+    }
+    else if (strcmp(arg[ka],"-bwBAOCalib")==0) {
+      bandWidthBAOCalib = arg[ka+1];
+      ka+=2;
+    } 
+    else if (strcmp(arg[ka],"-mode")==0) {
+      mode =arg[ka+1];
+      ka+=2; 
+    }
+    else if (strcmp(arg[ka],"-numcycle")==0) {
+      numcycle =arg[ka+1];
+      ka+=2; 
+    }
+    else if (strcmp(arg[ka],"-calibopt")==0) {
+      calibrationOpt =arg[ka+1];
+      ka+=2; 
+    }
+    else ka++;
+  }//eo while
+
+
+  //JEC 21/9/11 Give the input parameters START
+  cout << "Dump Iiitial parameters ............" << endl;
+  cout << " action = " << action << "\n"
+       << " inputPath = " << inputPath << "\n" 
+       << " outputPath = " << outputPath << "\n"
+       << " sourceName = " << sourceName << "\n"
+       << " scaFile = " << scaFile << "\n"
+       << " dateOfRun = " << dateOfRun << "\n"
+       << " spectraDirectory = " << spectraDirectory << "\n"
+       << " spectraName = " << typeOfFile << "\n"
+       << " freqBAOCalib = " << freqBAOCalib  << "\n"
+       << " bandWidthBAOCalib = " << bandWidthBAOCalib << "\n"
+       << " debuglev = "  << debuglev  << "\n"
+       << " mode = " << mode << "\n"
+       << " numcycle = " << numcycle << "\n"
+       << " calibrationOpt = " << calibrationOpt << endl;
+  cout << "...................................." << endl;
+  //JEC 21/9/11 Give the input parameters END
+
+
+  try {
+    //verification of action
+    if(process.find(action) == process.end()) {
+      msg = "action ";
+      msg += action + " not valid... FATAL";
+      rc = 999;
+      throw msg;
+    }
+    
+
+    //
+    //Process initialisation...
+    //
+    try {
+      ProcessBase* procbase = dynamic_cast<ProcessBase*>(process[action]);
+      if (procbase == 0) {
+	msg= "action ";
+	msg += action + "Not a <process base> type...FATAL";
+	rc = 999;
+	throw msg;
+      }
+      procbase->SetInputPath(inputPath);
+      procbase->SetOutputPath(outputPath);
+
+      if ("" == sourceName) {
+	msg = "(FATAL) missingsourceName  for action " + action;
+	Usage(true);
+	throw msg;
+      }
+      procbase->SetSourceName(sourceName);
+
+      if ("" == dateOfRun) {
+	msg = "(FATAL) missing dateOfRun for action " + action;
+	Usage(true);
+	throw msg;
+      }
+      procbase->SetDateOfRun(dateOfRun);
+
+      
+      if ("" == spectraDirectory) {
+	msg = "(FATAL) missing spectraDirectory for action " + action;
+	Usage(true);
+	throw msg;
+      }
+      procbase->SetSpectraDirectory(spectraDirectory);
+
+      if ("" == scaFile) {
+	msg = "(FATAL) missing scaFile for action " + action;
+	Usage(true);
+	throw msg;
+      }
+      procbase->SetScaFileName(scaFile);
+
+      if ("" == numcycle) {
+	msg = "(FATAL) missing cycle number for action " + action;
+	Usage(true);
+	throw msg;
+      }
+      procbase->SetNumCycle(numcycle);
+
+
+      procbase->SetTypeOfFile(typeOfFile);
+
+      procbase->SetDebugLevel(debuglev);
+    }
+    catch(exception& e){
+      throw e.what();
+    }
+
+    //JEC 22/9/11 Make ON-OFF analysis WO any calibration START
+//     try {
+//       ProcessONOFFRawData* procRawdata = dynamic_cast<ProcessONOFFRawData*>(process[action]);
+//     }
+//     catch(exception& e){
+//       throw e.what();
+//     }
+    //JEC 22/9/11 Make ON-OFF analysis WO any calibration END
+
+
+    try {
+      ProcessONOFFData* procdata = dynamic_cast<ProcessONOFFData*>(process[action]);
+      if (procdata) {
+	if (freqBAOCalib == "") {
+	  msg = "(FATAL) missing calibration BAO frequency for action " + action;
+	  Usage(true);
+	  throw msg;
+	}
+	procdata->SetFreqBAOCalibration(freqBAOCalib);
+      }
+    }
+    catch(exception& e){
+      throw e.what();
+    }
+    
+
+    try {
+      ProcessGain* procgain = dynamic_cast<ProcessGain*>(process[action]);
+      if(procgain) {
+	if (mode == "") {
+	  msg = "(FATAL) missing mode-type for action " + action;
+	  Usage(true);
+	  throw msg;
+	}
+	procgain->SetMode(mode);
+      }
+    }
+    catch(exception& e){
+      throw e.what();
+    }
+
+    try {
+      ProcessCalibration* proccalib = dynamic_cast<ProcessCalibration*>(process[action]);
+      if(proccalib) {
+	if (calibrationOpt == "") {
+	  msg = "(FATAL) missing calibration option";
+	  Usage(true);
+	  throw msg;
+	}
+	if (freqBAOCalib == "") {
+	  msg = "(FATAL) missing calibration BAO frequency for action " + action;
+	  Usage(true);
+	  throw msg;
+	}
+	if (bandWidthBAOCalib == "") {
+	  msg = "(FATAL) missing calibration BAO frequency band width for action " + action;
+	  Usage(true);
+	  throw msg;
+	}
+	proccalib->SetOption(calibrationOpt);
+	proccalib->SetFreqBAOCalibration(freqBAOCalib);
+	proccalib->SetBandWidthBAOCalibration(bandWidthBAOCalib);
+	proccalib->ComputeLowerUpperFreqBin();
+      }
+    }
+    catch(exception& e){
+      throw e.what();
+    }
+
+    //
+    //execute command
+    //
+    rc = process[action]->processCmd();
+
+  }
+  catch (std::exception& sex) {
+    cerr << "\n analyse.cc std::exception :"  << (string)typeid(sex).name() 
+	 << "\n msg= " << sex.what() << endl;
+    rc = 78;
+  }
+  catch ( string str ) {
+    cerr << "analyse.cc Exception raised: " << str << endl;
+  }
+  catch (...) {
+    cerr << " analyse.cc catched unknown (...) exception  " << endl; 
+    rc = 79; 
+  } 
+
+  
+
+
+  cout << ">>>> analyse.cc ------- END ----------- RC=" << rc << endl;
+  
+  //Delete processes
+  for_each(process.begin(),process.end(), DeleteMapFntor<string,IProcess*>());
+
+  return rc;
+}
+
+//---------------------------------------------------
+int Usage(bool flag) {
+  cout << "Analyse.cc usage...." << endl;
+  cout << "analyse  -act <action_type>: meanONOFF,dataOnOff, rawOnOff, gain, calib\n"
+       << "         -inPath <path for input files: default='.'>\n"
+       << "         -outPath <path for output files: default='.'>\n"
+       << "         -source <source name> \n" 
+       << "         -date <YYYYMMDD>\n"
+       << "         -sca <file name scaXYZ.sum.trans>\n"
+       << "         -specdir <generic directory name of spectra fits files>\n"
+       << "         -specname <generic name of spectra fits files>\n"
+       << "         -freqBAOCalib <freq in MHZ> freq. of calibration BAO\n"
+       << "            valid for act=dataOnOff\n"
+       << "         -bwBAOCalib <band width MHz> band width arround central freq. for calibration BAO\n"
+       << "            valid for act=calib\n"
+       << "         -mode <mode_type>:\n"
+       << "            valid for act=gain, mode_type: On, Off\n"
+       << "         -numcycle <number>,<number>:\n"
+       << "            valid for all actions"
+       << "         -calibopt <option>:\n"
+       << "            valid for act=calib: indiv OR mean (NOT USED)"
+       << "         -debug <number> [0=default]\n"
+       << "           1: normal print\n"
+       << "           2: save intermediate spectra\n"
+       << endl;
+  if (flag) {
+    cout << "use <path>/analyse -h for detailed instructions" << endl;
+    return 5;
+  }
+  return 1;
+}
+
+int ProcessBase::processCmd() throw(string) {
+  int rc =0;
+  string msg;
+  if(debuglev_>0)cout << "Process Base" << endl;
+  //------------------------
+  //Use the sca file informations
+  //------------------------
+  //  string scaFullPathName = "./";
+  //TOBE FIXED  scaFullPathName += sourceName_+"/"+dateOfRun_ + StringToLower(sourceName_)+"/";
+  string scaFullPathName = inputPath_ + "/" 
+    + sourceName_+ "/" +dateOfRun_ + StringToLower(sourceName_)+ "/" + scaFileName_;
+  char* scaTupleColumnName[9] = {"cycle","stcalOn","spcalOn","stOn","spOn","stcalOff","spcalOff","stOff","spOff"};
+  scaTuple_ = new NTuple(9,scaTupleColumnName);
+  int n = scaTuple_->FillFromASCIIFile(scaFullPathName);
+  if(n<0){ //Error
+    msg = "(FATAL) NTuple error loading "+ scaFullPathName;
+    rc = 999;
+    throw msg;
+  }
+  
+  if(debuglev_>1){
+    cout << "ProcessBase::processCmd: dump tuple in " << scaFullPathName << endl;
+    scaTuple_->Show(cout);
+  }
+  
+  
+  //Get the cycles (here consider consecutive cycles)    
+  //The SCA file cannot be used as the DAQ can miss some cycles...
+  //     r_8 firstCycle, lastCycle;
+  //     scaTuple_->GetMinMax("cycle",firstCycle,lastCycle);
+  //     ifirstCycle_ = (sa_size_t)firstCycle;
+  //     ilastCycle_  = (sa_size_t)lastCycle;
+  //Analyse the string given by -numcycle command line
+  int ai1=0,ai2=0;
+  sscanf(numcycle_.c_str(),"%d,%d",&ai1,&ai2);
+  ifirstCycle_ = (sa_size_t)ai1;
+  ilastCycle_  = (sa_size_t)ai2;
+  
+
+  //associate cycle number to index line in tuple
+  sa_size_t nLines = scaTuple_->NbLines();
+  for(sa_size_t iL=0; iL<nLines; ++iL){
+    idCycleInTuple_[(sa_size_t)scaTuple_->GetCell(iL,"cycle")]=iL;
+  }
+
+
+  return rc;
+}
+//----------------------------------------------
+//JEC 27/10/11
+//Process the files that are output of the specmfib -act = mspec (mean+sigma of signal files)
+//----------------------------------------------
+int ProcessONOFFMeanData::processCmd() throw(string) {
+  int rc = 0;
+  try {
+    rc = ProcessBase::processCmd();
+  } 
+  catch (string s) {
+    throw s;
+  }
+
+  if(debuglev_>0)cout << "Process Data" << endl;
+  vector<string> modeList;
+  modeList.push_back("On");
+  modeList.push_back("Off");
+  vector<string>::const_iterator iMode;
+  
+  uint_4 id; 
+  string tag;
+
+  map< pair<string, sa_size_t>, TMatrix<r_4> > spectreCollect;
+  map< pair<string, sa_size_t>, TMatrix<r_4> >::iterator iSpectre, iSpectreEnd;
+  
+  for (iMode = modeList.begin(); iMode != modeList.end(); ++iMode) {
+    string mode = *iMode;
+    if(debuglev_>0)cout << "Process Mean-mspec Mode " << mode << endl;
+
+    //------------------------------------------
+    //Produce mean of the mean spectra per cycle
+    //------------------------------------------
+
+    string directoryName;
+    list<string> listOfSpecFiles;
+    list<string>::const_iterator iFile, iFileEnd;
+   
+        
+    //
+    //loop on cycles
+    //
+    for (sa_size_t icycle = ifirstCycle_; icycle <= ilastCycle_; icycle++) {
+      directoryName = inputPath_ + "/" 
+	+ sourceName_ + "/" + dateOfRun_ + StringToLower(sourceName_) + "/"
+	+ mode + "/";
+      stringstream sicycle;
+      sicycle << icycle;
+      directoryName += spectraDirectory_ + sicycle.str() + "/";
+
+      //read directory
+      listOfSpecFiles = ListOfFileInDir(directoryName,typeOfFile_);
+      
+
+      //compute mean of spectra created in a cycle
+      if(debuglev_>0)cout << "compute mean for cycle " << icycle << endl;
+      TMatrix<r_4> spectreMean(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ); //implicit init to 0
+      iFileEnd = listOfSpecFiles.end();
+      r_4 nSpectres  = 0;
+      for (iFile = listOfSpecFiles.begin(); iFile != iFileEnd; ++iFile) {
+	FitsInOutFile aSpectrum(*iFile,FitsInOutFile::Fits_RO);
+	TMatrix<r_4> spectre(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ);
+	aSpectrum >> spectre;
+	spectreMean += spectre;
+	nSpectres++;
+      }// end of for files 
+      if(nSpectres>0) spectreMean /= nSpectres;
+      
+      //save mean spectrum
+      spectreCollect.insert( pair< pair<string,sa_size_t>, TMatrix<r_4> >(make_pair(mode,icycle),TMatrix<r_4>(spectreMean,false) ));
+    }//end of for cycles
+  }//end loop on mode for raw preocess
+
+  if(debuglev_>1) {//save mean spectra on file 
+    cout << "Save mean spectra" << endl;
+    string fileName;
+
+    fileName = "./dataMean_" + dateOfRun_ + "_" + StringToLower(sourceName_) + ".ppf";
+
+    POutPersist fos(fileName);
+    id=0;
+    iSpectreEnd = spectreCollect.end();
+    for (iSpectre = spectreCollect.begin();
+	 iSpectre != iSpectreEnd ; ++iSpectre, ++id) {
+      tag = "specMean";
+
+      tag += (iSpectre->first).first;
+      stringstream sid;
+      sid << (iSpectre->first).second;
+      tag += sid.str();
+      if(debuglev_>9) {
+ 	cout << "save tag<" << tag << ">" << endl;
+      }
+
+      fos << PPFNameTag(tag) << iSpectre->second;
+    }
+  }//end of save fits
+  
+
+
+
+
+  cout << "OK ProcessONOFFMeanData finished" <<endl;
+  return rc;
+}
+//----------------------------------------------
+
+//JEC 22/9/11 Make ON-OFF analysis WO any calibration START
+//----------------------------------------------
+int ProcessONOFFRawData::processCmd() throw(string) {
+  int rc = 0;
+  try {
+    rc = ProcessBase::processCmd();
+  } 
+  catch (string s) {
+    throw s;
+  }
+  if(debuglev_>0)cout << "Process Raw Data ON OFF" << endl;
+  vector<string> modeList;
+  modeList.push_back("On");
+  modeList.push_back("Off");
+  vector<string>::const_iterator iMode;
+  
+  uint_4 id; 
+  string tag;
+
+  //
+  //Process to get sucessively
+  //Raw Spectra, 
+  //The processes are separated to allow intermediate save of results
+
+  map< pair<string, sa_size_t>, TMatrix<r_4> > spectreCollect;
+  map< pair<string, sa_size_t>, TMatrix<r_4> >::iterator iSpectre, iSpectreEnd;
+  
+  for (iMode = modeList.begin(); iMode != modeList.end(); ++iMode) {
+    string mode = *iMode;
+    if(debuglev_>0)cout << "Process RAW Mode " << mode << endl;
+
+    //------------------------------------------
+    //Produce Raw spectra per cycle
+    //------------------------------------------
+
+    string directoryName;
+    list<string> listOfSpecFiles;
+    list<string>::const_iterator iFile, iFileEnd;
+    
+        
+    //
+    //loop on cycles
+    //
+    for (sa_size_t icycle = ifirstCycle_; icycle <= ilastCycle_; icycle++) {
+      directoryName = inputPath_ + "/" 
+	+ sourceName_ + "/" + dateOfRun_ + StringToLower(sourceName_) + "/"
+	+ mode + "/";
+      stringstream sicycle;
+      sicycle << icycle;
+      directoryName += spectraDirectory_ + sicycle.str() + "/";
+
+      //read directory
+      listOfSpecFiles = ListOfFileInDir(directoryName,typeOfFile_);
+      
+
+      //compute mean of spectra created in a cycle
+      if(debuglev_>0)cout << "compute mean for cycle " << icycle << endl;
+      TMatrix<r_4> spectreMean(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ); //implicit init to 0
+      iFileEnd = listOfSpecFiles.end();
+      r_4 nSpectres  = 0;
+      for (iFile = listOfSpecFiles.begin(); iFile != iFileEnd; ++iFile) {
+	FitsInOutFile aSpectrum(*iFile,FitsInOutFile::Fits_RO);
+	TMatrix<r_4> spectre(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ);
+	aSpectrum >> spectre;
+	spectreMean += spectre;
+	nSpectres++;
+      }// end of for files 
+      if(nSpectres>0) spectreMean /= nSpectres;
+      
+      //save mean spectrum
+      spectreCollect.insert( pair< pair<string,sa_size_t>, TMatrix<r_4> >(make_pair(mode,icycle),TMatrix<r_4>(spectreMean,false) ));
+    }//end of for cycles
+  }//end loop on mode for raw preocess
+
+  //JEC 23/9/11 DO IT 
+  //  if(debuglev_>1) {//save mean spectra on file 
+  cout << "Save mean raw spectra" << endl;
+  string fileName;
+  fileName = "./dataRaw_" + dateOfRun_ + "_" + StringToLower(sourceName_) + ".ppf";
+
+  POutPersist fos(fileName);
+  id=0;
+  iSpectreEnd = spectreCollect.end();
+  for (iSpectre = spectreCollect.begin();
+       iSpectre != iSpectreEnd ; ++iSpectre, ++id) {
+    tag = "specRaw";
+    tag += (iSpectre->first).first;
+    stringstream sid;
+    sid << (iSpectre->first).second;
+    tag += sid.str();
+    if(debuglev_>9) {
+      cout << "save tag<" << tag << ">" << endl;
+    }
+    fos << PPFNameTag(tag) << iSpectre->second;
+  }
+    //  }//end of save fits
+  
+
+  //------------------------------------------
+  // Perform ON-OFF
+  //------------------------------------------
+  
+  map< sa_size_t, TMatrix<r_4> > diffCollect;
+  map< sa_size_t, TMatrix<r_4> >::iterator iDiff, iDiffEnd;
+
+  TMatrix<r_4> diffMeanOnOff(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ); //init zero
+  r_4 nCycles = 0;
+  for (sa_size_t icycle = ifirstCycle_; icycle <= ilastCycle_; icycle++) {
+    nCycles++;
+    TMatrix<r_4> specmtxOn(spectreCollect[make_pair(modeList[0],icycle)],false); //clone the memory 
+    TMatrix<r_4> specmtxOff(spectreCollect[make_pair(modeList[1],icycle)],false); //clone the memory 
+    TMatrix<r_4> diffOnOff = specmtxOn - specmtxOff;
+    diffCollect.insert(pair< sa_size_t,TMatrix<r_4> >(icycle,TMatrix<r_4>(diffOnOff,false) ));
+    diffMeanOnOff += diffOnOff;
+  }//end loop on cycle
+  if(nCycles>0) diffMeanOnOff/=nCycles;
+
+  //extract channels and do the mean
+  TVector<r_4> meanOfChan(NUMBER_OF_FREQ); //implicitly init to 0
+  for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS; ++iCh) {
+    meanOfChan += diffMeanOnOff.Row(iCh).Transpose();
+  }
+  meanOfChan /= (r_4)NUMBER_OF_CHANNELS;
+  
+
+
+  {//save diff ON-OFF on Raw data
+    if(debuglev_>0)cout << "save ON-OFF RAW spectra" << endl;
+    string fileName;
+    fileName = "./diffOnOffRaw_" + dateOfRun_ + "_" + StringToLower(sourceName_) + ".ppf";
+    POutPersist fos(fileName);
+    iDiffEnd = diffCollect.end();
+    id = 0;
+
+    //JEC 22/9/11 Mean & Sigma in 32-bins size START
+    sa_size_t nSliceFreq = 32; //TODO: put as an input parameter option ?
+    sa_size_t deltaFreq = NUMBER_OF_FREQ/nSliceFreq;
+    //JEC 22/9/11 Mean & Sigma in 32-bins size END
+
+    for (iDiff = diffCollect.begin();iDiff != iDiffEnd ; ++iDiff, id++) {
+      tag = "specONOFFRaw";
+      stringstream sid;
+      sid << iDiff->first;
+      tag += sid.str();
+      fos << PPFNameTag(tag) << iDiff->second;
+
+      //JEC 22/9/11 Mean & Sigma in 32-bins size START
+      if (debuglev_>9) {
+ 	cout << "Debug slicing: slice/delta " << nSliceFreq << " " << deltaFreq << endl;
+      }
+      TMatrix<r_4> reducedMeanDiffOnOff(NUMBER_OF_CHANNELS,nSliceFreq); //init 0 by default
+      TMatrix<r_4> reducedSigmaDiffOnOff(NUMBER_OF_CHANNELS,nSliceFreq); //init 0 by default
+      for (sa_size_t iSlice=0; iSlice<nSliceFreq; iSlice++){
+	sa_size_t freqLow= iSlice*deltaFreq;
+	sa_size_t freqHigh= freqLow + deltaFreq -1;
+	if (debuglev_>9) {
+	  cout << "Debug .......... slicing ["<< iSlice << "]: low/high freq" << freqLow << "/" << freqHigh << endl;
+	}
+	for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS; ++iCh){
+	  if (debuglev_>9) {
+	    cout << "Debug .......... Channel " << iCh;
+	  }
+	  TVector<r_4> reducedRow;
+	  reducedRow = (iDiff->second).SubMatrix(Range(iCh),Range(freqLow,freqHigh)).CompactAllDimensions();
+	  double mean; 
+	  double sigma;
+	  MeanSigma(reducedRow,mean,sigma);
+	  if (debuglev_>9) {
+	    cout << "mean/sigma " << mean << "/" << sigma << endl;
+	  }
+	  reducedMeanDiffOnOff(iCh,iSlice) = mean;
+	  reducedSigmaDiffOnOff(iCh,iSlice) = sigma;
+	}//loop on Channel
+      }//loop on Freq. slice 
+      tag = "redMeanONOFFRaw";
+      tag += sid.str();
+      fos << PPFNameTag(tag) << reducedMeanDiffOnOff;
+      tag = "redSigmaONOFFRaw";
+      tag += sid.str();
+      fos << PPFNameTag(tag) << reducedSigmaDiffOnOff;
+      //JEC 22/9/11 END
+
+    }//loop on ON-OFF spectre
+    //save the mean also
+    fos << PPFNameTag("specONOFFRawMean") << diffMeanOnOff;
+
+    //JEC 22/9/11 START
+    TMatrix<r_4> reducedMeanDiffOnOffAll(NUMBER_OF_CHANNELS,nSliceFreq); //init 0 by default
+    TMatrix<r_4> reducedSigmaDiffOnOffAll(NUMBER_OF_CHANNELS,nSliceFreq); //init 0 by default
+    for (sa_size_t iSlice=0; iSlice<nSliceFreq; iSlice++){
+      sa_size_t freqLow= iSlice*deltaFreq;
+      sa_size_t freqHigh= freqLow + deltaFreq -1;
+      if (debuglev_>9) {
+	cout << "Debug .......... slicing ["<< iSlice << "]: low/high freq" << freqLow << "/" << freqHigh << endl;
+      }
+      for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS; ++iCh){
+	if (debuglev_>9) {
+	  cout << "Debug .......... Channel " << iCh;
+	}
+	TVector<r_4> reducedRow;
+	reducedRow = diffMeanOnOff.SubMatrix(Range(iCh),Range(freqLow,freqHigh)).CompactAllDimensions();
+	double mean; 
+	double sigma;
+	MeanSigma(reducedRow,mean,sigma);
+	if (debuglev_>9) {
+	  cout << "mean/signa " << mean << "/" << sigma << endl;
+	}
+	reducedMeanDiffOnOffAll(iCh,iSlice) = mean;
+	reducedSigmaDiffOnOffAll(iCh,iSlice) = sigma;
+      }//loop on Channel
+    }//loop on Freq. slice 
+    tag = "redMeanONOFFRawAll";
+    fos << PPFNameTag(tag) << reducedMeanDiffOnOffAll;
+    tag = "redSigmaONOFFRawAll";
+    fos << PPFNameTag(tag) << reducedSigmaDiffOnOffAll;
+    //JEC 22/9/11 END
+
+
+
+    fos << PPFNameTag("specONOFFRaw2ChanMean") << meanOfChan;
+  }//end of save fits
+
+  
+  cout << "OK rawOnOff finished" <<endl;
+  return rc;
+} //ProcessONOFFRawData::processCmd
+
+//JEC 22/9/11 Make ON-OFF analysis WO any calibration END
+//----------------------------------------------
+int ProcessONOFFData::processCmd() throw(string) {
+  int rc = 0;
+  try {
+    rc = ProcessBase::processCmd();
+  } 
+  catch (string s) {
+    throw s;
+  }
+  if(debuglev_>0)cout << "Process Data" << endl;
+  vector<string> modeList;
+  modeList.push_back("On");
+  modeList.push_back("Off");
+  vector<string>::const_iterator iMode;
+  
+  uint_4 id; 
+  string tag;
+
+  //
+  //Process to get sucessively
+  //Raw Spectra, 
+  //BAO Calibrated Spectra 
+  //and RT Calibrated Spectra
+  //The pocesses are separated to allow intermediate save of results
+
+  map< pair<string, sa_size_t>, TMatrix<r_4> > spectreCollect;
+  map< pair<string, sa_size_t>, TMatrix<r_4> >::iterator iSpectre, iSpectreEnd;
+  
+  for (iMode = modeList.begin(); iMode != modeList.end(); ++iMode) {
+    string mode = *iMode;
+    if(debuglev_>0)cout << "Process RAW Mode " << mode << endl;
+
+    //------------------------------------------
+    //Produce Raw spectra per cycle
+    //------------------------------------------
+
+    string directoryName;
+    list<string> listOfSpecFiles;
+    list<string>::const_iterator iFile, iFileEnd;
+    
+        
+    //
+    //loop on cycles
+    //
+    for (sa_size_t icycle = ifirstCycle_; icycle <= ilastCycle_; icycle++) {
+      //TOBE FIXED      directoryName = "./" + sourceName_ + "/"+ dateOfRun_ + StringToLower(sourceName_) + "/" +mode + "/";
+      directoryName = "./" + mode + "/";
+      stringstream sicycle;
+      sicycle << icycle;
+      directoryName += spectraDirectory_ + sicycle.str() + "/";
+
+      //read directory
+      listOfSpecFiles = ListOfFileInDir(directoryName,typeOfFile_);
+      
+
+      //compute mean of spectra created in a cycle
+      if(debuglev_>0)cout << "compute mean for cycle " << icycle << endl;
+      TMatrix<r_4> spectreMean(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ); //implicit init to 0
+      iFileEnd = listOfSpecFiles.end();
+      r_4 nSpectres  = 0;
+      for (iFile = listOfSpecFiles.begin(); iFile != iFileEnd; ++iFile) {
+	FitsInOutFile aSpectrum(*iFile,FitsInOutFile::Fits_RO);
+	TMatrix<r_4> spectre(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ);
+	aSpectrum >> spectre;
+	spectreMean += spectre;
+	nSpectres++;
+      }// end of for files 
+      if(nSpectres>0) spectreMean /= nSpectres;
+      
+      //save mean spectrum
+      spectreCollect.insert( pair< pair<string,sa_size_t>, TMatrix<r_4> >(make_pair(mode,icycle),TMatrix<r_4>(spectreMean,false) ));
+    }//end of for cycles
+  }//end loop on mode for raw preocess
+
+  if(debuglev_>1) {//save mean spectra on file 
+    cout << "Save mean raw spectra" << endl;
+    string fileName;
+    //TOBE FIXED    fileName = "./" + sourceName_ + "/" + dateOfRun_ + "_" + StringToLower(sourceName_) + "_" + "dataRaw" + ".ppf";
+    fileName = "./dataRaw_" + dateOfRun_ + "_" + StringToLower(sourceName_) + ".ppf";
+
+    POutPersist fos(fileName);
+    id=0;
+    iSpectreEnd = spectreCollect.end();
+    for (iSpectre = spectreCollect.begin();
+	 iSpectre != iSpectreEnd ; ++iSpectre, ++id) {
+      tag = "specRaw";
+
+      //JEC 20/9/11 modif tag to take into account Mode and Cycle number START
+//       stringstream sid;
+//       sid << id;
+//       tag += sid.str();
+      tag += (iSpectre->first).first;
+      stringstream sid;
+      sid << (iSpectre->first).second;
+      tag += sid.str();
+      if(debuglev_>9) {
+ 	cout << "save tag<" << tag << ">" << endl;
+      }
+      //JEC 20/9/11 modif tag to take into account Mode and Cycle number END
+
+      fos << PPFNameTag(tag) << iSpectre->second;
+    }
+  }//end of save fits
+  
+
+
+  for (iMode = modeList.begin(); iMode != modeList.end(); ++iMode) {
+    string mode = *iMode;
+    if(debuglev_>0)cout << "Process CALIB BAO Mode " << mode << endl;
+    //------------------------------------------
+    // Correct Raw spectra for BAO calibration
+    //------------------------------------------
+    //Read BAO calibration files
+    sa_size_t nr,nc; //values read 
+    
+    //JEC 20/9/11 use mean calibration coeff upon all cycles START
+    string calibFileName = inputPath_+ "/" 
+      + sourceName_ + "/" + dateOfRun_ + StringToLower(sourceName_) 
+      + "/calib_" + dateOfRun_ + "_" + StringToLower(sourceName_) + "_"
+      + mode + "_" + freqBAOCalibration_ + "MHz-All.txt";
+
+    if(debuglev_>0) cout << "Read file " << calibFileName << endl;
+    ifstream ifs(calibFileName.c_str());
+    if ( ! ifs.is_open() ) {
+      rc = 999;
+      throw calibFileName + " cannot be opened...";
+    }	
+    TVector<r_4> calibBAOfactors;
+    if(debuglev_>9) cout << "Debug 1" << endl;
+    calibBAOfactors.ReadASCII(ifs,nr,nc);
+    if(debuglev_>9){
+      cout << "Debug 2: (nr,nc): "<< nr << "," << nc << endl;
+      calibBAOfactors.Print(cout);
+    }
+
+    //JEC 20/9/11 use mean calibration coeff upon all cycles END
+
+    //
+    //spectra corrected by BAO calibration factor 
+    //-----make it different on Channels and Cycles (1/06/2011) OBSOLETE
+    //use mean calibration coeff upon all cycles (20/6/11)
+    //warning cycles are numbered from 1,...,N
+    //
+    if(debuglev_>0)cout << "do calibration..." << endl;
+    for (sa_size_t icycle = ifirstCycle_; icycle <= ilastCycle_; icycle++) {
+      TMatrix<r_4> specmtx(spectreCollect[make_pair(mode,icycle)],true); //share the memory 
+      
+      for (sa_size_t iCh=0;iCh<NUMBER_OF_CHANNELS;++iCh){
+	//JEC 20/9/11 use mean calibration coeff upon all cycles START
+
+	//	specmtx( Range(iCh), Range::all() ) /= calibBAOfactors(iCh,icycle-1);
+	specmtx( Range(iCh), Range::all() ) /= calibBAOfactors(iCh);
+	//JEC 20/9/11 use mean calibration coeff upon all cycles END
+      }
+    }
+  } //end loop mode for BAO calib
+
+  cout << "save calibrated BAO spectra" << endl;
+  string fileName;
+  //TO BE FIXED    fileName = "./" + sourceName_ + "/" + dateOfRun_ + "_" + StringToLower(sourceName_) + "_" + "dataBAOCalib" + ".ppf";
+  fileName = "./dataBAOCalib_" + dateOfRun_ + "_" + StringToLower(sourceName_) + ".ppf";
+  
+  POutPersist fos(fileName);
+  iSpectreEnd = spectreCollect.end();
+  id=0;
+  for (iSpectre = spectreCollect.begin();iSpectre != iSpectreEnd ; ++iSpectre, ++id) {
+    
+    tag = "specBAOCalib";
+    //JEC 20/9/11 modif tag to take into account Mode and Cycle number START
+    //       stringstream sid;
+    //       sid << id;
+    //       tag += sid.str();
+    tag += (iSpectre->first).first;
+    stringstream sid;
+    sid << (iSpectre->first).second;
+    tag += sid.str();
+    if(debuglev_>9) {
+      cout << "save tag<" << tag << ">" << endl;
+    }
+    //JEC 20/9/11 modif tag to take into account Mode and Cycle number END
+    
+    fos << PPFNameTag(tag) << iSpectre->second;
+  }
+  
+  for (iMode = modeList.begin(); iMode != modeList.end(); ++iMode) {
+    string mode = *iMode;
+    if(debuglev_>0)cout << "Process CALIB RT Mode " << mode << endl;
+    //------------------------------------------
+    // Correct BAO calib spectra for RT calibration
+    //------------------------------------------
+    //Very Preliminary May-June 11
+    //coef RT @ 1346MHz Ouest - Est associees a Ch 0 et 1
+    r_4 calibRT[NUMBER_OF_CHANNELS] = {27.724, 22.543};
+    for (sa_size_t icycle = ifirstCycle_; icycle <= ilastCycle_; icycle++) {
+      TMatrix<r_4> specmtx(spectreCollect[make_pair(mode,icycle)],true); //share the memory    
+      for (sa_size_t iCh=0;iCh<NUMBER_OF_CHANNELS;++iCh){
+	specmtx( Range(iCh), Range::all() ) *= calibRT[iCh];
+      }
+    }
+  }//end loop on mode RT calib
+
+  {//save mean spectra BAO & RT calibrated on file
+    if(debuglev_>0)cout << "save calibrated BAO & RT spectra" << endl;
+    string fileName;
+    //TO BE FIXED    fileName = "./" + sourceName_ + "/" + dateOfRun_ + "_" + StringToLower(sourceName_) + "_" + "dataBAORTCalib" + ".ppf";
+     fileName = "./dataBAORTCalib_" + dateOfRun_ + "_" + StringToLower(sourceName_) + ".ppf";   
+    POutPersist fos(fileName);
+    iSpectreEnd = spectreCollect.end();
+    id = 0;
+    for (iSpectre = spectreCollect.begin();iSpectre != iSpectreEnd ; ++iSpectre, ++id) {
+      tag = "specBAORTCalib";
+      //JEC 20/9/11 modif tag to take into account Mode and Cycle number START
+//       stringstream sid;
+//       sid << id;
+//       tag += sid.str();
+      tag += (iSpectre->first).first;
+      stringstream sid;
+      sid << (iSpectre->first).second;
+      tag += sid.str();
+      if(debuglev_>9) {
+ 	cout << "save tag<" << tag << ">" << endl;
+      }
+      //JEC 20/9/11 modif tag to take into account Mode and Cycle number END
+      fos << PPFNameTag(tag) << iSpectre->second;
+    }
+  }//end of save fits
+
+  //------------------------------------------
+  // Perform ON-OFF
+  //------------------------------------------
+  
+  map< sa_size_t, TMatrix<r_4> > diffCollect;
+  map< sa_size_t, TMatrix<r_4> >::iterator iDiff, iDiffEnd;
+
+  TMatrix<r_4> diffMeanOnOff(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ); //init zero
+  r_4 nCycles = 0;
+  for (sa_size_t icycle = ifirstCycle_; icycle <= ilastCycle_; icycle++) {
+    nCycles++;
+    TMatrix<r_4> specmtxOn(spectreCollect[make_pair(modeList[0],icycle)],false); //clone the memory 
+    TMatrix<r_4> specmtxOff(spectreCollect[make_pair(modeList[1],icycle)],false); //clone the memory 
+    TMatrix<r_4> diffOnOff = specmtxOn - specmtxOff;
+    diffCollect.insert(pair< sa_size_t,TMatrix<r_4> >(icycle,TMatrix<r_4>(diffOnOff,false) ));
+    diffMeanOnOff += diffOnOff;
+  }//end loop on cycle
+  if(nCycles>0) diffMeanOnOff/=nCycles;
+
+  //exctract channels and do the mean
+  TVector<r_4> meanOfChan(NUMBER_OF_FREQ); //implicitly init to 0
+  for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS; ++iCh) {
+    meanOfChan += diffMeanOnOff.Row(iCh).Transpose();
+  }
+  meanOfChan /= (r_4)NUMBER_OF_CHANNELS;
+  
+
+
+  {//save diff ON-OFF BAO & RT calibrated
+    if(debuglev_>0)cout << "save ON-OFF spectra" << endl;
+    string fileName;
+    //TO BE FIXED    fileName = "./" + sourceName_ + "/" + dateOfRun_ + "_" + StringToLower(sourceName_) + "_" + "diffOnOff" + ".ppf";
+    fileName = "./diffOnOff_" + dateOfRun_ + "_" + StringToLower(sourceName_) + ".ppf";
+    POutPersist fos(fileName);
+    iDiffEnd = diffCollect.end();
+    id = 0;
+    for (iDiff = diffCollect.begin();iDiff != iDiffEnd ; ++iDiff, id++) {
+      tag = "specONOFF";
+      stringstream sid;
+      //JEC 20/9/11      sid << id;
+      sid << iDiff->first;
+      tag += sid.str();
+      if(debuglev_>9) {
+ 	cout << "save tag<" << tag << ">" << endl;
+      }
+      fos << PPFNameTag(tag) << iDiff->second;
+    }
+    //save the mean also
+    fos << PPFNameTag("specONOFFMean") << diffMeanOnOff;
+    fos << PPFNameTag("specONOFF2ChanMean") << meanOfChan;
+  }//end of save fits
+
+  cout << "OK dataOnOff finished";
+
+  return rc;
+} //ProcessONOFFData::processCmd
+//
+//----------------------------------------------
+//
+int ProcessGain::processCmd() throw(string) {
+  int rc = 0;
+  string msg = "";
+
+  try {
+    rc = ProcessBase::processCmd();
+  } 
+  catch (string s) {
+    throw s;
+  }
+  if(debuglev_>0)cout << "Process Gain" << endl;
+  
+  string directoryName;
+  //TOBE FIXED  directoryName = "./" + sourceName_ + "/"+ dateOfRun_ + StringToLower(sourceName_) + "/" +mode_ + "/";
+  //JEC 6/09/2011 numcycle_ repalced by ifirstCycle_ according to definition of numcycle_ and the fact that for GAIN 1 cycle is involved
+  stringstream thegaincycle;
+  thegaincycle << ifirstCycle_;
+  directoryName = inputPath_ + "/" 
+    + sourceName_ + "/" + dateOfRun_ + StringToLower(sourceName_) + "/" 
+    + mode_ + "/" + spectraDirectory_ + thegaincycle.str()  + "/";
+  
+  list<string> listOfSpecFiles;
+  list<string>::const_iterator iFile, iFileEnd;
+  //read directory
+
+  listOfSpecFiles = ListOfFileInDir(directoryName,typeOfFile_);
+  
+  //Mean power computed over the N channels to select the spectra for gain computation 
+  //The threshold is computed "on-line" as  1%  of the difference (max power -min power) over the
+  // the min power.
+  //A possible alternative is to set an absolute value...
+  if(debuglev_>0)cout << "compute mean poser spectra for files in " << directoryName << endl;
+  iFileEnd = listOfSpecFiles.end();
+  map<string, r_4> meanpowerCollect;
+  //JEC 21/9/11 add meanpower for each Channels START
+  map<string, r_4> meanPowerPerChanCollect;
+  //JEC 21/9/11 add meanpower for each Channels END
+
+  map<string, r_4>::const_iterator iMeanPow, iMeanPowEnd;
+
+  for (iFile = listOfSpecFiles.begin(); iFile != iFileEnd; ++iFile) {
+    FitsInOutFile aSpectrum(*iFile,FitsInOutFile::Fits_RO);
+    TMatrix<r_4> spectre(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ);
+    aSpectrum >> spectre;
+    meanpowerCollect[*iFile] = spectre.Sum()/spectre.Size();
+    //JEC 21/9/11 add meanpower for each Channels START
+    for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS; ++iCh) {
+      TVector<r_4> specChan(NUMBER_OF_FREQ);
+      specChan = spectre.Row(iCh).Transpose();
+      stringstream tmp;
+      tmp << iCh;
+      string tag = *iFile + "_" + tmp.str();
+      meanPowerPerChanCollect[tag] = specChan.Sum()/specChan.Size();
+    }
+    //JEC 21/9/11 add meanpower for each Channels END
+  }//end of for files
+  pair<string, r_4> minelement = *min_element(meanpowerCollect.begin(),meanpowerCollect.end(),compare);
+  pair<string, r_4> maxelement = *max_element(meanpowerCollect.begin(),meanpowerCollect.end(),compare);
+  if(debuglev_>1){
+    cout << "meanpowerCollect has " << meanpowerCollect.size() << " spectra registered" << endl;
+    cout << "find min mean power "<<minelement.second << " for " << minelement.first << endl;
+    cout << "find max mean power "<<maxelement.second << " for " << maxelement.first << endl;
+  }
+  r_4 threshold = minelement.second + 0.01*(maxelement.second-minelement.second);
+  if(debuglev_>1){
+    cout << "threshold found at " << threshold <<endl;
+  }  
+
+  TMatrix<r_4> spectreMean(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ); //implicit init to 0
+  r_4 nSpectres  = 0;
+  iMeanPowEnd = meanpowerCollect.end();
+  for (iMeanPow = meanpowerCollect.begin(); iMeanPow != iMeanPowEnd; ++iMeanPow) {
+    if ( iMeanPow->second <= threshold ) {
+      //TODO avoid the reloading of the file may speed up
+      FitsInOutFile aSpectrum(iMeanPow->first,FitsInOutFile::Fits_RO);
+      TMatrix<r_4> spectre(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ);
+      aSpectrum >> spectre;
+      spectreMean += spectre;
+      nSpectres++;
+    }
+  }
+  if(debuglev_>1){
+    cout << "Number of files selected for gain " << nSpectres <<endl;
+  }    
+  if(nSpectres>0) {
+    spectreMean /= nSpectres;
+  } else {
+    stringstream tmp;
+    tmp << threshold;
+    msg = "Gain: cannot find a spectra above threshold value =" + tmp.str() + " ... FATAL";
+    throw msg;
+  }
+
+  //Save gain spectra
+  {
+    //use ! to override the file: special features of cfitsio library
+    string fileName;
+    //TOBE FIXED   fileName = "!./" + sourceName_ + "/gain_" + dateOfRun_ + "_" + StringToLower(sourceName_) + ".fits";
+    fileName = "!"+ outputPath_ + "/gain_" + dateOfRun_ + "_" + StringToLower(sourceName_) + ".fits";
+    if(debuglev_>1){
+      cout << "save gains in " << fileName << endl;
+    }
+    FitsInOutFile fos(fileName, FitsInOutFile::Fits_Create);
+    fos << spectreMean;
+  }
+  //save mean power values
+  {
+    vector<r_4> tmp;
+    //JEC 21/9/11 add meanpower for each Channels START
+    vector<r_4> tmpCh0; //for Chan 0
+    vector<r_4> tmpCh1; //for Chan 1
+    //JEC 21/9/11 add meanpower for each Channels END
+    for (iFile = listOfSpecFiles.begin(); iFile != iFileEnd; ++iFile) {
+      if (debuglev_>9) {
+	cout << "Gain: save mean power of file: " << *iFile << endl;
+      }
+      tmp.push_back(meanpowerCollect[*iFile]);
+      //JEC 21/9/11 add meanpower for each Channels START  
+      stringstream tmp0;
+      tmp0 << (sa_size_t)0;
+      string tag0 = *iFile + "_" + tmp0.str();
+      tmpCh0.push_back(meanPowerPerChanCollect[tag0]);
+      if (NUMBER_OF_CHANNELS>1){
+	stringstream tmp1;
+	tmp1 << (sa_size_t)1;
+	string tag1 = *iFile + "_" + tmp1.str();
+	tmpCh1.push_back(meanPowerPerChanCollect[tag1]);
+      }
+      //JEC 21/9/11 add meanpower for each Channels END
+    }
+    string fileName;
+    //TOBE FIXED    fileName = "./" + sourceName_ + "/gain_monitor_" + dateOfRun_ 
+    fileName = outputPath_ + "/gain_monitor_" + dateOfRun_ + "_" + StringToLower(sourceName_) + ".ppf";
+    POutPersist fos(fileName); 
+    TVector<r_4> tvtmp(tmp);
+    fos.PutObject(tvtmp,"gainmoni"); //Attention initialement le tag etait "monitor"...
+    //JEC 21/9/11 add meanpower for each Channels START  
+    TVector<r_4> tvtmp0(tmpCh0);
+    fos.PutObject(tvtmp0,"gainmoni0");
+    if (NUMBER_OF_CHANNELS>1){
+      TVector<r_4> tvtmp1(tmpCh1);
+      fos.PutObject(tvtmp1,"gainmoni1");
+    }
+    //JEC 21/9/11 add meanpower for each Channels END
+  }
+  
+  cout << "OK gain finished" <<endl;
+   return rc;
+}//ProcessGain::processCmd
+//
+//----------------------------------------------
+//
+int ProcessCalibration::processCmd() throw(string) {
+  int rc = 0;
+  string msg = "";
+
+  try {
+    rc = ProcessBase::processCmd();
+  } 
+  catch (string s) {
+    throw s;
+  }
+  if(debuglev_>0)cout << "Process Calibration with option "<< option_ << endl;
+  
+  vector<string> modeList;
+  modeList.push_back("On");
+  modeList.push_back("Off");
+
+  r_8 t0absolute = -1;  //TIMEWIN of the first spectra used
+  r_8 timeTag0   = -1;   //MEANTT, mean TIME TAG of the first paquet window  
+  bool first = true;     // for initialisation
+  
+  // Power Tuple
+  // mode, cycle, time, {Ch0, ... ,ChN} mean poser in the range [f0-Bw/2, f0+Bw/2] 
+  vector<string> varPowerTupleName; //ntuple variable naming
+  varPowerTupleName.push_back("mode");
+  varPowerTupleName.push_back("cycle");  
+  varPowerTupleName.push_back("time");
+  for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS;++iCh){
+    stringstream tmp;
+    tmp << iCh;
+    varPowerTupleName.push_back("Ch"+tmp.str());
+  }
+  r_4 valPowerTuple[varPowerTupleName.size()];
+  NTuple powerEvolution(varPowerTupleName); 
+  
+  
+  //-----------------
+  //Start real process
+  //------------------
+  for (size_t iMode = 0; iMode < modeList.size(); ++iMode) {
+    string mode = modeList[iMode];
+    if(debuglev_>0)cout << "Process Calibration for Mode " << mode << endl;
+
+    //initialize the start of each calibration procedure given by the RT SCA file
+    //see ProcessBase::processCmd for the structure of the sca file
+    string scaStartCalibName = "stcal"+mode; 
+    sa_size_t idStartCalib   = scaTuple_->ColumnIndex(scaStartCalibName);
+
+    string directoryName;
+    list<string> listOfSpecFiles;
+    list<string>::const_iterator iFile, iFileEnd;            
+    //
+    //loop on cycles
+    //
+    for (sa_size_t icycle = ifirstCycle_; icycle <= ilastCycle_; icycle++) {
+
+      directoryName = inputPath_ + "/" 
+	+ sourceName_ + "/"+ dateOfRun_ + StringToLower(sourceName_) + "/" +mode + "/";
+      stringstream sicycle;
+      sicycle << icycle;
+      directoryName += spectraDirectory_ + sicycle.str() + "/";
+      
+      //read directory
+      listOfSpecFiles = ListOfFileInDir(directoryName,typeOfFile_);
+
+      iFileEnd = listOfSpecFiles.end();
+      DVList header;
+      TMatrix<r_4> spectre(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ); //implicit init to 0
+
+      for (iFile = listOfSpecFiles.begin(); iFile != iFileEnd; ++iFile) {
+	FitsInOutFile aSpectrum(*iFile,FitsInOutFile::Fits_RO);
+	aSpectrum.GetHeaderRecords(header);
+	aSpectrum >> spectre;
+
+	if(first){//initialise the timer
+	  first = false;
+	  t0absolute = header.GetD("TIMEWIN")/1000.;
+	  timeTag0 = header.GetD("MEANTT");
+	  if (debuglev_>1){
+	    cout << "debug Header of " << *iFile << endl;
+	    cout << "TIMEWIN = " << setprecision(12) << t0absolute << " "
+		 << "MEANTT = " << setprecision(12) << timeTag0 << endl;
+	  }
+	}//end init timer
+	
+	//Set time of current file
+	//Add to the non-precise absolute origin an precise increment
+	r_4 timeTag = t0absolute + (header.GetD("MEANTT") - timeTag0);
+	int index=0;
+	valPowerTuple[index++] = iMode;
+	valPowerTuple[index++] = icycle;
+	valPowerTuple[index++] = timeTag-scaTuple_->GetCell(idCycleInTuple_[icycle],idStartCalib); //take the RT time start as refernce 
+
+	//Compute the mean power of the two channel (separatly) in the range [f-bw/2, f+bw/2]
+	for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS;++iCh){
+	  TMatrix<r_4> tmp(spectre(Range(iCh),Range(lowerFreqBin_,upperFreqBin_)),false);
+	  r_4 mean = tmp.Sum()/(r_4)tmp.Size();
+	  valPowerTuple[index++] = mean;
+	}//end of channel loop
+       
+	//Fill Tuple
+	powerEvolution.Fill(valPowerTuple);
+      }//end of files loop
+    }//end of cycles loop
+  }//end of mode loop
+
+  //store power evolution Tuple
+  if(debuglev_>0){
+    cout << "ProcessCalibration::processCmd: dump powerEvolution tuple" << endl;
+    powerEvolution.Show(cout);
+  }
+  //
+  //Compute Calibration Coefficients as function of mode/cycle/channels
+  //
+
+  //Tsys,Incremant Intensity... Tuple
+  //mode mode cycle [(tsys0,dint0),...,(tsysN,dintN)]
+  vector<string> varCalibTupleName;
+  varCalibTupleName.push_back("mode");
+  varCalibTupleName.push_back("cycle");
+  for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS;++iCh){
+    stringstream tmp;
+    tmp << iCh;
+    varCalibTupleName.push_back("tsys"+tmp.str());
+    varCalibTupleName.push_back("dint"+tmp.str());
+  }
+  r_4 valCalibTuple[varCalibTupleName.size()];
+  NTuple calibEvolution(varCalibTupleName);
+
+  // select time E [twin0,twin1] U [twin2,twin3] for Tsys
+  // time unit = second 
+  const r_4 twin0 = -3.;
+  const r_4 twin1 = -1.;
+  const r_4 twin2 =  6.;
+  const r_4 twin3 =  8;
+  const r_4 thresholdFactor = 0.20; //80% of the diff. Max-Min intensity
+
+  sa_size_t inModeIdx = powerEvolution.ColumnIndex("mode");
+  sa_size_t inCycleIdx= powerEvolution.ColumnIndex("cycle");
+  sa_size_t inTimeIdx = powerEvolution.ColumnIndex("time");
+  sa_size_t inOffsetCh0 = powerEvolution.ColumnIndex("Ch0"); //nb Ch0 position in the powerEvolution tuple  
+  if(debuglev_>1) cout << "DEBUG: in Idx: (" 
+		       << inModeIdx << ", "
+		       << inCycleIdx << ", "
+		       << inTimeIdx << ", "
+		       << inOffsetCh0 << ")"
+		       << endl;
+
+ 
+  size_t outModeIdx = calibEvolution.ColumnIndex("mode");
+  size_t outCycleIdx= calibEvolution.ColumnIndex("cycle");
+  size_t outOffsetCh0 = calibEvolution.ColumnIndex("tsys0"); //nb Ch0 position in the monitor tuple  
+  size_t outNDataPerCh= 2;
+  if(debuglev_>1)  cout << "DEBUG: out Idx: (" 
+			<< outModeIdx << ", "
+			<< outCycleIdx << ", "
+			<< outOffsetCh0 << ")"
+			<< endl;
+
+  sa_size_t nPowerEvolEntry = powerEvolution.NEntry();
+  double minMode;
+  double maxMode;
+  powerEvolution.GetMinMax("mode",minMode,maxMode);
+  double minCycleNum;
+  double maxCycleNum;
+  powerEvolution.GetMinMax("cycle",minCycleNum,maxCycleNum);
+  if(debuglev_>1)  cout << "DEBUG mode ("<<minMode<<","<<maxMode<<")\n"
+			<< "cycle ("<<minCycleNum<<","<<maxCycleNum<<")"
+			<< endl;
+
+  r_4* aPowerEvolEntry; // a ligne of the powerEvolution tuple
+//   r_4* aPowerEvolEntry = new r_4[powerEvolution.NbColumns()]; // a ligne of the powerEvolution tuple
+
+  r_4 minMean;
+  r_4 maxMean;
+
+  for (size_t iMode = (size_t)minMode; iMode <= (size_t)maxMode; iMode++){
+    for (size_t iCycle = (size_t)minCycleNum; iCycle <= (size_t)maxCycleNum; iCycle++ ){
+      if(debuglev_>1) cout<<"DEBUG >>>>>>> mode/cycle: " << iMode << "/" << iCycle << endl;
+ 
+      valCalibTuple[outModeIdx]=iMode;
+      valCalibTuple[outCycleIdx]=iCycle;
+      //
+      //Compute the Min && Max value of each Ch<i> data
+      if(debuglev_>1) cout<<"DEBUG compute Min and Max for each channels" << endl;
+      //
+      TVector<r_4> chMean[NUMBER_OF_CHANNELS];
+      for (sa_size_t iCh=0;iCh<NUMBER_OF_CHANNELS;iCh++){
+	chMean[iCh].SetSize(nPowerEvolEntry);
+      }
+      for (sa_size_t ie=0; ie<nPowerEvolEntry; ie++){
+	aPowerEvolEntry = powerEvolution.GetVec(ie);
+	if ( (size_t)aPowerEvolEntry[inModeIdx] == iMode && (size_t)aPowerEvolEntry[inCycleIdx] == iCycle ){
+	  for (sa_size_t iCh=0;iCh<NUMBER_OF_CHANNELS;iCh++){
+	    chMean[iCh](ie) = aPowerEvolEntry[iCh+inOffsetCh0];
+	  }//end cut
+	}
+      }//eo loop on tuple entries
+      for (sa_size_t iCh=0;iCh<NUMBER_OF_CHANNELS;iCh++){
+	//
+	//select values to compute background Tsys
+	if(debuglev_>1) {
+	  cout<< "DEBUG >>>> Ch[" << iCh << "]" << endl;
+	  cout<< "DEBUG select values to compute background Tsys " << endl;
+	}
+	//
+       
+	std::vector<r_4> lowerInt;
+	for (sa_size_t ie=0; ie<nPowerEvolEntry; ie++){
+	  aPowerEvolEntry = powerEvolution.GetVec(ie);
+	  if ( (size_t)aPowerEvolEntry[inModeIdx] == iMode && (size_t)aPowerEvolEntry[inCycleIdx] == iCycle ){
+	    r_4 time = aPowerEvolEntry[inTimeIdx];
+	    if ( (time >= twin0 && time <= twin1) ||
+		 (time >= twin2 && time <= twin3)
+		 ) lowerInt.push_back(aPowerEvolEntry[iCh+inOffsetCh0]);
+	  }//end cut
+	} //end loop entries
+	//
+	//compute the Tsys
+	if(debuglev_>1) cout <<"DEBUG compute Tsys" << endl;
+	//
+	std::nth_element(lowerInt.begin(),
+			 lowerInt.begin()+lowerInt.size()/2,
+			 lowerInt.end());
+	r_4 tsys = *(lowerInt.begin()+lowerInt.size()/2);
+	if(debuglev_>1) cout << "DEBUG tsys["<<iCh<<"] : " << tsys <<endl;
+	//
+	//set the threshold for DAB detection
+	//
+	chMean[iCh].MinMax(minMean,maxMean);
+	minMean = (tsys > minMean) ? tsys : minMean; //pb of empty vector
+	if(debuglev_>1) cout << "DEBUG min["<<iCh<<"] : " << minMean
+			     << " max["<<iCh<<"] : " << maxMean
+			     <<endl;
+	r_4 deltathres = thresholdFactor * (maxMean-minMean);
+	r_4 thres =  tsys + deltathres;
+	if(debuglev_>1) cout << "DEBUG thres["<<iCh<<"] : " << thres <<endl;
+	//
+	//collect upper part of the DAB
+	if(debuglev_>1) cout <<"DEBUG collect upper part of the DAB" << endl;
+	//
+	std::vector<r_4> upperInt;
+	for (sa_size_t ie=0; ie<nPowerEvolEntry; ie++){
+	  aPowerEvolEntry = powerEvolution.GetVec(ie);
+	  if ( (size_t)aPowerEvolEntry[inModeIdx] == iMode && (size_t)aPowerEvolEntry[inCycleIdx] == iCycle ){
+	    r_4 mean = aPowerEvolEntry[iCh+inOffsetCh0];
+	    if (mean >= thres) upperInt.push_back(mean);
+	  }//end cut
+	}//eo loop on channels
+	//
+	//compute adjacent differences to detect the 2 DAB levels
+	//
+	if(debuglev_>1) cout << "(DEBUG )size upper [" << iCh << "]: " << upperInt.size() <<endl;
+	std::vector<r_4> upperIntAdjDiff(upperInt.size());
+	std::adjacent_difference(upperInt.begin(),
+				 upperInt.end(),
+				 upperIntAdjDiff.begin());
+	//
+	//Search the 2 DAB states
+	if(debuglev_>1) cout<<"DEBUG Search the 2 DAB states" << endl;
+	//
+	std::vector<r_4> upIntState[2];
+	int state=-1;
+	for (size_t i=1;i<upperInt.size();i++) {//skip first value
+	  if (fabs(upperIntAdjDiff[i])<upperInt[i]*0.010) {
+	    if(state == -1) state=0;
+	    if(state == -2) state=1;
+	    upIntState[state].push_back(upperInt[i]);
+	  } else {
+	    if (state == 0) state=-2;
+	  }
+	}
+	//
+	//Take the mean of the median values of each levels
+	if(debuglev_>1)cout << "DEBUG mean of the median values of each levels" << endl;       
+	//
+	r_4 meanUpper = 0;
+	r_4 nval = 0;
+	for (int i=0;i<2;i++) {
+	  if (!upIntState[i].empty()) {
+// 	    std::nth_element(upIntState[i].begin(),
+// 			     upIntState[i].begin()+upIntState[i].size()/2,
+// 			     upIntState[i].end());
+// 	    meanUpper += *(upIntState[i].begin()+upIntState[i].size()/2);
+	    meanUpper += median(upIntState[i].begin(),upIntState[i].end());
+	    nval++;
+	  } 
+	}
+	meanUpper /= nval;
+	//
+	//Finaly the increase of power due to the DAB is:
+	//
+	r_4 deltaInt = meanUpper - tsys;
+	if(debuglev_>1) cout << "DEBUG deltaInt["<<iCh<<"] : " << deltaInt <<endl;
+	//
+	//Save for monitoring and final calibration operations
+	//
+	valCalibTuple[outOffsetCh0+outNDataPerCh*iCh]   = tsys;
+	valCalibTuple[outOffsetCh0+outNDataPerCh*iCh+1] = deltaInt;
+      }//end loop on channels
+      if(debuglev_>1) cout<<"DEBUG Fill the calibEvolution tuple" << endl;
+      calibEvolution.Fill(valCalibTuple);
+    }//eo loop on Cycles
+  }//eo loop on Modes
+  //
+  //store calibration evolution Tuple
+  //
+  if(debuglev_>0){
+    cout << "ProcessCalibration::processCmd: dump calibEvolution tuple" << endl;
+    calibEvolution.Show(cout);
+  }
+  //
+  //Compute the means per channel of the calibration coefficients (deltaInt)
+  //and save cycle based Calibration Ctes in file named as 
+  //    <source>-<date>-<mode>-<fcalib>MHz-Ch<channel>Cycles.txt
+  //   format <cycle> <coef> 
+  //the means are stored in files     
+  //    <source>-<date>-<mode>-<fcalib>MHz-All.txt
+  //   format <channel> <coef>
+  //
+  sa_size_t nModes = (sa_size_t)(maxMode - minMode) + 1;
+  string calibCoefFileName;
+  ofstream  calibMeanCoefFile[nModes]; //Mean over cycles
+  ofstream  calibCoefFile[nModes][NUMBER_OF_CHANNELS]; //cycle per cycle
+  for (sa_size_t iMode=0; iMode<nModes; iMode++){
+    //The file for the Means Coeff.
+    calibCoefFileName = outputPath_ + "/calib_" 
+      + dateOfRun_ + "_" + StringToLower(sourceName_) + "_"
+      + modeList[iMode] + "_"
+      + freqBAOCalibration_ + "MHz-All.txt";
+    calibMeanCoefFile[iMode].open(calibCoefFileName.c_str());
+    //The file for the cycle per cycle Coeff.
+    for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS; iCh++){
+      stringstream chString;
+      chString << iCh;
+      calibCoefFileName = outputPath_ + "/calib_" 
+	+ dateOfRun_ + "_" + StringToLower(sourceName_) + "_"
+	+ modeList[iMode] + "_"
+	+ freqBAOCalibration_ + "MHz-Ch" + chString.str() + "Cycles.txt";
+      calibCoefFile[iMode][iCh].open(calibCoefFileName.c_str());
+    }
+  }
+
+  r_4* aCalibEvolEntry;
+  sa_size_t nCalibEvolEntry = calibEvolution.NEntry();
+
+  TMatrix<r_4> meanCalibCoef(nModes,NUMBER_OF_CHANNELS); //by default init to 0
+  TMatrix<r_4> nData4Mean(nModes,NUMBER_OF_CHANNELS);
+
+  //READ the calibration tuple, fill the array for mean and write to ascii file
+  for (sa_size_t ie=0; ie<nCalibEvolEntry; ie++){
+    aCalibEvolEntry = calibEvolution.GetVec(ie);
+    if(debuglev_>1){
+      cout << "DEBUG mode/cycle/Coef " 
+	   << aCalibEvolEntry[outModeIdx] << " "
+	   << aCalibEvolEntry[outCycleIdx] << " ";
+    }
+    for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS; iCh++){
+      if(debuglev_>1) cout << aCalibEvolEntry[outOffsetCh0+outNDataPerCh*iCh+1] << " "; // for debug
+      sa_size_t currentMode = (sa_size_t)(aCalibEvolEntry[outModeIdx] - minMode); //ok even if minMode <> 0
+      nData4Mean(currentMode,iCh)++;
+      meanCalibCoef(currentMode,iCh) += aCalibEvolEntry[outOffsetCh0+outNDataPerCh*iCh+1];
+
+      calibCoefFile[currentMode][iCh] << aCalibEvolEntry[outCycleIdx] << " "
+				      << setprecision(12)
+				      << aCalibEvolEntry[outOffsetCh0+outNDataPerCh*iCh+1]
+				      << endl;
+    }
+    if(debuglev_>1) cout << endl; //for debug
+  }
+  
+  //Perform means: true means that div per 0 is treated (slower but safer) 
+  meanCalibCoef.Div(nData4Mean,true);
+  
+  if(debuglev_>0){
+    cout << "DEBUG nData4Mean" << endl;
+    nData4Mean.Print(cout);
+    cout << "DEBUG meanCalibCoef (averaged)" << endl;
+    meanCalibCoef.Print(cout);
+  }
+
+  //Save means Coef
+  for (sa_size_t iMode=0; iMode<nModes; iMode++){
+    for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS; iCh++){
+      calibMeanCoefFile[iMode] << setprecision(12)
+			       << meanCalibCoef(iMode,iCh)
+			       << endl;
+    }
+  }
+
+  //Save Monitor File
+  {
+    string fileName = outputPath_ + "/calib_monitor_" + dateOfRun_ + "_" + StringToLower(sourceName_) + ".ppf";
+    POutPersist calibMonitorFile(fileName);
+    calibMonitorFile << PPFNameTag("powermoni") <<  powerEvolution;
+    calibMonitorFile << PPFNameTag("calibmoni") <<  calibEvolution;
+  }
+
+  //Clean & Return
+  for (sa_size_t iMode=0; iMode<nModes; iMode++){
+    calibMeanCoefFile[iMode].close();
+    for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS; iCh++){
+      calibCoefFile[iMode][iCh].close();
+    }
+  }
+
+  cout << "Ok calibration finished" << endl;  
+  return rc;
+}//ProcessCalibration::processCmd
+
Index: /BAORadio/AmasNancay/v5/analysis-scriptsAndprg-description.txt
===================================================================
--- /BAORadio/AmasNancay/v5/analysis-scriptsAndprg-description.txt	(revision 596)
+++ /BAORadio/AmasNancay/v5/analysis-scriptsAndprg-description.txt	(revision 596)
@@ -0,0 +1,291 @@
+Title: Status of the programs and scripts used for Amas@Nancay analysis at CCIN2P3
+Revision: 11/10/11 (JEC)
+Author: J.E Campagne 22/7/11
+----------------------------
+
+Intro:
+All these tools are located for the while in J.E Campagne private directory, so they are not
+yet available to public usage and this note is essentially for information and software tracking.
+
+-----------------------------------------------------------
+Analysis program
+------------------------------------------------------------
+o analysis.cc
+	- perfom
+		. gain spectra determination + monitoring
+                . ON-OFF spectra without calibration 
+		. calibration coefficient determination + monitoring
+		. ON-OFF spectra determination (no RT calibration included)
+	- Todo
+		. include RT calibration, or a RT/BAO calibration using a calibrator source
+	- comments
+		. the STANDARD usage since end september 11 is GAIN + ON-OFF wo calibration
+		
+-----------------------------------------------------------
+Collection of  Bourne SHELL script for analysis
+------------------------------------------------------------
+
+A) Utilitary scripts to follow the DAQ & Analysis progress
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+o mkarchive.sh
+---------------
+	- perform the archive of a processing in Irods
+	  . create a <ppTag>Arch<apTag> directory 
+	    . move the cabli_*.txt files
+	    . move the *.ppf / *.fits files results of the analysis
+	    . for the gain...fits only a copy is done to keep a version
+	    . move the Off and On directorys
+	  . create new fresh On and Off directory
+
+
+o statusdaq.sh
+--------------
+	- perform
+		. scan all the /baoradio/data/AmamNancay to look at the directories and and make
+			a summary of the Data Acquisition
+
+o statusheader.sh
+-----------------
+	- perform
+		. scan Irods directories to look at header fits files extraction progress 
+		
+o statusgain.sh
+---------------
+	- perform
+		. scan Irods directories to look at FINAL gain_* files production progress 
+
+o statuscalib.sh
+----------------
+	- perform
+		. scan Irods directories to look at INTERMEDIATE calibcycle files production progress
+	- Todo
+		. scan also for FINAL calib_* files progress
+o statusonoff.sh
+----------------
+	- perform
+		. scan Irods On and Off directories to look at datacycle<cycle> contents
+
+o statusCycles.sh 
+-----------------
+	- perform
+		. scan Irods directories to look at sca<>.sum files to count the number of cycles per run
+
+B) Utilitary scripts to send to BQS system high level task
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++		
+o submit2bqs-hdrfitsextractor.sh
+--------------------------------
+        - SHOULD BE DONE BEFORE gain/calib/analysis
+	- send the hdrfitsextractor.sh script to BQS system	
+	- Todo list
+		- TO MIGRATE TO NEW BATCH 
+
+o submit2bqs-scaextractor.sh
+--------------------------------
+        - SHOULD BE DONE BEFORE gain/calib/analysis
+	- send the scaextractor.sh script to BQS system
+		although this script is called by getscafiles lower level script
+	- Todo list
+		- TO MIGRATE TO NEW BATCH 
+
+o submit2bqs-procspecmfib.sh
+-----------------------------
+	- SHOULD BE DONE for processing signals for FFT/paquet median filtering
+	- GAIN/CALIB/ON, OFF... 
+	- prepare and send in batch the proc_specmfib.sh to BQS
+	- exemple
+        ./submit2bqs-procspecmfib.sh -src Abell85 -date 20110422 -type CALIBOFF -fcycle 8 -lcycle 14
+	- Todo list
+		- TO MIGRATE TO NEW BATCH 
+
+o submit2bqs-anagainmaker.sh
+----------------------------
+	- done after proc_specmfib
+	- prepare and send the analyse.cc prg for gain computation
+	- exemple
+	- Todo list
+		- TO MIGRATE TO NEW BATCH 
+
+o submit2bqs-anacalibmaker.sh
+----------------------------
+	- done after proc_specmfib
+	- prepare and send the analyse.cc prg for calibration computation
+	- exemples: 
+	> $./submit2bqs-anacalibmaker.sh -src Abell85 -date 20110410
+
+	
+	- Todo list
+		- TO MIGRATE TO NEW BATCH 
+	
+o submit2qs-onoffmaker.sh (OBSOLETE ???)
+--------------------------
+	- send the onoffmaker.sh script to BQS system
+	- Todo list
+		- TO MIGRATE TO NEW BATCH 
+
+o submit2bqs-rawonoffmaker.sh (OBSOLETE ???) 
+-----------------------------
+	- used after the anagainmaker 
+	- prepare and send in batch the proc_rawonoff.sh to BQS system
+	- exemple submit2bqs-rawonoffmaker.sh -src Abell85 -date 20110417 -fcycle 8 -lcycle 23 -type ON	
+	- Todo list
+		- TO MIGRATE TO NEW BATCH
+
+o submit2qs-gainmaker.sh (OBSOLETE)
+-------------------------
+	- send the gainmaker.sh script to BQS system 
+	- Todo list
+		- TO MIGRATE TO NEW BATCH
+
+o submit2qs-calibmaker.sh (OBSOLETE)
+--------------------------
+	- send the calibmaker.sh script to BQS system
+	- Todo list
+		- TO MIGRATE TO NEW BATCH 
+
+		
+C) High level scripts 
+++++++++++++++++++++++		
+o hdrfitsextractor.sh
+---------------------
+	- SHOULD BE DONE BEFORE ANYTHING
+	- perform
+		. extraction of the header part of the signalXYZ.fits files and
+		. put the results into Irods	
+	- use 
+		. statusdaq.sh	
+
+o anagainmaker.sh
+-----------------
+	- perform 
+	  . the analysis of the above fits files to determine the 
+			gains of each channel: produce gain_* files (monitoring + gain files)
+	  . put the results into Irods
+	- use 
+		- getscafiles.sh
+		- analysis.cc	
+
+o anacalibmaker.sh
+------------------
+	- perfom
+	  . prepare the analysis of the above fits files
+	  . put calib_* files (monitoring +  calibration files) into Irods
+	- use 
+		- getscafiles.sh
+		- analysis.cc	
+
+
+o gainmaker.sh (OBOLETE)
+---------------
+	- perform 
+		1) the extraction of signalXYZ.fits files 
+			concerned by the OFF-calibration time window
+			of the cycle located at the middle of the run
+		2) . the analysis of the above fits files to determine the 
+			gains of each channel: produce gain_* files (monitoring + gain files)
+			. put the results into Irods
+	- use 
+		- statusdaq.sh, proc_script.sh, getscafiles.sh
+		- analysis.cc	
+	
+o calibmaker.sh (OBSOLETE)
+---------------
+	- perfom
+		1) several x-checks to see at which stage of the analysis process we are
+		2) trig the proc_script.sh script if necessary to create the spectra fits files via specmfib.cc prg 
+		3) . prepare the analysis of the above fits files
+		   . put calib_* files (monitoring +  calibration files) into Irods
+	- use 
+		- statusdaq.sh, proc_script.sh, getscafiles.sh
+		- analysis.cc	
+
+o onoffmaker.sh (preliminary)
+----------------------------
+	- perform
+		1) several x-checks to see at which stage of the analysis process we are
+		2) trig the proc_script.sh script if necessary to create the spectra fits files via specmfib.cc prg 
+		3) prepare the analysis of the above fits files
+		4) put dataRaw_*        (raw spectra), 
+		       dataBAOCalib_*   (after BAO calibration), 
+		       dataBAORTCalib_* (after BAO & RT calibration), 
+		       diffOnOff_*      (ON-OFF spectra) 
+
+D) Lower level scripts
+++++++++++++++++++++++
+
+o proc_specmfib.sh
+------------------
+	- perform all the preparation work to send in batch the "specmfib" 
+	  program which perform the FFT and median/mean spectra 
+	  for the GAIN/CALIB/ON-OFF... task
+	- use
+	  - getscafiles.sh, select.sh, statusdaq.sh, getsignalfiles.sh
+	- comments
+	  - this is the pre-processing of the data to be used before
+	    anaXYZ script which are post-processing
+
+
+o proc_rawonoff.sh (OBSOLETE)
+------------------
+	- this is the script to use to perform the "datacycle" contents
+	- perform all the preparation work to send in batch the "specmfib" program 
+			which perform the FFT and median/mean spectra for the ON-OFF task
+	- use
+	  - getscafiles.sh, select.sh, statusdaq.sh, getsignalfiles.sh
+	- comments
+	  - contrary to proc_script (below) specmfib is activated in the same thread
+
+o proc_script.sh (OBSOLETE)
+-----------------
+	- VERY BUSY script
+	- perform 
+		1) all the preparation work to send in batch the "specmfib" program 
+			which perform the FFT and median/mean spectra for GAIN, CALIBRATION, ON-OFF task
+		2) the script that is sent in batch put the results into Irods	
+	- use
+		- getscafiles.sh, select.sh, getsignalfiles.sh
+	- Todo list
+		- TO MIGRATE TO NEW BATCH 
+		
+
+o scaextractor.sh
+-----------------
+	- perform
+		1) extraction of the scaXYZ file
+		2) if the scaXYZ.sum and the scaXYZ.sum.trans files do not exist
+			. create and put them into Irods
+			. scaXYZ.sum = summary of the SCA file
+			. scaXYZ.sum.trans = transformation of the date format of the scaXYZ.sum file	
+	- use
+		- sca.sh, transdate.sh
+		
+o sca.sh
+--------
+	- perform
+		. produce the scaXYZ.sum (= summary of the SCA file) from a scaXYZ file
+		
+o transdate.sh
+--------------
+	- perform
+		. produce the scaXYZ.sum.trans (= transformation of the date format) from the scaXYZ.sum file	
+
+o select.sh
+-----------
+	-perform 
+		. the selection of the signalXYZ.fits files according to the type of task requested
+			as ON, OFF, CALIBON, CALIBOFF, GAIN
+		
+o getscafiles.sh
+----------------
+	- perform
+		. download from Irods the scaXYZ, scaXYZ.sum and scaXYZ.sum.trans files	
+	- use
+		scaextractor.sh
+		
+o getsignals.sh
+---------------
+	- perform
+		. download from Irods the signalXYZ.fits files
+		
+		
+		
+
Index: /BAORadio/AmasNancay/v5/anarawonoffmaker.sh
===================================================================
--- /BAORadio/AmasNancay/v5/anarawonoffmaker.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/anarawonoffmaker.sh	(revision 596)
@@ -0,0 +1,324 @@
+#!/bin/sh -xvf
+#Perform the ON-OFF analysis
+DATE=/bin/date
+GREP=/bin/grep
+AWK=/bin/awk
+ECHO=/bin/echo
+WC=/usr/bin/wc
+CAT=/bin/cat
+PRINTF=/usr/bin/printf
+FIND=/usr/bin/find
+MKDIR=/bin/mkdir
+XARGS=/usr/bin/xargs
+SORT=/bin/sort
+RM=/bin/rm
+TR=/usr/bin/tr
+CP=/bin/cp
+LS=/bin/ls
+CHMOD=/bin/chmod
+
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+#set Irods environment    
+. /usr/local/shared/bin/irods_env.sh -noverbose
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+#which source to analyse
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+dateSelected=
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=Off
+while [ $# -gt 0 ]
+  do
+  case "$1" in
+      -src)  sourceRadio=$2;    shift;;
+      -date) dateSelected=$2;     shift;;
+      -sim)  simulationMode=On;;
+      -h)
+      echo >&2 \
+	  "usage: $0 -src souce -date YYYYMMDD [-freq freq in MHz (default ${freqBAOCalib})] [-sim to trig simulation mode]"
+      exit 1;;
+      *)  break;;	# terminate while loop
+  esac
+  shift
+done
+
+if [ ${simulationMode} = "On" ]; then
+    $ECHO "INFO ${scriptName} running in SIMUL mode"
+fi
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+case ${sourceRadio} in
+    Abell85) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    Abell2440) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    Abell1205) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    *) ECHO "FATAL (${scriptName}): process ${sourceRadio} not yet foreseen"
+    exit 1;;
+esac
+
+srclower=`${ECHO} ${sourceRadio} | ${TR} "[:upper:]" "[:lower:]" `
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+#wakeup the NFS disk
+$LS -l ${tmppublicpath} > /dev/null
+#clean previous spurious files
+$RM -f ${tmppublicpath}/*.finished
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/isInteractive.sh
+isInteractive=$(isInteractive)
+if [ ${isInteractive} == "1" ]; then
+  $ECHO "Usage in INTERACTIVE may be destructive... To be used with great care !!!!"
+   exit 0;
+fi
+
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+localpath="${sourceRadio}"
+$MKDIR -p ./${localpath}
+cd ./${localpath}
+
+#save the top directory
+topDir=`pwd`
+
+#Path of the utility scripts
+scriptpath=${SCRIPTPATH}
+
+#JEC 1/10/11 Use generic baodaqstatus name 
+#get the daq current irod status
+#tag=`${DATE} +%F`
+#OUT1=${publicpath}/baodaqstatus-${tag}.txt
+OUT1=${publicpath}/baodaqstatus-current.txt
+
+if [ ! -e ${OUT1}  -o ! -r ${OUT1} ]; then
+    $ECHO "FATAL (${scriptName}): ${OUT1} has a problem"
+    exit 1
+fi
+
+
+
+$ECHO "You have selected sourceRadio = ${sourceRadio} [date = ${dateSelected}]"
+tableau=( `$GREP -i "${dateSelected}${srclower}" ${OUT1} | $AWK '( NF==4 ) { print $2 }' ` )
+IFS='
+' 
+tableau=( $( $PRINTF "%s\n" "${tableau[@]}" | $AWK 'x[$0]++ == 0' ) )
+IFS=$DefaultIFS
+
+
+for i in ${tableau[@]}
+  do
+#
+# start a "fresh" session  
+  cd ${topDir}
+  $LS | $XARGS -i $RM -rf {}
+  
+  $ECHO "DEBUG: (${scriptName}) irods root dir $i"
+  dateDAQ=`$ECHO ${i} | $AWK '{split($0,a,"/"); print a[6];}' | $AWK "{sub(/${srclower}/,\"\"); print}"`
+
+  $ECHO "DEBUG: (${scriptName}): we are in directory `pwd` the topDir=${topDir}"
+  $LS -lrt
+
+  gainDone=`ils ${i} 2>&1 | $GREP -i "gain_.*\.fits" | $WC -l`
+  if [ ! ${gainDone} -gt 0 ]; then
+      $ECHO "FATAL (${scriptName}): gain file DOES NOT exist skip `basename $i` "
+      continue
+  fi
+
+######
+  $ECHO ">>>>>>>>>>>>> ANALYSIS Part of ${sourceRadio} ${dateDAQ}"
+#go to the .../source/date-sourcelowercase directory
+#download Off/datacycle<> and On/datacycle<> directories
+  $MKDIR -p ${topDir}/${dateDAQ}${srclower}
+  cd ${topDir}/${dateDAQ}${srclower}
+  aboveOnOffDir=`pwd`
+  $ECHO "DEBUG (${scriptName}): we are in directory: <`pwd`>"
+#
+  mode="Off"
+  $ECHO "DEBUG (${scriptName}): START download the ${mode} data fits files"
+  inFileDirectory="./${mode}"
+  $MKDIR -p ${inFileDirectory}
+  listOfDataCycle=( `ils ${i}/${mode} 2>&1 | $GREP -i "datacycle"|$AWK 'BEGIN{FS="C- "}{print $2}' | $XARGS -i basename {} | $SORT -k1.10n` )
+  IFS='
+'
+  listOfDataCycle=( $( $PRINTF "%s\n" "${listOfDataCycle[@]}" | $AWK 'x[$0]++ == 0' ) )
+  IFS=$DefaultIFS
+
+  firstCycleOff=`$ECHO ${listOfDataCycle[0]} | $AWK '{match($0,"[0-9]+",arr); print arr[0]}'`
+  nCyclesOff=`expr ${#listOfDataCycle[*]} - 1`
+
+  if [ ${nCyclesOff} -eq -1 ]; then
+      continue
+  fi
+
+  lastCycleOff=`$ECHO ${listOfDataCycle[${nCyclesOff}]} | $AWK '{match($0,"[0-9]+",arr); print arr[0]}'`
+
+  listOfDataCycle=( "${listOfDataCycle[@]/#/${i}/${mode}/}" )
+
+  
+  for j in ${listOfDataCycle[@]}
+    do
+    irodsDownDir="${j}"
+    OUT=./getInFits.$$
+    iget -r -f -K ${irodsDownDir} ${inFileDirectory} > ${OUT} 2>&1
+    igetStatus=`$GREP "^ERROR" ${OUT}`
+    if [ "<$igetStatus>" != "<>" ]; then
+	$ECHO "FATAL (${scriptName}): error while iget fits files:"
+	$ECHO $igetStatus
+	$ECHO " ==> skip this run $sourceRadio $dateDAQ"
+	continue
+    fi
+    $RM -f ${OUT}
+  done
+  $ECHO "DEBUG (${scriptName}): END download the ${mode} data fits files"
+#
+  mode="On"
+  $ECHO "DEBUG (${scriptName}): START download the ${mode} data fits files"
+  inFileDirectory="./${mode}"
+  $MKDIR -p ${inFileDirectory}
+
+  listOfDataCycle=( `ils ${i}/${mode} 2>&1 | $GREP -i "datacycle" |$AWK 'BEGIN{FS="C- "}{print $2}' | $XARGS -i basename {} | $SORT -k1.10n` )
+  IFS='
+'
+  listOfDataCycle=( $( $PRINTF "%s\n" "${listOfDataCycle[@]}" | $AWK 'x[$0]++ == 0' ) )
+  IFS=$DefaultIFS
+
+  firstCycleOn=`$ECHO ${listOfDataCycle[0]} | $AWK '{match($0,"[0-9]+",arr); print arr[0]}'`
+  nCyclesOn=`expr ${#listOfDataCycle[*]} - 1`
+
+  if [ ${nCyclesOn} -eq -1 ]; then
+      continue
+  fi
+
+  lastCycleOn=`$ECHO ${listOfDataCycle[${nCyclesOn}]} | $AWK '{match($0,"[0-9]+",arr); print arr[0]}'`
+
+  listOfDataCycle=( "${listOfDataCycle[@]/#/${i}/${mode}/}" )
+
+#
+#Check if there is the same number of cycles in Off and On mode
+#      
+#first cycle = max(firstCycleOn, firstCycleOff)
+#last  cycle = min(lastCycleOn,lastCycleOff)
+
+  if [ ${firstCycleOn} -eq ${firstCycleOff} -a ${lastCycleOn} -eq ${lastCycleOff} ]; then
+      firstCycle=${firstCycleOff}
+      lastCycle=${lastCycleOff}
+  else
+      $ECHO "INFO (${scriptName}): missmatch between Off and On mode"
+      $ECHO "${firstCycleOn} != ${firstCycleOff} OR ${lastCycleOn} != ${lastCycleOff}"
+      firstCycle=${firstCycleOff}
+      if [ ${firstCycleOn} -gt ${firstCycle} ]; then
+	  firstCycle=${firstCycleOn}
+      fi
+      lastCycle=${lastCycleOff}
+      if [ ${lastCycleOn} -lt ${lastCycle} ]; then
+	  lastCycle=${lastCycleOn}
+      fi
+  fi
+  $ECHO "INFO (${scriptName}): use cycles [${firstCycle}, ${lastCycle}]"
+  
+
+  for j in ${listOfDataCycle[@]}
+    do
+    irodsDownDir="${j}"
+    OUT=./getInFits.$$
+    iget -r -f -K ${irodsDownDir} ${inFileDirectory} > ${OUT} 2>&1
+    igetStatus=`$GREP "^ERROR" ${OUT}`
+    if [ "<$igetStatus>" != "<>" ]; then
+	$ECHO "FATAL (${scriptName}): error while iget fits files:"
+	$ECHO $igetStatus
+	$ECHO " ==> skip this run $sourceRadio $dateDAQ"
+	continue
+    fi
+    $RM -f ${OUT}
+  done
+  $ECHO "DEBUG (${scriptName}): END download the ${mode} data fits files"
+#Get sca file
+  $ECHO "DEBUG (${scriptName}): START call getscafiles.sh ${sourceRadio} ${dateDAQ}"
+  OUT1=./getScaStatus.$$
+  $RM -f ${tmppublicpath}/getscafiles.finished
+  ${scriptpath}/getscafiles.sh ${sourceRadio} ${dateDAQ} > ${OUT1} 2>&1
+#  while [ ! -f "${tmppublicpath}/getscafiles.finished" ]; do
+#      $ECHO "INFO (${scriptName}): waiting for ${tmppublicpath}/getscafiles.finished"
+#      date +%T
+#      sleep 30
+#  done
+  $RM ${tmppublicpath}/getscafiles.finished
+  $ECHO "DEBUG (${scriptName}): END"
+#
+  getScaStatus=`$GREP "^\(FATAL\|ERROR\)" ${OUT1}`
+#	
+  if [ "<${getScaStatus}>" != "<>" ]; then
+      $ECHO "FATAL (${scriptName}): error to get sca file for $sourceRadio $dateDAQ"
+      $ECHO "DEBUG (${scriptName}): START with cat ${OUT1}"
+      $CAT ${OUT1}
+      $ECHO "DEBUG (${scriptName}): END"
+      continue
+  fi
+  $RM -f ${OUT1}
+
+  scaFile=`$FIND . -name "sca*.sum.trans" | $XARGS -i basename {}`
+
+  
+#prepare job submission
+  cd ${aboveOnOffDir}
+#the default spectra name is medfiltmtx, otherwise use -specname <a_string>
+
+  logFile="analyse_RAWDATA_${sourceRadio}_${dateDAQ}.log"
+  $ECHO "DEBUG (${scriptName}): execute the analysis... should not take long. `date`"
+  if [ ${simulationMode} = "On" ]; then
+      $ECHO "SIMUL: ${scriptpath}/Objs/analyse -act rawOnOff -inPath ${iojobpath}  -source  ${sourceRadio} -date ${dateDAQ} -sca ${scaFile} -specdir datacycle -numcycle ${firstCycle},${lastCycle} -debug 1 >& ${logFile}"
+      cat > ${logFile} <<EOF
+      Ok rawOnOff finished
+EOF
+  else
+      ${scriptpath}/Objs/analyse -act rawOnOff -inPath ${iojobpath}  -source  ${sourceRadio} -date ${dateDAQ} -sca ${scaFile} -specdir datacycle -numcycle ${firstCycle},${lastCycle} -debug 1 >& ${logFile}
+  fi
+  $ECHO "DEBUG (${scriptName}): analysis finished `date`. Look for errors before saving to Irods"
+  rcstatus=`$GREP -i "Ok rawOnOff finished" ${logFile} | $WC -l`
+  if [ ${rcstatus} -eq 0 ]; then
+      $ECHO "INFO (${scriptName}): analysis problem for ${sourceRadio} ${dateDAQ}"
+      $ECHO "                      START logfile"
+      $CAT ${logFile}
+      $ECHO "                      END   logFile"
+#clean and leave
+      cd ${aboveOnOffDir}
+      $LS | $XARGS -i $RM -rf {}
+      continue
+  fi
+#Save into Irods
+  $ECHO "DEBUG (${scriptName}): START save output files"
+  $LS ${aboveOnOffDir}
+#use -f option for iput ONLY to force override
+  if [ ${simulationMode} = "On" ]; then
+      $ECHO "SIMUL: here we look for output files and put them in Irods"
+  else
+      $LS -lrth
+      $FIND . -name "dataRaw_*"      -print | $XARGS -i  iput -f -v -K {} ${i}
+      $FIND . -name "diffOnOffRaw_*" -print | $XARGS -i  iput -f -v -K {} ${i}
+  fi
+#save analysis logfile
+  $LS -l ${tmppublicpath} > /dev/null
+  $CP ${logFile} ${tmppublicpath}
+  $ECHO "DEBUG (${scriptName}): END save output files"
+#clean up to avoid scratch SIZE EXCEED LIMIT
+  cd ${aboveOnOffDir}
+  $LS | $XARGS -i $RM -rf {}
+
+done
+
+exit 0
Index: /BAORadio/AmasNancay/v5/calibmaker.sh
===================================================================
--- /BAORadio/AmasNancay/v5/calibmaker.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/calibmaker.sh	(revision 596)
@@ -0,0 +1,429 @@
+#!/bin/sh -xvf
+#download SCA file, proceed to introspection, and upload results
+DATE=/bin/date
+GREP=/bin/grep
+AWK=/bin/awk
+ECHO=/bin/echo
+WC=/usr/bin/wc
+CAT=/bin/cat
+PRINTF=/usr/bin/printf
+FIND=/usr/bin/find
+MKDIR=/bin/mkdir
+XARGS=/usr/bin/xargs
+SORT=/bin/sort
+RM=/bin/rm
+TR=/usr/bin/tr
+CP=/bin/cp
+LS=/bin/ls
+CHMOD=/bin/chmod
+
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+#set Irods environment    
+. /usr/local/shared/bin/irods_env.sh -noverbose
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+#which source to analyse
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+freqBAOCalib=1346
+bwBAOCalib=6.25
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=Off
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -src)  sourceRadio=$2; shift;;
+      -freq) freqBAOCalib=$2; shift;;
+      -bwd)  bwBAOCalib=$2; shift;;
+      -sim) simulationMode=On;;
+	-h)
+	    echo >&2 \
+	    "usage: $0 -src souce [-freq freq in MHz (default ${freqBAOCalib})] [-bwd bandwidth in MHz (default ${bwBAOCalib})]"
+	    exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+if [ ${simulationMode} = "On" ]; then
+    $ECHO "INFO ${scriptName} running in SIMUL mode"
+fi
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+case ${sourceRadio} in
+    Abell85) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    Abell2440) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    Abell1205) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    *) ECHO "FATAL (${scriptName}): process ${sourceRadio} not yet foreseen"
+    exit 1;;
+esac
+
+srclower=`${ECHO} ${sourceRadio} | ${TR} "[:upper:]" "[:lower:]" `
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+#wakeup the NFS disk
+$LS -l ${tmppublicpath} > /dev/null
+#clean previous spurious files
+$RM -f ${tmppublicpath}/*.finished
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/isInteractive.sh
+isInteractive=$(isInteractive)
+if [ ${isInteractive} == "1" ]; then
+  $ECHO "Usage in INTERACTIVE may be destructive... To be used with great care !!!!"
+   exit 0;
+fi
+
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+localpath="${sourceRadio}"
+$MKDIR -p ./${localpath}
+cd ./${localpath}
+
+#save the top directory
+topDir=`pwd`
+
+#Path of the utility scripts
+scriptpath=${SCRIPTPATH}
+
+#JEC 1/10/11 Use generic baodaqstatus name 
+OUT1=${publicpath}/baodaqstatus-current.txt
+#
+#get the daq current irod status
+#tag=`${DATE} +%F`
+#OUT1=${publicpath}/baodaqstatus-${tag}.txt
+#
+if [ ! -e ${OUT1}  -o ! -r ${OUT1} ]; then
+    $ECHO "FATAL (${scriptName}): ${OUT1} has a problem"
+    exit 1
+#    $ECHO "We should bring the DAQ status more up to date, this take 1 or 2sec..."
+#    $RM -f ${tmppublicpath}/statusdaq.finished
+#   ${scriptpath}/statusdaq.sh > ${OUT1}
+#    while [ ! -f "${tmppublicpath}/statusdaq.finished" ]; do
+#	sleep 30
+#    done
+#    $RM ${tmppublicpath}/statusdaq.finished
+#protect against remove/rewriting    
+#    $CHMOD -v 444 ${OUT1} 
+fi
+
+
+#Nb: if we want to implement a loop on sources we have to take care of srclower...
+
+$ECHO "You have selected sourceRadio = $sourceRadio"
+tableau=( `$GREP -i ${sourceRadio} ${OUT1} | $AWK '( NF==4 ) { print $2 }' ` )
+IFS='
+' 
+tableau=( $( $PRINTF "%s\n" "${tableau[@]}" | $AWK 'x[$0]++ == 0' ) )
+IFS=$DefaultIFS
+
+
+for i in ${tableau[@]}
+  do
+#
+# start a "fresh" session  
+  cd ${topDir}
+  $LS | $XARGS -i $RM -rf {}
+
+  
+  $ECHO "DEBUG: (${scriptName}) irods root dir $i"
+  dateDAQ=`$ECHO ${i} | $AWK '{split($0,a,"/"); print a[6];}' | $AWK "{sub(/${srclower}/,\"\"); print}"`
+
+  $ECHO "DEBUG: (${scriptName}): we are in directory `pwd` the topDir=${topDir}"
+  $LS -lrt
+
+
+#JEC 1/10/11 Use generic baodaqstatus name 
+#Look if the date has changed since beginning of the job!
+#  curtag=`${DATE} +%F`
+#  if [ "<${curtag}>" != "<${tag}>" ]; then
+#      tag=${curtag}
+#it is necessary to update the daq status as the day has changed during the processing... (batch can take a long time...)
+#      OUT1=${publicpath}/baodaqstatus-${curtag}.txt
+#      $ECHO "We should bring the DAQ status more up to date, this take 1 or 2sec..."
+#      $RM -f ${tmppublicpath}/statusdaq.finished
+#      ${scriptpath}/statusdaq.sh > ${OUT1}
+#      while [ ! -f "${tmppublicpath}/statusdaq.finished" ]; do
+#	  sleep 30
+#      done
+#      $RM ${tmppublicpath}/statusdaq.finished
+#protect against remove/rewriting    
+#      $CHMOD -v 444 ${OUT1} 
+#  fi
+#
+# look if the calibration files already exist
+#
+  alreadyDone=`ils ${i} 2>&1 | $GREP -i "calib_.*\.txt" | $WC -l`
+  if [ ${alreadyDone} -gt 0 ]; then
+      $ECHO "INFO (${scriptName}): calibration coef files already exist"
+      continue
+  fi
+#
+  somethingTodo=1
+  input4calibOff=`ils ${i}/Off 2>&1 | $GREP -i "calibcycle" | $AWK 'BEGIN{FS="C- "}{print $2}' | $XARGS -i basename {} | $SORT -k1.11n`  
+  input4calibOn=`ils ${i}/On 2>&1 | $GREP -i "calibcycle" | $AWK 'BEGIN{FS="C- "}{print $2}' | $XARGS -i basename {} | $SORT -k1.11n`  
+#
+  if [ "<${input4calibOff}>" != "<>" -a "<${input4calibOn}>" != "<>"  ]; then
+#look at the content of the calibcycle directory as may be the previous batch job has crashed
+      tableauOff=( `$ECHO ${input4calibOff}` )
+      IFS='
+'
+      tableauOff=( $( $PRINTF "%s\n" "${tableauOff[@]}" | $AWK 'x[$0]++ == 0' ) )
+      IFS=$DefaultIFS
+#
+      nTotFilesOff=0
+      for j in ${tableauOff[@]}
+	do
+	nFiles=`ils ${i}/Off/${j} | $GREP -i "medfiltmtx" | $WC -l`
+	nTotFilesOff=`expr ${nTotFilesOff} + ${nFiles}`
+      done
+#
+      tableauOn=( `$ECHO ${input4calibOn}` )
+      IFS='
+      '
+      tableauOn=( $( $PRINTF "%s\n" "${tableauOn[@]}" | $AWK 'x[$0]++ == 0' ) )
+      IFS=$DefaultIFS
+#
+      nTotFilesOn=0
+      for j in ${tableauOn[@]}
+	do
+	nFiles=`ils ${i}/On/${j} | $GREP -i "medfiltmtx" | $WC -l`
+	nTotFilesOn=`expr ${nTotFilesOn} + ${nFiles}`
+      done
+      diffOnOff=`expr ${nTotFilesOff} - ${nTotFilesOn}`
+      if [ ${diffOnOff} -lt 0 ]; then
+	  zero=0
+	  diffOnOff=`expr ${zero} - ${diffOnOff}` 
+      fi
+#allow up to 5 files differences
+      if [  ${nTotFilesOff} -gt 0 -a ${nTotFilesOn} -gt 0  ]; then
+	  somethingTodo=0
+	  $ECHO "DEBUG (${scriptName}): $sourceRadio $dateDAQ has <${nTotFilesOff}> Off-files and <${nTotFilesOn}> On-files but OK"
+      else
+	  $ECHO "INFO (${scriptName}): $sourceRadio $dateDAQ has <${nTotFilesOff}> Off-files and <${nTotFilesOn}> On-files => one should rebuild has something is wrong"
+      fi
+# 
+  fi 
+  if [ ${somethingTodo} -eq 1 ]; then
+#
+      $ECHO ">>>>>>>>>>>>>>>> Do $sourceRadio $dateDAQ CALIBOFF"
+      $RM -f ${tmppublicpath}/proc_script.finished
+      if [ ${simulationMode} = "On" ]; then
+	  $ECHO "SIMUL: ${scriptpath}/proc_script.sh $sourceRadio $dateDAQ CALIBOFF"
+      else
+	  ${scriptpath}/proc_script.sh $sourceRadio $dateDAQ CALIBOFF
+	  while [ ! -e "${tmppublicpath}/proc_script.finished"  ]; do
+	      $ECHO "INFO (${scriptName}): waiting for ${tmppublicpath}/proc_script.finished"
+	      date +%T
+	      sleep 60
+	  done
+      fi
+      $ECHO "INFO (${scriptName}): proc_script has finished"
+      $ECHO ">>>>>>>>>>>> Done $sourceRadio $dateDAQ CALIBOFF"
+      $ECHO ">>>>>>>>>>>>>>>> Do $sourceRadio $dateDAQ CALIBON"
+      $RM ${tmppublicpath}/proc_script.finished
+      
+      if [ ${simulationMode} = "On" ]; then
+	  $ECHO "SIMUL: ${scriptpath}/proc_script.sh $sourceRadio $dateDAQ CALIBON"
+      else
+	  ${scriptpath}/proc_script.sh $sourceRadio $dateDAQ CALIBON
+	  while [ ! -e "${tmppublicpath}/proc_script.finished"  ]; do
+	      $ECHO "INFO (${scriptName}): waiting for ${tmppublicpath}/proc_script.finished"
+	      date +%T
+	      sleep 60
+	  done
+      fi
+      $ECHO "INFO (${scriptName}): proc_script has finished"
+      $RM ${tmppublicpath}/proc_script.finished
+#Todo see if there is errors in the log file before copy
+      $ECHO ">>>>>>>>>>>> Done $sourceRadio $dateDAQ CALIBON"
+######
+  else
+######
+      $ECHO ">>>>>>>>>>>>> ANALYSIS Part of ${sourceRadio} ${dateDAQ}"
+      #go to the .../source/date-sourcelowercase directory
+#download Off/calibcycle<> and On/calibcycle<> directories
+      $MKDIR -p ${topDir}/${dateDAQ}${srclower}
+      cd ${topDir}/${dateDAQ}${srclower}
+      aboveOnOffDir=`pwd`
+      $ECHO "DEBUG (${scriptName}): we are in directory: <`pwd`>"
+#
+      mode="Off"
+      $ECHO "DEBUG (${scriptName}): START download the ${mode} calib fits files"
+      inFileDirectory="./${mode}"
+      $MKDIR -p ${inFileDirectory}
+      listOfCalibCycle=( `ils ${i}/${mode} 2>&1 | $GREP -i "calibcycle"|$AWK 'BEGIN{FS="C- "}{print $2}' | $XARGS -i basename {} | $SORT -k1.11n` )
+      IFS='
+'
+      listOfCalibCycle=( $( $PRINTF "%s\n" "${listOfCalibCycle[@]}" | $AWK 'x[$0]++ == 0' ) )
+      IFS=$DefaultIFS
+
+      firstCycleOff=`$ECHO ${listOfCalibCycle[0]} | $AWK '{match($0,"[0-9]+",arr); print arr[0]}'`
+      nCyclesOff=`expr ${#listOfCalibCycle[*]} - 1`
+
+      lastCycleOff=`$ECHO ${listOfCalibCycle[${nCyclesOff}]} | $AWK '{match($0,"[0-9]+",arr); print arr[0]}'`
+
+      listOfCalibCycle=( "${listOfCalibCycle[@]/#/${i}/${mode}/}" )
+
+      
+      for j in ${listOfCalibCycle[@]}
+	do
+	irodsDownDir="${j}"
+	OUT=./getInFits.$$
+	iget -r -f -K ${irodsDownDir} ${inFileDirectory} > ${OUT} 2>&1
+	igetStatus=`$GREP "^ERROR" ${OUT}`
+	if [ "<$igetStatus>" != "<>" ]; then
+	    $ECHO "FATAL (${scriptName}): error while iget fits files:"
+	    $ECHO $igetStatus
+	    $ECHO " ==> skip this run $sourceRadio $dateDAQ"
+	    continue
+	fi
+	$RM -f ${OUT}
+      done
+      $ECHO "DEBUG (${scriptName}): END download the ${mode} calib fits files"
+#
+      mode="On"
+      $ECHO "DEBUG (${scriptName}): START download the ${mode} calib fits files"
+      inFileDirectory="./${mode}"
+      $MKDIR -p ${inFileDirectory}
+
+      listOfCalibCycle=( `ils ${i}/${mode} 2>&1 | $GREP -i "calibcycle" |$AWK 'BEGIN{FS="C- "}{print $2}' | $XARGS -i basename {} | $SORT -k1.11n` )
+      IFS='
+'
+      listOfCalibCycle=( $( $PRINTF "%s\n" "${listOfCalibCycle[@]}" | $AWK 'x[$0]++ == 0' ) )
+      IFS=$DefaultIFS
+
+      firstCycleOn=`$ECHO ${listOfCalibCycle[0]} | $AWK '{match($0,"[0-9]+",arr); print arr[0]}'`
+      nCyclesOn=`expr ${#listOfCalibCycle[*]} - 1`
+
+      lastCycleOn=`$ECHO ${listOfCalibCycle[${nCyclesOn}]} | $AWK '{match($0,"[0-9]+",arr); print arr[0]}'`
+
+      listOfCalibCycle=( "${listOfCalibCycle[@]/#/${i}/${mode}/}" )
+
+
+#
+#Check if there is the same number of cycles in Off and On mode
+#      
+#first cycle = max(firstCycleOn, firstCycleOff)
+#last  cycle = min(lastCycleOn,lastCycleOff)
+
+      if [ ${firstCycleOn} -eq ${firstCycleOff} -a ${lastCycleOn} -eq ${lastCycleOff} ]; then
+	  firstCycle=${firstCycleOff}
+	  lastCycle=${lastCycleOff}
+      else
+	  $ECHO "INFO (${scriptName}): missmatch between Off and On mode"
+	  $ECHO "${firstCycleOn} != ${firstCycleOff} OR ${lastCycleOn} != ${lastCycleOff}"
+	  firstCycle=${firstCycleOff}
+	  if [ ${firstCycleOn} -gt ${firstCycle} ]; then
+	      firstCycle=${firstCycleOn}
+	  fi
+	  lastCycle=${lastCycleOff}
+	  if [ ${lastCycleOn} -lt ${lastCycle} ]; then
+	      lastCycle=${lastCycleOn}
+	  fi
+      fi
+      $ECHO "INFO (${scriptName}): use cycles [${firstCycle}, ${lastCycle}]"
+      
+
+      for j in ${listOfCalibCycle[@]}
+	do
+	irodsDownDir="${j}"
+	OUT=./getInFits.$$
+	iget -r -f -K ${irodsDownDir} ${inFileDirectory} > ${OUT} 2>&1
+	igetStatus=`$GREP "^ERROR" ${OUT}`
+	if [ "<$igetStatus>" != "<>" ]; then
+	    $ECHO "FATAL (${scriptName}): error while iget fits files:"
+	    $ECHO $igetStatus
+	    $ECHO " ==> skip this run $sourceRadio $dateDAQ"
+	    continue
+	fi
+	$RM -f ${OUT}
+      done
+      $ECHO "DEBUG (${scriptName}): END download the ${mode} calib fits files"
+#Get sca file
+      $ECHO "DEBUG (${scriptName}): START call getscafiles.sh ${sourceRadio} ${dateDAQ}"
+      OUT1=./getScaStatus.$$
+      $RM -f ${tmppublicpath}/getscafiles.finished
+      ${scriptpath}/getscafiles.sh ${sourceRadio} ${dateDAQ} > ${OUT1} 2>&1
+      while [ ! -f "${tmppublicpath}/getscafiles.finished" ]; do
+	  $ECHO "INFO (${scriptName}): waiting for ${tmppublicpath}/getscafiles.finished"
+	  date +%T
+	  sleep 30
+      done
+      $RM ${tmppublicpath}/getscafiles.finished
+      $ECHO "DEBUG (${scriptName}): END"
+#
+      getScaStatus=`$GREP "^\(FATAL\|ERROR\)" ${OUT1}`
+#	
+      if [ "<${getScaStatus}>" != "<>" ]; then
+	  $ECHO "FATAL (${scriptName}): error to get sca file for $sourceRadio $dateDAQ"
+	  $ECHO "DEBUG (${scriptName}): START with cat ${OUT1}"
+	  $CAT ${OUT1}
+	  $ECHO "DEBUG (${scriptName}): END"
+	  continue
+      fi
+      $RM -f ${OUT1}
+
+      scaFile=`$FIND . -name "sca*.sum.trans" | $XARGS -i basename {}`
+      
+#prepare job submission
+      cd ${aboveOnOffDir}
+#the default spectra name is medfiltmtx, otherwise use -specname <a_string>
+
+      logFile="analyse_CALIB_${sourceRadio}_${dateDAQ}.log"
+      $ECHO "DEBUG (${scriptName}): execute the analysis... should not take long. `date`"
+      if [ ${simulationMode} = "On" ]; then
+	  $ECHO "SIMUL: ${scriptpath}/Objs/analyse -act calib -inPath ${iojobpath}  -source  ${sourceRadio} -date ${dateDAQ} -sca ${scaFile} -specdir calibcycle -numcycle ${firstCycle},${lastCycle} -calibopt mean  -debuglev 1 -freqBAOCalib ${freqBAOCalib} -bwBAOCalib ${bwBAOCalib} >& ${logFile}"
+	  cat > ${logFile} <<EOF
+	  Ok calibration finished
+EOF
+      else
+	  ${scriptpath}/Objs/analyse -act calib -inPath ${iojobpath}  -source  ${sourceRadio} -date ${dateDAQ} -sca ${scaFile} -specdir calibcycle  -numcycle ${firstCycle},${lastCycle} -calibopt mean  -debuglev 1 -freqBAOCalib ${freqBAOCalib} -bwBAOCalib ${bwBAOCalib} >& ${logFile}
+      fi
+      $ECHO "DEBUG (${scriptName}): analysis finished `date`. Look for errors before saving to Irods"
+      rcstatus=`$GREP -i "Ok calibration finished" ${logFile} | $WC -l`
+      if [ ${rcstatus} -eq 0 ]; then
+	  $ECHO "INFO (${scriptName}): analysis problem for ${sourceRadio} ${dateDAQ}"
+	  $ECHO "                      START logfile"
+	  $CAT ${logFile}
+	  $ECHO "                      END   logFile"
+#clean and leave
+	  cd ${aboveOnOffDir}
+	  $LS | $XARGS -i $RM -rf {}
+	  continue
+      fi
+#Save into Irods
+      $ECHO "DEBUG (${scriptName}): START save output files"
+      $LS ${aboveOnOffDir}
+#use -f option for iput ONLY to force override
+      if [ ${simulationMode} = "On" ]; then
+	  $ECHO "SIMUL: here we look for calib file and put them in Irods"
+      else
+	  $FIND . -name "calib_*" -print | $XARGS -i  iput  -v -K {} ${i}
+      fi
+#save analysis logfile
+      $LS -l ${tmppublicpath} > /dev/null
+      $CP ${logFile} ${tmppublicpath}
+      $ECHO "DEBUG (${scriptName}): END save output files"
+#clean up to avoid scratch SIZE EXCEED LIMIT
+      cd ${aboveOnOffDir}
+      $LS | $XARGS -i $RM -rf {}
+  fi
+done
+
+exit 0
Index: /BAORadio/AmasNancay/v5/etude_data.pic
===================================================================
--- /BAORadio/AmasNancay/v5/etude_data.pic	(revision 596)
+++ /BAORadio/AmasNancay/v5/etude_data.pic	(revision 596)
@@ -0,0 +1,227 @@
+echo ".... execute ON"
+exec analdata 20110416abell85 151300 On datacycle 1
+echo ".... execute OFF"
+exec analdata 20110416abell85 151300 Off datacycle 1
+
+echo ".... execute Merging"
+
+c++compile offset
+
+
+#
+#follow cycle to cycle variation of calibration coeff
+#
+vecfrascii calibOnCh0   20110416abell85-On-1346MHz-Ch0Cycles.txt
+vecfrascii calibOnCh1   20110416abell85-On-1346MHz-Ch1Cycles.txt
+vecfrascii calibOffCh0  20110416abell85-Off-1346MHz-Ch0Cycles.txt
+vecfrascii calibOffCh1  20110416abell85-Off-1346MHz-Ch1Cycles.txt
+
+del diff0
+del diff1
+
+set ncount 0
+set first 1
+
+for ic ${firstcycle}:${ncycles}
+  echo "...... cycle $ic"
+  ncount = $ncount + 1
+  k = ${ic} -1
+  del diffcycle${ic}v0 diffcycle${ic}v1
+  if ( $first == 1 ) then
+     set first 0
+     c++exec \
+        TVector<r_4> sigcalOnv0(sumc${ic}mOnv0,false); sigcalOnv0/=calibOnCh0[$k]; \
+        TVector<r_4> sigcalOnv1(sumc${ic}mOnv1,false); sigcalOnv1/=calibOnCh1[$k]; \
+        TVector<r_4> sigcalOffv0(sumc${ic}mOffv0,false); sigcalOffv0/=calibOffCh0[$k]; \
+        TVector<r_4> sigcalOffv1(sumc${ic}mOffv1,false); sigcalOffv1/=calibOffCh1[$k]; \
+        TVector<r_4> diffcycle${ic}v0 = sigcalOnv0-sigcalOffv0; \
+        TVector<r_4> diffcycle${ic}v1 = sigcalOnv1-sigcalOffv1; \
+	TVector<r_4> diff0(diffcycle${ic}v0,false); \
+	TVector<r_4> diff1(diffcycle${ic}v1,false); \
+        KeepObj(diff0);KeepObj(diff1); \
+	KeepObj(diffcycle${ic}v0); KeepObj(diffcycle${ic}v1);
+  else
+     c++exec \
+        TVector<r_4> sigcalOnv0(sumc${ic}mOnv0,false); sigcalOnv0/=calibOnCh0[$k]; \
+        TVector<r_4> sigcalOnv1(sumc${ic}mOnv1,false); sigcalOnv1/=calibOnCh1[$k]; \
+        TVector<r_4> sigcalOffv0(sumc${ic}mOffv0,false); sigcalOffv0/=calibOffCh0[$k]; \
+        TVector<r_4> sigcalOffv1(sumc${ic}mOffv1,false); sigcalOffv1/=calibOffCh1[$k]; \
+        TVector<r_4> diffcycle${ic}v0 = sigcalOnv0-sigcalOffv0; \
+        TVector<r_4> diffcycle${ic}v1 = sigcalOnv1-sigcalOffv1; \
+	diff0+=diffcycle${ic}v0; \
+	diff1+=diffcycle${ic}v1; \
+	KeepObj(diffcycle${ic}v0); KeepObj(diffcycle${ic}v1);
+  endif
+end
+
+
+newvec nmean 1 $ncount nodisp
+#coef RT @ 1346MHz Ouest - Est associees a Ch 0 et 1
+set xcal ( 27.724 22.543 )
+line2vec calib $xcal
+del difftot
+c++exec diff0/=nmean[0]; diff1/=nmean[0]; \
+        diff0*=calib[0];diff1*=calib[1]; \
+        TVector<r_4> difftot(diff0,false);difftot+=diff1;difftot/=2.; \
+        KeepObj(difftot);
+
+
+#
+#Calibrate and Offset Correction
+#
+for ic ${firstcycle}:${ncycles}
+  c++exec diffcycle${ic}v0*=calib[0];diffcycle${ic}v1*=calib[1]; 
+end
+
+del modiff0 moddiff1
+set first 1
+for ic ${firstcycle}:${ncycles}
+  echo "modif ...... cycle $ic"
+  
+  del inarr outarr  modiffc${ic}v0
+  cp  diffcycle${ic}v0 inarr
+  c++link offset.so meanoffset
+  call meanoffset 1285 1335 1355 1450
+  cp outarr modiffc${ic}v0
+
+  del inarr outarr modiffc${ic}v1
+  cp  diffcycle${ic}v1 inarr
+  c++link offset.so meanoffset
+  call meanoffset 1285 1335 1355 1450
+  cp outarr modiffc${ic}v1
+
+  if ( $first == 1 ) then
+     set first 0
+     c++exec \ 
+       TVector<r_4> modiff0(modiffc${ic}v0,false); \ 
+       TVector<r_4> modiff1(modiffc${ic}v1,false); \ 
+       KeepObj(modiff0);KeepObj(modiff1);
+  else
+     c++exec modiff0+=modiffc${ic}v0;  modiff1+=modiffc${ic}v1;
+  endif
+end  
+
+
+newwin 1 1
+setaxesatt $defatt
+graphicatt "$defatt xylimits=1250,1500,-1.,1."
+set first 1
+for ic ${firstcycle}:${ncycles}
+  echo "...... cycle $ic"
+  k = ${ic}-floor(${ic}/${#cols})*${#cols}
+  if ( $first == 1 ) then
+     set first 0
+     plot2d  diffcycle${ic}v0 (n/8192)*250+1250 val n>0 "$cols[k] cpts nsta notit"
+  else
+     plot2d  diffcycle${ic}v0 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+  endif
+end
+settitle "Diff. On-Off No Corr. $source Ch 0 cycles [$firstcycle,$lastcycle]"
+setaxelabels "Freq. (MHz)" "I (Jy)"
+
+
+newwin 1 1
+setaxesatt $defatt
+graphicatt "$defatt xylimits=1250,1500,-1.,1."
+set first 1
+for ic ${firstcycle}:${ncycles}
+  echo "...... cycle $ic"
+  k = ${ic}-floor(${ic}/${#cols})*${#cols}
+  if ( $first == 1 ) then
+     set first 0
+     plot2d  diffcycle${ic}v1 (n/8192)*250+1250 val n>0 "$cols[k] cpts nsta notit"
+  else
+     plot2d  diffcycle${ic}v1 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+  endif
+end
+settitle "Diff. On-Off No Corr. $source Ch 1 cycles [$firstcycle,$lastcycle]"
+setaxelabels "Freq. (MHz)" "I (Jy)"
+
+
+newwin 1 1
+setaxesatt $defatt
+graphicatt "$defatt xylimits=1250,1500,-50.,50."
+plot2d diff0  (n/8192)*250+1250 val*1000 n>0 "blue cpts nsta notit"
+plot2d diff1  (n/8192)*250+1250 val*1000 n>0 "red same cpts nsta notit"
+plot2d difftot  (n/8192)*250+1250 val*1000 n>0 "black same cpts nsta notit"
+settitle "Mean diff calib No Corr. per cycle ON-OFF Int.  $source cycles [$firstcycle,$lastcycle]"
+setaxelabels "Freq. (MHz)" "Int. (mJy)"
+
+newwin 1 1
+graphicatt "$defatt"
+n/plot difftot.val*1000 n>1090&&n<4000 ! ! "black  notit"
+n/plot diff0.val*1000 n>1090&&n<4000 ! ! "blue same notit"
+n/plot diff1.val*1000 n>1090&&n<4000 ! ! "red same notit"
+settitle "Diff ON-OFF No Corr. $source [$firstcycle,$lastcycle] 1280MHz - 1370MHz"
+setaxelabels "mJy" " "
+
+
+
+newwin 1 1
+setaxesatt $defatt
+graphicatt "$defatt xylimits=1250,1500,-1.,1."
+set first 1
+for ic ${firstcycle}:${ncycles}
+  echo "...... cycle $ic"
+  k = ${ic}-floor(${ic}/${#cols})*${#cols}
+  if ( $first == 1 ) then
+     set first 0
+     plot2d  modiffc${ic}v0 (n/8192)*250+1250 val n>0 "$cols[k] cpts nsta notit"
+  else
+     plot2d  modiffc${ic}v0 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+  endif
+end
+settitle "Diff. On-Off With Corr. $source Ch 0 cycles [$firstcycle,$lastcycle]"
+setaxelabels "Freq. (MHz)" "I (Jy)"
+
+newwin 1 1
+setaxesatt $defatt
+graphicatt "$defatt xylimits=1250,1500,-1.,1."
+set first 1
+for ic ${firstcycle}:${ncycles}
+  echo "...... cycle $ic"
+  k = ${ic}-floor(${ic}/${#cols})*${#cols}
+  if ( $first == 1 ) then
+     set first 0
+     plot2d  modiffc${ic}v1 (n/8192)*250+1250 val n>0 "$cols[k] cpts nsta notit"
+  else
+     plot2d  modiffc${ic}v1 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+  endif
+end
+settitle "Diff. On-Off With Corr. $source Ch 1 cycles [$firstcycle,$lastcycle]"
+setaxelabels "Freq. (MHz)" "I (Jy)"
+
+
+
+
+  
+del modifftot
+c++exec modiff0/=nmean[0]; modiff1/=nmean[0]; \
+        TVector<r_4> modifftot(modiff0,false);modifftot+=modiff1;modifftot/=2.; \
+        KeepObj(modifftot);
+
+newwin 1 1
+setaxesatt $defatt"
+graphicatt "$defatt xylimits=1250,1500,-50.,50."
+plot2d modiff0  (n/8192)*250+1250 val*1000 n>0 "blue cpts nsta notit"
+plot2d modiff1  (n/8192)*250+1250 val*1000 n>0 "red same cpts nsta notit"
+plot2d modifftot  (n/8192)*250+1250 val*1000 n>0 "black same cpts nsta notit"
+settitle "Mean diff ON-OFF With Corr.  $source cycles [$firstcycle,$lastcycle]"
+setaxelabels "Freq. (MHz)" "Int. (mJy)"
+
+newwin 1 1
+graphicatt "$defatt"
+n/plot modifftot.val*1000 n>1090&&n<4000 ! ! "black  notit"
+n/plot modiff0.val*1000 n>1090&&n<4000 ! ! "blue same notit"
+n/plot modiff1.val*1000 n>1090&&n<4000 ! ! "red same notit"
+settitle "Diff ON-OFF With Corr. $source [$firstcycle,$lastcycle] 1280MHz - 1370MHz"
+setaxelabels "mJy" " "
+
+
+newwin 1 1
+setaxesatt $defatt"
+graphicatt "$defatt xylimits=1250,1500,-50.,50."
+plot2d difftot  (n/8192)*250+1250 val*1000 n>0 "blue  cpts nsta notit"
+plot2d modifftot  (n/8192)*250+1250 val*1000 n>0 "red same  cpts nsta notit"
+settitle "Mean diff ON-OFF NO Corr (blue) With Corr (red)  $source cycles [$firstcycle,$lastcycle]"
+setaxelabels "Freq. (MHz)" "Int. (mJy)"
Index: /BAORadio/AmasNancay/v5/etude_gain.pic
===================================================================
--- /BAORadio/AmasNancay/v5/etude_gain.pic	(revision 596)
+++ /BAORadio/AmasNancay/v5/etude_gain.pic	(revision 596)
@@ -0,0 +1,49 @@
+set user "AST"
+set toppath "/sps/baoradio/AmasNancay/${user}"
+set source "Abell85"
+set srclower "abell85"
+set date   "20110812"
+set saveplot "1"
+
+####################################################
+# Gains
+####################################################
+newwin 1 1
+graphicatt "xylimits=1250,1500,0,0.008"
+
+openfits ${toppath}/${source}/${date}${srclower}/gain_${date}_${srclower}.fits
+del g0 g1
+objaoper gain_${date}_${srclower} row 0 g0
+objaoper gain_${date}_${srclower} row 1 g1
+plot2d g1 (n/8192)*250+1250 val n>0 "red cpts nsta notit"
+plot2d g0 (n/8192)*250+1250 val n>0 "same blue cpts nsta notit"
+settitle "Gain $source ${date} Ch 0 (blue) Ch 1 (red)"
+setaxelabels "Freq. (MHz)" "I (a.u)"
+if ( $saveplot == "1" ) then
+  echo "saving plot"
+  w2eps ${toppath}/${source}/eps/gain/gain_${date}_${srclower}.eps
+endif
+
+####################################################
+# Control of the gains
+####################################################
+newwin 1 1
+graphicatt "xylimits=0,25,0,0.006"
+del gainmoni gainmoni0 gainmoni1
+
+openppf ${toppath}/${source}/${date}${srclower}/gain_monitor_${date}_${srclower}.ppf
+#attention les "monitor" ont ete utilise a une epoque ou il n'y avait pas de
+#reordering...
+ls
+#plot2d monitor n val n>0 "black cpts nsta notit"
+plot2d gainmoni n val n>0 "black cpts nsta notit"
+plot2d gainmoni0 n val n>0 "same blue cpts nsta notit"
+plot2d gainmoni1 n val n>0 "same red cpts nsta notit"
+settitle "Gain monitor $source ${date} Ch 0 (blue) Ch 1 (red)"
+if ( $saveplot == "1" ) then
+#  w2eps ${toppath}/${source}/eps/gain/gain_monitor_${date}_${srclower}.eps
+endif
+
+del g0 g1 gainmoni gainmoni0 gainmoni1
+del gain_${date}_${srclower}
+ls
Index: /BAORadio/AmasNancay/v5/etude_mergeAna.pic
===================================================================
--- /BAORadio/AmasNancay/v5/etude_mergeAna.pic	(revision 596)
+++ /BAORadio/AmasNancay/v5/etude_mergeAna.pic	(revision 596)
@@ -0,0 +1,508 @@
+
+
+set source  $1
+set ncycles $2
+
+
+#set fcalib $3
+#set f1420low $4
+#set f1420high $5
+
+set fcalib 1410
+set f1420low 1420.2
+set f1420high 1420.6
+
+
+
+nbins1420 = floor((${f1420high}-${f1420low})/250*8192)
+
+echo $nbins1420
+
+
+clearscript diffOnOff
+clearscript evolAt1420Freq
+clearscript evolAt1420SideFreq
+clearscript IntAt1420
+clearscript sigmaRaw1420Side
+clearscript sigmaRaw1400a1420
+############################################################################
+defscript evolAtCalibFreq
+
+
+#Follow up of the intensity arround the Calib frequency in different calibration conditions
+# NO calibration
+# Calibration coeff. mean per Run
+# Calibration coeff. per cycles
+
+set fcalib $1
+
+
+newwin 1 2
+n/pl onoffevol.onoffRaw0%cycle ! ! "blue cpts notit nsta"
+settitle "Raw ON-OFF  ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles " ' ' $defatt
+n/pl onoffevol.onoffRaw1%cycle ! ! "red cpts notit nsta"
+setaxelabels "cycle" "I[${fcalib}MHz/6.25MHz] Raw (a.u)" $axedefatt
+
+newwin 1 2
+n/proj hRaw0 onoffevol.onoffRaw0 ! ! ! "blue cpts notit"
+settitle "Raw ON-OFF  ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles " ' ' $defatt
+n/proj hRaw1 onoffevol.onoffRaw1 ! ! ! "red cpts notit"
+settitle "I[${fcalib}MHz/6.25MHz] Raw (a.u)"
+
+
+	
+newwin 1 2
+n/pl onoffevol.onoffRun0%cycle ! ! "blue cpts notit nsta"
+settitle "ON-OFF Calib Run ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles" ' ' $defatt
+n/pl onoffevol.onoffRun1%cycle ! ! "red cpts notit nsta"
+setaxelabels "cycle" "I[${fcalib}MHz/6.25MHz] Run (a.u)" $axedefatt
+
+
+newwin 1 2
+n/proj hRun0 onoffevol.onoffRun0 ! ! ! "blue cpts notit"
+settitle "ON-OFF Calib Run ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles" ' ' $defatt
+n/proj hRun1 onoffevol.onoffRun1 ! ! ! "red cpts notit"
+settitle "I[${fcalib}MHz/6.25MHz] Run (a.u)"
+
+
+newwin 1 2
+n/pl onoffevol.onoffCycle0%cycle ! ! "blue cpts notit nsta"
+settitle "ON-OFF Calib Cycle ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles" ' ' $defatt
+n/pl onoffevol.onoffCycle1%cycle ! ! "red cpts notit nsta"
+setaxelabels "cycle" "I[${fcalib}MHz/6.25MHz] Cycle (a.u)" $axedefatt
+
+newwin 1 2
+n/proj hCycle0 onoffevol.onoffCycle0 ! ! ! "blue cpts notit"
+settitle "ON-OFF Calib Cycle ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles" ' ' $defatt
+n/proj hCycle1 onoffevol.onoffCycle1 ! ! ! "red cpts notit"
+settitle "I[${fcalib}MHz/6.25MHz] Cycle (a.u)"
+
+
+endscript
+###########################################
+defscript evolAt1420Freq
+
+
+#Follow up of the intensity arround the [1420,1421]MHz frequency in different calibration conditions
+# NO calibration
+# Calibration coeff. mean per Run
+# Calibration coeff. per cycles
+
+
+graphicatt "xylimits=0,500,-0.01,0.01"
+
+newwin 1 2
+n/pl onoffevol.onoffRaw01420%cycle ! ! "blue cpts notit nsta"
+settitle "Raw ON-OFF  ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles " ' ' $defatt
+n/pl onoffevol.onoffRaw11420%cycle ! ! "red cpts notit nsta"
+setaxelabels "cycle" "I[${f1420low},${f1420high}]MHz Raw (a.u)" $axedefatt
+
+
+newwin 1 2
+n/pl onoffevol.onoffRun01420%cycle ! ! "blue cpts notit nsta"
+settitle "ON-OFF Calib Run ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles" ' ' $defatt
+n/pl onoffevol.onoffRun11420%cycle ! ! "red cpts notit nsta"
+setaxelabels "cycle" "I[${f1420low},${f1420high}]MHz Run (a.u)" $axedefatt
+
+
+newwin 1 2
+n/pl onoffevol.onoffCycle01420%cycle ! ! "blue cpts notit nsta"
+settitle "ON-OFF Calib Cycle ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles" ' ' $defatt
+n/pl onoffevol.onoffCycle11420%cycle ! ! "red cpts notit nsta"
+setaxelabels "cycle" "I[${f1420low},${f1420high}]MHz Cycle (a.u)" $axedefatt
+
+
+newh1d hSigmaRaw0 -0.01 0.01 25
+newh1d hSigmaRaw1 -0.01 0.01 25
+newh1d hSigmaRun0 -0.01 0.01 25
+newh1d hSigmaRun1 -0.01 0.01 25
+newh1d hSigmaCycl0 -0.01 0.01 25
+newh1d hSigmaCycl1 -0.01 0.01 25
+
+graphicatt ""
+
+newwin 1 1
+n/proj hSigmaRaw0 onoffevol.onoffRaw01420 ! ! ! "blue cpts notit"
+n/proj hSigmaRaw1 onoffevol.onoffRaw11420 ! ! ! "same red cpts notit"
+settitle "Raw ON-OFF  ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles " ' ' $defatt
+setaxelabels "(a.u)" "I[${f1420low},${f1420high}]MHz Raw" $axedefatt
+
+newwin 1 1
+n/proj hSigmaRun0 onoffevol.onoffRun01420 ! ! ! "blue cpts notit"
+n/proj hSigmaRun1 onoffevol.onoffRun11420 ! ! ! "same red cpts notit"
+settitle "ON-OFF Calib Run ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles" ' ' $defatt
+setaxelabels "(a.u)" "I[${f1420low},${f1420high}]MHz Run" $axedefatt
+
+
+newwin 1 1
+n/proj hSigmaCycl0 onoffevol.onoffCycle01420 ! ! ! "blue cpts notit"
+n/proj hSigmaCycl1 onoffevol.onoffCycle11420 ! ! ! "same red cpts notit"
+settitle "ON-OFF Calib Cycle ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles" ' ' $defatt
+setaxelabels "(a.u)" "I[${f1420low},${f1420high}]MHz Cycle" $axedefatt
+
+
+endscript
+##################################################
+defscript sigmaRaw1420Side
+
+c++compile rebining
+c++link rebining.so dorebin
+
+
+#col 13 = onoffRaw01420side   Ch 0
+#col 14 = onoffRaw11420side   Ch 1
+
+ntcol2var onoffevol 13 linCh0All
+line2vec vecCh0All $linCh0All
+
+ntcol2var onoffevol 14 linCh1All
+line2vec vecCh1All $linCh1All
+
+#packing values only valid for 500 cycles...
+set packVal "1 10 25 50 100"
+set sigmaCh0 ""
+set errsigCh0 ""
+set sigmaCh1 ""
+set errsigCh1 ""
+
+
+foreach ipack ( $packVal )
+
+#Packing per ipack
+  del invec 
+  del outvec
+  cp vecCh0All invec
+  call dorebin $ipack
+  mean0 = ${outvec.sum}/${outvec.size}
+  sigma0 = sqrt(${outvec.sumsq}/${outvec.size}-${mean0}*${mean0})
+  errsig0 = ${sigma0}/sqrt(2*${outvec.size})	
+  set sigmaCh0 "${sigmaCh0} ${sigma0}"	
+  set errsigCh0 "${errsigCh0} ${errsig0}"	
+#
+  del invec
+  del outvec
+  cp vecCh1All invec
+  call dorebin $ipack
+  mean1 = ${outvec.sum}/${outvec.size}
+  sigma1 = sqrt(${outvec.sumsq}/${outvec.size}-${mean1}*${mean1})
+  errsig1 = ${sigma1}/sqrt(2*${outvec.size})	
+  set sigmaCh1 "${sigmaCh1} ${sigma1}"	
+  set errsigCh1 "${errsigCh1} ${errsig1}"
+end
+
+
+newnt nt0 x y ey
+newnt nt1 x y ey
+
+set x0 ( $packVal )
+set y0 ( $sigmaCh0 )
+set ey0 ( $errsigCh0 )
+
+set x1 ( $packVal )
+set y1 ( $sigmaCh1 )
+set ey1 ( $errsigCh1 )
+	
+for i 0:$#x0
+ line2nt nt0 $x0[i] $y0[i] $ey0[i]
+ line2nt nt1 $x1[i] $y1[i] $ey1[i]
+end
+
+
+newwin 1 1
+plot2de nt0 x y 0 ey 1 "blue marker=fcircle,9 notit nsta"     
+plot2de nt1 x y 0 ey 1 "same red  marker=fcircle,9 notit nsta"
+n = ${#x0}-1
+func $y0[0]/sqrt(x) $x0[0] $x0[n]  100 "same"
+settitle "Sigma [1418,1419]U[1422,1423]MHz ${source} Ch 0 (blue) Ch 1 (red)" ' ' $defatt
+setaxelabels "num of cycles" "Sigma (a.u)" $axedefatt
+
+
+
+endscript
+##################################################
+defscript sigmaRaw1400a1420
+
+c++compile rebining
+c++link rebining.so dorebin
+
+
+#col 19 = onoffRaw0f14001420   Ch 0
+#col 20 = onoffRaw1f14001420  Ch 1
+
+ntcol2var onoffevol 19 linCh0All
+line2vec vecCh0All $linCh0All
+
+ntcol2var onoffevol 20 linCh1All
+line2vec vecCh1All $linCh1All
+
+#packing values only valid for 500 cycles...
+set packVal "1 10 25 50 100"
+set sigmaCh0 ""
+set errsigCh0 ""
+set sigmaCh1 ""
+set errsigCh1 ""
+
+
+foreach ipack ( $packVal )
+
+#Packing per ipack
+  del invec 
+  del outvec
+  cp vecCh0All invec
+  call dorebin $ipack
+  mean0 = ${outvec.sum}/${outvec.size}
+  sigma0 = sqrt(${outvec.sumsq}/${outvec.size}-${mean0}*${mean0})
+  errsig0 = ${sigma0}/sqrt(2*${outvec.size})	
+  set sigmaCh0 "${sigmaCh0} ${sigma0}"	
+  set errsigCh0 "${errsigCh0} ${errsig0}"	
+#
+  del invec
+  del outvec
+  cp vecCh1All invec
+  call dorebin $ipack
+  mean1 = ${outvec.sum}/${outvec.size}
+  sigma1 = sqrt(${outvec.sumsq}/${outvec.size}-${mean1}*${mean1})
+  errsig1 = ${sigma1}/sqrt(2*${outvec.size})	
+  set sigmaCh1 "${sigmaCh1} ${sigma1}"	
+  set errsigCh1 "${errsigCh1} ${errsig1}"
+end
+
+
+newnt nt0 x y ey
+newnt nt1 x y ey
+
+set x0 ( $packVal )
+set y0 ( $sigmaCh0 )
+set ey0 ( $errsigCh0 )
+
+set x1 ( $packVal )
+set y1 ( $sigmaCh1 )
+set ey1 ( $errsigCh1 )
+	
+for i 0:$#x0
+ line2nt nt0 $x0[i] $y0[i] $ey0[i]
+ line2nt nt1 $x1[i] $y1[i] $ey1[i]
+end
+
+
+newwin 1 1
+plot2de nt0 x y 0 ey 1 "blue marker=fcircle,9 notit nsta"     
+plot2de nt1 x y 0 ey 1 "same red  marker=fcircle,9 notit nsta"
+n = ${#x0}-1
+func $y0[0]/sqrt(x) $x0[0] $x0[n]  100 "same"
+settitle "Sigma [1400,1420]MHz ${source} Ch 0 (blue) Ch 1 (red)" ' ' $defatt
+setaxelabels "num of cycles" "Sigma (a.u)" $axedefatt
+
+
+
+endscript
+###########################################
+
+defscript evolAt1420SideFreq
+
+
+#Follow up of the intensity arround the [${f1420low},${f1420high}]MHz frequency in different calibration conditions
+# NO calibration
+# Calibration coeff. mean per Run
+# Calibration coeff. per cycles
+
+
+graphicatt "xylimits=0,500,-0.01,0.01"
+
+newwin 1 2
+n/pl onoffevol.onoffRaw01420side%cycle ! ! "blue cpts notit nsta"
+settitle "Raw ON-OFF  ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles " ' ' $defatt
+n/pl onoffevol.onoffRaw11420side%cycle ! ! "red cpts notit nsta"
+setaxelabels "cycle" "I[1418,1419]U[1422,1423]MHz Raw (a.u)" $axedefatt
+
+
+newwin 1 2
+n/pl onoffevol.onoffRun01420side%cycle ! ! "blue cpts notit nsta"
+settitle "ON-OFF Calib Run ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles" ' ' $defatt
+n/pl onoffevol.onoffRun11420side%cycle ! ! "red cpts notit nsta"
+setaxelabels "cycle" "I[1418,1419]U[1422,1423]MHz Run (a.u)" $axedefatt
+
+
+newwin 1 2
+n/pl onoffevol.onoffCycle01420side%cycle ! ! "blue cpts notit nsta"
+settitle "ON-OFF Calib Cycle ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles" ' ' $defatt
+n/pl onoffevol.onoffCycle11420side%cycle ! ! "red cpts notit nsta"
+setaxelabels "cycle" "I[1418,1419]U[1422,1423]MHz Cycle (a.u)" $axedefatt
+
+
+newh1d hSigmaSideRaw0 -0.01 0.01 25
+newh1d hSigmaSideRaw1 -0.01 0.01 25
+newh1d hSigmaSideRun0 -0.01 0.01 25
+newh1d hSigmaSideRun1 -0.01 0.01 25
+newh1d hSigmaSideCycl0 -0.01 0.01 25
+newh1d hSigmaSideCycl1 -0.01 0.01 25
+
+graphicatt ""
+
+newwin 1 1
+n/proj hSigmaSideRaw0 onoffevol.onoffRaw01420side ! ! ! "blue cpts notit"
+n/proj hSigmaSideRaw1 onoffevol.onoffRaw11420side ! ! ! "same red cpts notit"
+settitle "Raw ON-OFF  ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles " ' ' $defatt
+setaxelabels "(a.u)" "I[1418,1419]U[1422,1423]MHz Raw" $axedefatt
+
+newwin 1 1
+n/proj hSigmaSideRun0 onoffevol.onoffRun01420side ! ! ! "blue cpts notit"
+n/proj hSigmaSideRun1 onoffevol.onoffRun11420side ! ! ! "same red cpts notit"
+settitle "ON-OFF Calib Run ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles" ' ' $defatt
+setaxelabels "(a.u)" "I[1418,1419]U[1422,1423]MHz Run" $axedefatt
+
+
+newwin 1 1
+n/proj hSigmaSideCycl0 onoffevol.onoffCycle01420side ! ! ! "blue cpts notit"
+n/proj hSigmaSideCycl1 onoffevol.onoffCycle11420side ! ! ! "same red cpts notit"
+settitle "ON-OFF Calib Cycle ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles" ' ' $defatt
+setaxelabels "(a.u)" "I[1418,1419]U[1422,1423]MHz Cycle" $axedefatt
+
+
+endscript
+
+###########################################
+defscript IntAt1420
+
+
+#Follow up of the intensity arround the [${f1420low},${f1420high}]MHz 
+#frequency in different calibration conditions with baseline removed
+# NO calibration
+# Calibration coeff. mean per Run
+# Calibration coeff. per cycles
+
+
+graphicatt "xylimits=0,500,-0.1,0.1"
+
+newwin 1 2
+n/pl onoffevol.${nbins1420}*(onoffRaw01420-onoffRaw01420side)%cycle ! ! "blue cpts notit nsta"
+settitle "Raw ON-OFF  ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles " ' ' $defatt
+n/pl onoffevol.${nbins1420}*(onoffRaw11420-onoffRaw11420side)%cycle ! ! "red cpts notit nsta"
+setaxelabels "cycle" "I 1420MHz Raw (a.u)" $axedefatt
+
+
+newwin 1 2
+n/pl onoffevol.${nbins1420}*(onoffRun01420-onoffRun01420side)%cycle ! ! "blue cpts notit nsta"
+settitle "ON-OFF Calib Run ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles" ' ' $defatt
+n/pl onoffevol.${nbins1420}*(onoffRun11420-onoffRun11420side)%cycle ! ! "red cpts notit nsta"
+setaxelabels "cycle" "I 1420MHz Run (a.u)" $axedefatt
+
+
+newwin 1 2
+n/pl onoffevol.${nbins1420}*(onoffCycle01420-onoffCycle01420side)%cycle ! ! "blue cpts notit nsta"
+settitle "ON-OFF Calib Cycle ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles" ' ' $defatt
+n/pl onoffevol.${nbins1420}*(onoffCycle11420-onoffCycle11420side)%cycle ! ! "red cpts notit nsta"
+setaxelabels "cycle" "I 1420MHz Cycle (a.u)" $axedefatt
+
+
+newh1d h1420IntRaw0 -0.1 0.1 25
+newh1d h1420IntRaw1 -0.1 0.1 25
+newh1d h1420IntRun0 -0.1 0.1 25
+newh1d h1420IntRun1 -0.1 0.1 25
+newh1d h1420IntCycl0 -0.1 0.1 25
+newh1d h1420IntCycl1 -0.1 0.1 25
+
+graphicatt ""
+
+newwin 1 1
+n/proj h1420IntRaw0 onoffevol.${nbins1420}*(onoffRaw01420-onoffRaw01420side) ! ! ! "blue cpts notit"
+n/proj h1420IntRaw1 onoffevol.${nbins1420}*(onoffRaw11420-onoffRaw11420side) ! ! ! "same red cpts notit"
+settitle "Raw ON-OFF  ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles " ' ' $defatt
+setaxelabels "(a.u)" "I 1420MHz Raw" $axedefatt
+
+newwin 1 1
+n/proj h1420IntRun0 onoffevol.${nbins1420}*(onoffRun01420-onoffRun01420side) ! ! ! "blue cpts notit"
+n/proj h1420IntRun1 onoffevol.${nbins1420}*(onoffRun11420-onoffRun11420side) ! ! ! "same red cpts notit"
+settitle "ON-OFF Calib Run ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles" ' ' $defatt
+setaxelabels "(a.u)" "I 1420MHz Run" $axedefatt
+
+
+
+newwin 1 1
+n/proj h1420IntCycl0 onoffevol.${nbins1420}*(onoffCycle01420-onoffCycle01420side) ! ! ! "blue cpts notit"
+n/proj h1420IntCycl1 onoffevol.${nbins1420}*(onoffCycle11420-onoffCycle11420side) ! ! ! "same red cpts notit"
+settitle "ON-OFF Calib Cycle ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles" ' ' $defatt
+setaxelabels "(a.u)" "I 1420MHz Cycle" $axedefatt
+
+
+
+endscript
+##################################################
+defscript diffOnOff
+
+#
+#Display the ON-OFF over the whole freq. range in diffrent Calib. conditions
+# NO calibration
+# Calibration coeff. mean per Run
+# Calibration coeff. per cycles
+#
+
+graphicatt "xylimits=1250,1500,-0.01,0.01"
+del sonoffovoff0 sonoffovoff1
+objaoper meanOvOffNoCalib row 0 sonoffovoff0
+objaoper meanOvOffNoCalib row 1 sonoffovoff1
+newwin 1 1
+plot2d sonoffovoff0 (n/8192)*250+1250 val n>0 "blue cpts notit nsta"
+plot2d sonoffovoff1 (n/8192)*250+1250 val n>0 "red same cpts notit nsta"
+settitle "Raw (ON-OFF)/OFF  ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles" ' ' $defatt
+setaxelabels "Freq. (MHz)" "I (a.u)" $axedefatt
+
+
+
+graphicatt "xylimits=1250,1500,-0.01,0.01"
+del snocal0 snocal1
+objaoper meanNoCalib row 0 snocal0
+objaoper meanNoCalib row 1 snocal1
+newwin 1 1
+plot2d snocal0 (n/8192)*250+1250 val n>0 "blue cpts notit nsta"
+plot2d snocal1 (n/8192)*250+1250 val n>0 "red same cpts notit nsta"
+settitle "Raw ON-OFF  ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles" ' ' $defatt
+setaxelabels "Freq. (MHz)" "I (a.u)" $axedefatt
+
+del sruncal0 sruncal1
+objaoper meanPerRunCalib row 0 sruncal0
+objaoper meanPerRunCalib row 1 sruncal1
+newwin 1 1
+plot2d sruncal0 (n/8192)*250+1250 val n>0 "blue cpts notit nsta"
+plot2d sruncal1 (n/8192)*250+1250 val n>0 "red same cpts notit nsta"
+settitle "ON-OFF Calib Run  ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles" ' ' $defatt
+setaxelabels "Freq. (MHz)" "I (a.u)" $axedefatt
+
+newwin 1 1
+del scyclecal0 scyclecal1
+objaoper meanPerCycleCalib row 0 scyclecal0
+objaoper meanPerCycleCalib row 1 scyclecal1
+plot2d scyclecal0 (n/8192)*250+1250 val n>0 "blue cpts notit nsta"
+plot2d scyclecal1 (n/8192)*250+1250 val n>0 "red same cpts notit nsta"
+settitle "ON-OFF Calib Cycle  ${source} Ch 0 (blue) Ch 1 (red) ${ncycles}cycles" ' ' $defatt
+setaxelabels "Freq. (MHz)" "I (a.u)" $axedefatt
+
+
+endscript
+
+
+
+
+#Main
+#use minuscule for source label
+
+
+
+
+openppf onoffsurvey_${source}-${ncycles}Cycles.ppf
+print onoffevol
+
+set defatt "font=helvetica,bold,20 fixedfonsize"
+set axedefatt  "font=helvetica,bold,30 fixedfonsize grid"
+
+set defatt ""
+set axedefatt  "grid"
+
+graphicatt ""
+setaxesatt "$axedefatt"
+
+
+#diffOnOff
+#evolAt1420Freq
+#evolAt1420SideFreq
+#IntAt1420
Index: /BAORadio/AmasNancay/v5/etude_onoff.pic
===================================================================
--- /BAORadio/AmasNancay/v5/etude_onoff.pic	(revision 596)
+++ /BAORadio/AmasNancay/v5/etude_onoff.pic	(revision 596)
@@ -0,0 +1,317 @@
+
+set cols ( blue red black green purple orange cyan violet yellow )
+
+set toppath "/sps/baoradio/AmasNancay/JEC"
+set source "Abell${1}"
+set srclower "abell${1}"
+set date   "${2}"
+
+
+#####################################
+#Plots ON-OFF with all calibrations 
+#####################################
+openppf ${toppath}/${source}/diffOnOff_${date}_${srclower}.ppf
+
+
+#specONOFF<i>       Matrix 2 x 8192 : i=0...
+#specONOFFMean      Matrix 2 x 8192
+#specONOFF2ChanMean Vector 8192 x 1
+
+
+#####################################
+#Plots with different Means: per channel and all 
+#####################################
+del sallcyclev0
+objaoper specONOFFMean row 0 sallcyclev0
+del sallcyclev1
+objaoper specONOFFMean row 1 sallcyclev1
+
+newwin 1 1
+graphicatt "xylimits=1250,1500,-0.5,0.5"
+plot2d specONOFF2ChanMean (n/8192)*250+1250 val n>0 "black cpts nsta notit"
+plot2d sallcyclev0        (n/8192)*250+1250 val n>0 "same blue cpts nsta notit"
+plot2d sallcyclev1        (n/8192)*250+1250 val n>0 "same red cpts nsta notit"
+settitle "ON-OFF  ${source}/${date} Ch 0 (blue) Ch 1 (red) Mean (black)  All cycles"
+setaxelabels "Freq. (MHz)" "I (Jy)"
+
+#####################################
+#Examine fluctuations sigma for the combination of all cycles
+#####################################
+cp sallcyclev0 specv0
+cp sallcyclev1 specv1
+c++compile reducing        
+c++link reducing.so doreduc
+call doreduc
+
+newwin 1 1
+graphicatt "xylimits=1250,1500,-0.01,0.01"
+ del redMeanv0                                                                      
+ del redMeanv1                                                                      
+ objaoper reducedMeanDiffOnOff row 0 redMeanv0                                      
+ objaoper reducedMeanDiffOnOff row 1 redMeanv1                                      
+ plot2d redMeanv0 (n/32)*250+1250 val n>0 "blue marker=fcircle,7 nsta notit"        
+ plot2d redMeanv1 (n/32)*250+1250 val n>0 "same red marker=fcircle,7 nsta notit"
+settitle "Red Mean ON-OFF  ${source} Ch 0 (blue) Ch 1 (red) ${tmpvec.sum} cycles"
+setaxelabels "Freq. (MHz)" "I (Jy)"
+
+newwin 1 1
+graphicatt "xylimits=1250,1500,0,0.001"
+ del redSigmav0                                                                      
+ del redSigmav1                                                                      
+ objaoper reducedSigmaDiffOnOff row 0 redSigmav0                                      
+ objaoper reducedSigmaDiffOnOff row 1 redSigmav1                                      
+ plot2d redSigmav0 (n/32)*250+1250 val n>0 "blue marker=fcircle,7 nsta notit"        
+ plot2d redSigmav1 (n/32)*250+1250 val n>0 "same red marker=fcircle,7 nsta notit"
+settitle "ON-OFF  ${source} Ch 0 (blue) Ch 1 (red) ${tmpvec.sum} cycles"
+setaxelabels "Freq. (MHz)" "I (Jy)"
+
+
+#####################################
+#Plots ON-OFF with all calibrations: chan 0 & 1 separaed and cycle per cycle 
+#####################################
+newwin 1 1
+graphicatt "xylimits=1250,1500,-0.5,0.5"
+del sc1v0
+objaoper specONOFF1 row 0 sc1v0
+plot2d sc1v0 (n/8192)*250+1250 val n>0 "$cols[0] cpts nsta notit"
+for ic 2:13
+    k = ${ic}-floor(${ic}/${#cols})*${#cols}
+    del sc${ic}v0
+    objaoper specONOFF${ic} row 0 sc${ic}v0	
+    plot2d sc${ic}v0 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+end
+settitle "ON-OFF  ${source}/${date} Ch 0 cycle per cycle"
+setaxelabels "Freq. (MHz)" "I (Jy)"
+
+newwin 1 1
+graphicatt "xylimits=1250,1500,-0.5,0.5"
+del sc1v1
+objaoper specONOFF1 row 1 sc1v1
+plot2d sc1v1 (n/8192)*250+1250 val n>0 "$cols[0] cpts nsta notit"
+for ic 2:13
+    k = ${ic}-floor(${ic}/${#cols})*${#cols}
+    del sc${ic}v1
+    objaoper specONOFF${ic} row 1 sc${ic}v1	
+    plot2d sc${ic}v1 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+end
+settitle "ON-OFF  ${source}/${date} Ch 1 cycle per cycle"
+setaxelabels "Freq. (MHz)" "I (Jy)"
+
+
+#####################################
+# Plots RAW no calibration at all
+#####################################
+openppf ${toppath}/${source}/dataRaw_${date}_${srclower}.ppf
+newwin 2 2
+graphicatt "xylimits=1250,1500,0.95,1.05"
+
+###         #
+### On Ch 0 # On Ch 1 
+######################
+### Off Ch 0# Off Ch 1
+###         #
+
+set mode On	
+set first 1
+for ic 1:13
+  k = ${ic}-floor(${ic}/${#cols})*${#cols}	
+    del sm${mode}c${ic}v0
+    objaoper specRaw${mode}${ic} row 0 sm${mode}c${ic}v0
+    if ( ${first} == 1 ) then
+      plot2d sm${mode}c${ic}v0 (n/8192)*250+1250 val n>0 "$cols[k] cpts nsta notit"
+    else
+      plot2d sm${mode}c${ic}v0 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+    endif
+  set first 0
+end
+settitle "${source}/${date} Raw: On Ch 0"
+
+set first 1
+for ic 1:13
+  k = ${ic}-floor(${ic}/${#cols})*${#cols}	
+    del sm${mode}c${ic}v1
+    objaoper specRaw${mode}${ic} row 1 sm${mode}c${ic}v1
+    if ( ${first} == 1 ) then
+      plot2d sm${mode}c${ic}v1 (n/8192)*250+1250 val n>0 "$cols[k] cpts nsta notit"
+    else
+      plot2d sm${mode}c${ic}v1 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+    endif
+  set first 0
+end
+settitle "${source}/${date} Raw: On Ch 1"
+
+set mode Off
+set first 1
+for ic 1:13
+  k = ${ic}-floor(${ic}/${#cols})*${#cols}	
+    del sm${mode}c${ic}v0
+    objaoper specRaw${mode}${ic} row 0 sm${mode}c${ic}v0
+    if ( ${first} == 1 ) then
+      plot2d sm${mode}c${ic}v0 (n/8192)*250+1250 val n>0 "$cols[k] cpts nsta notit"
+    else
+      plot2d sm${mode}c${ic}v0 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+    endif
+  set first 0
+end
+settitle "${source}/${date} Raw: Off Ch 0"
+
+set first 1
+for ic 1:13
+  k = ${ic}-floor(${ic}/${#cols})*${#cols}	
+    del sm${mode}c${ic}v1
+    objaoper specRaw${mode}${ic} row 1 sm${mode}c${ic}v1
+    if ( ${first} == 1 ) then
+      plot2d sm${mode}c${ic}v1 (n/8192)*250+1250 val n>0 "$cols[k] cpts nsta notit"
+    else
+      plot2d sm${mode}c${ic}v1 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+    endif
+  set first 0
+end
+settitle "${source}/${date} Raw: Off Ch 1"
+
+#####################################
+# Plots BAO calibration included
+#####################################
+openppf ${toppath}/${source}/dataBAOCalib_${date}_${srclower}.ppf
+newwin 2 2
+#graphicatt "xylimits=1250,1500,0.95,1.05"
+graphicatt ""
+
+
+###         #
+### On Ch 0 # On Ch 1 
+######################
+### Off Ch 0# Off Ch 1
+###         #
+
+set mode On	
+set first 1
+for ic 1:13
+  k = ${ic}-floor(${ic}/${#cols})*${#cols}	
+    del sm${mode}c${ic}v0
+    objaoper specBAOCalib${mode}${ic} row 0 sm${mode}c${ic}v0
+    if ( ${first} == 1 ) then
+      plot2d sm${mode}c${ic}v0 (n/8192)*250+1250 val n>0 "$cols[k] cpts nsta notit"
+    else
+      plot2d sm${mode}c${ic}v0 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+    endif
+  set first 0
+end
+settitle "${source}/${date} BAOCalib: On Ch 0"
+
+set first 1
+for ic 1:13
+  k = ${ic}-floor(${ic}/${#cols})*${#cols}	
+    del sm${mode}c${ic}v1
+    objaoper specBAOCalib${mode}${ic} row 1 sm${mode}c${ic}v1
+    if ( ${first} == 1 ) then
+      plot2d sm${mode}c${ic}v1 (n/8192)*250+1250 val n>0 "$cols[k] cpts nsta notit"
+    else
+      plot2d sm${mode}c${ic}v1 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+    endif
+  set first 0
+end
+settitle "${source}/${date} BAOCalib: On Ch 1"
+
+set mode Off
+set first 1
+for ic 1:13
+  k = ${ic}-floor(${ic}/${#cols})*${#cols}	
+    del sm${mode}c${ic}v0
+    objaoper specBAOCalib${mode}${ic} row 0 sm${mode}c${ic}v0
+    if ( ${first} == 1 ) then
+      plot2d sm${mode}c${ic}v0 (n/8192)*250+1250 val n>0 "$cols[k] cpts nsta notit"
+    else
+      plot2d sm${mode}c${ic}v0 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+    endif
+  set first 0
+end
+settitle "${source}/${date} BAOCalib: Off Ch 0"
+
+set first 1
+for ic 1:13
+  k = ${ic}-floor(${ic}/${#cols})*${#cols}	
+    del sm${mode}c${ic}v1
+    objaoper specBAOCalib${mode}${ic} row 1 sm${mode}c${ic}v1
+    if ( ${first} == 1 ) then
+      plot2d sm${mode}c${ic}v1 (n/8192)*250+1250 val n>0 "$cols[k] cpts nsta notit"
+    else
+      plot2d sm${mode}c${ic}v1 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+    endif
+  set first 0
+end
+settitle "${source}/${date} BAOCalib: Off Ch 1"
+
+#####################################
+# Plots BAO+RT calibration included
+#####################################
+openppf ${toppath}/${source}/dataBAORTCalib_${date}_${srclower}.ppf
+newwin 2 2
+#graphicatt "xylimits=1250,1500,0.95,1.05"
+graphicatt ""
+
+
+###         #
+### On Ch 0 # On Ch 1 
+######################
+### Off Ch 0# Off Ch 1
+###         #
+
+set mode On	
+set first 1
+for ic 1:13
+  k = ${ic}-floor(${ic}/${#cols})*${#cols}	
+    del sm${mode}c${ic}v0
+    objaoper specBAORTCalib${mode}${ic} row 0 sm${mode}c${ic}v0
+    if ( ${first} == 1 ) then
+      plot2d sm${mode}c${ic}v0 (n/8192)*250+1250 val n>0 "$cols[k] cpts nsta notit"
+    else
+      plot2d sm${mode}c${ic}v0 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+    endif
+  set first 0
+end
+settitle "${source}/${date} BAORTCalib: On Ch 0"
+
+set first 1
+for ic 1:13
+  k = ${ic}-floor(${ic}/${#cols})*${#cols}	
+    del sm${mode}c${ic}v1
+    objaoper specBAORTCalib${mode}${ic} row 1 sm${mode}c${ic}v1
+    if ( ${first} == 1 ) then
+      plot2d sm${mode}c${ic}v1 (n/8192)*250+1250 val n>0 "$cols[k] cpts nsta notit"
+    else
+      plot2d sm${mode}c${ic}v1 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+    endif
+  set first 0
+end
+settitle "${source}/${date} BAORTCalib: On Ch 1"
+
+set mode Off
+set first 1
+for ic 1:13
+  k = ${ic}-floor(${ic}/${#cols})*${#cols}	
+    del sm${mode}c${ic}v0
+    objaoper specBAORTCalib${mode}${ic} row 0 sm${mode}c${ic}v0
+    if ( ${first} == 1 ) then
+      plot2d sm${mode}c${ic}v0 (n/8192)*250+1250 val n>0 "$cols[k] cpts nsta notit"
+    else
+      plot2d sm${mode}c${ic}v0 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+    endif
+  set first 0
+end
+settitle "${source}/${date} BAORTCalib: Off Ch 0"
+
+set first 1
+for ic 1:13
+  k = ${ic}-floor(${ic}/${#cols})*${#cols}	
+    del sm${mode}c${ic}v1
+    objaoper specBAORTCalib${mode}${ic} row 1 sm${mode}c${ic}v1
+    if ( ${first} == 1 ) then
+      plot2d sm${mode}c${ic}v1 (n/8192)*250+1250 val n>0 "$cols[k] cpts nsta notit"
+    else
+      plot2d sm${mode}c${ic}v1 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+    endif
+  set first 0
+end
+settitle "${source}/${date} BAORTCalib: Off Ch 1"
+
Index: /BAORadio/AmasNancay/v5/etude_rawonoff.pic
===================================================================
--- /BAORadio/AmasNancay/v5/etude_rawonoff.pic	(revision 596)
+++ /BAORadio/AmasNancay/v5/etude_rawonoff.pic	(revision 596)
@@ -0,0 +1,307 @@
+
+set cols ( blue red black green purple orange cyan violet yellow )
+
+set toppath "/sps/baoradio/AmasNancay/JEC"
+set source "Abell${1}"
+set srclower "abell${1}"
+set date   "${2}"
+# implicitement firstcycle =1
+set lastcycle $3
+lastP1cycle = ${lastcycle}+1
+
+echo Analyse ${source}/${data} from cycles 1-${lastcycle} (${lastP1cycle})
+
+pssetfilename rawonoff-${source}-${date}.ps
+
+
+
+
+#set showFigs ( 0 0 0 0 0 0 0 )
+
+
+
+#####################################
+#Plots RAW ON-OFF (RAW = WO calibrations) 
+#####################################
+openppf ${toppath}/${source}/${date}${srclower}/diffOnOffRaw_${date}_${srclower}.ppf
+
+
+#specONOFFRaw<i>       Matrix 2 x 8192 : i=0...
+#specONOFFRawMean      Matrix 2 x 8192
+#specONOFFRaw2ChanMean Vector 8192 x 1
+
+
+#####################################
+#Plots RAW ON-OFF with mean computed among the cycles AND(or NOT) the Channels
+#####################################
+
+#if ( $showFigs[0] == 1 ) then
+echo "Figure 1.........."
+
+del sallcyclev0
+objaoper specONOFFRawMean row 0 sallcyclev0
+del sallcyclev1
+objaoper specONOFFRawMean row 1 sallcyclev1
+
+newwin 1 1
+graphicatt "xylimits=1250,1500,-0.01,0.01"
+plot2d specONOFFRaw2ChanMean (n/8192)*250+1250 val n>0 "black cpts nsta notit"
+plot2d sallcyclev0        (n/8192)*250+1250 val n>0 "same blue cpts nsta notit"
+plot2d sallcyclev1        (n/8192)*250+1250 val n>0 "same red cpts nsta notit"
+settitle "ON-OFF  ${source}/${date} Ch 0 (blue) Ch 1 (red) Mean (black)  All cycles"
+setaxelabels "Freq. (MHz)" "I (a.u)"
+
+w2ps
+
+#endif
+
+#####################################
+#Plots RAW ON-OFF  chan 0 & 1 separaed and cycle per cycle 
+#####################################
+
+
+#if ( $showFigs[1] == 1 ) then
+echo "Figure 2.........."
+
+newwin 1 1
+graphicatt "xylimits=1250,1500,-0.01,0.01"
+del sc1v0
+objaoper specONOFFRaw1 row 0 sc1v0
+plot2d sc1v0 (n/8192)*250+1250 val n>0 "$cols[0] cpts nsta notit"
+for ic 2:${lastP1cycle}
+    k = ${ic}-floor(${ic}/${#cols})*${#cols}
+    del sc${ic}v0
+    objaoper specONOFFRaw${ic} row 0 sc${ic}v0	
+    plot2d sc${ic}v0 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+end
+settitle "ON-OFF  ${source}/${date} Ch 0 cycle per cycle"
+setaxelabels "Freq. (MHz)" "I (a.u)"
+w2ps
+
+
+
+newwin 1 1
+graphicatt "xylimits=1250,1500,-0.01,0.01"
+del sc1v1
+objaoper specONOFFRaw1 row 1 sc1v1
+plot2d sc1v1 (n/8192)*250+1250 val n>0 "$cols[0] cpts nsta notit"
+for ic 2:${lastP1cycle}
+    k = ${ic}-floor(${ic}/${#cols})*${#cols}
+    del sc${ic}v1
+    objaoper specONOFFRaw${ic} row 1 sc${ic}v1	
+    plot2d sc${ic}v1 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+end
+settitle "ON-OFF  ${source}/${date} Ch 1 cycle per cycle"
+setaxelabels "Freq. (MHz)" "I (a.u)"
+w2ps
+
+
+
+#endif
+
+#####################################
+# Plots RAW no calibration at all and no Diff ON-OFF
+#####################################
+openppf ${toppath}/${source}/${date}${srclower}/dataRaw_${date}_${srclower}.ppf
+
+#if ( $showFigs[2] == 1 ) then
+echo "Figure 3........."
+
+newwin 2 2
+graphicatt "xylimits=1250,1500,0.95,1.05"
+
+###         #
+### On Ch 0 # On Ch 1 
+######################
+### Off Ch 0# Off Ch 1
+###         #
+
+set mode On	
+set first 1
+for ic 1:${lastP1cycle}
+  k = ${ic}-floor(${ic}/${#cols})*${#cols}	
+    del sm${mode}c${ic}v0
+    objaoper specRaw${mode}${ic} row 0 sm${mode}c${ic}v0
+    if ( ${first} == 1 ) then
+      plot2d sm${mode}c${ic}v0 (n/8192)*250+1250 val n>0 "$cols[k] cpts nsta notit"
+    else
+      plot2d sm${mode}c${ic}v0 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+    endif
+  set first 0
+end
+settitle "${source}/${date} Raw: On Ch 0"
+
+set first 1
+for ic 1:${lastP1cycle}
+  k = ${ic}-floor(${ic}/${#cols})*${#cols}	
+    del sm${mode}c${ic}v1
+    objaoper specRaw${mode}${ic} row 1 sm${mode}c${ic}v1
+    if ( ${first} == 1 ) then
+      plot2d sm${mode}c${ic}v1 (n/8192)*250+1250 val n>0 "$cols[k] cpts nsta notit"
+    else
+      plot2d sm${mode}c${ic}v1 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+    endif
+  set first 0
+end
+settitle "${source}/${date} Raw: On Ch 1"
+
+set mode Off
+set first 1
+for ic 1:${lastP1cycle}
+  k = ${ic}-floor(${ic}/${#cols})*${#cols}	
+    del sm${mode}c${ic}v0
+    objaoper specRaw${mode}${ic} row 0 sm${mode}c${ic}v0
+    if ( ${first} == 1 ) then
+      plot2d sm${mode}c${ic}v0 (n/8192)*250+1250 val n>0 "$cols[k] cpts nsta notit"
+    else
+      plot2d sm${mode}c${ic}v0 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+    endif
+  set first 0
+end
+settitle "${source}/${date} Raw: Off Ch 0"
+
+set first 1
+for ic 1:${lastP1cycle}
+  k = ${ic}-floor(${ic}/${#cols})*${#cols}	
+    del sm${mode}c${ic}v1
+    objaoper specRaw${mode}${ic} row 1 sm${mode}c${ic}v1
+    if ( ${first} == 1 ) then
+      plot2d sm${mode}c${ic}v1 (n/8192)*250+1250 val n>0 "$cols[k] cpts nsta notit"
+    else
+      plot2d sm${mode}c${ic}v1 (n/8192)*250+1250 val n>0 "same $cols[k] cpts nsta notit"
+    endif
+  set first 0
+end
+settitle "${source}/${date} Raw: Off Ch 1"
+
+w2ps
+
+#endif
+
+#####################################
+#Plots RAW ON-OFF  MEAN REDUCED  chan 0 & 1 separaed and cycle per cycle 
+#####################################
+
+#if ( $showFigs[3] == 1 ) then
+echo "Figure 4.........."
+
+newwin 1 1
+graphicatt "xylimits=1250,1500,-0.01,0.01"
+del sc1v0
+objaoper redMeanONOFFRaw1 row 0 sc1v0
+plot2d sc1v0 (n/32)*250+1250 val n>0 "$cols[0] marker=fcircle,7  nsta notit"
+for ic 2:${lastP1cycle}
+    k = ${ic}-floor(${ic}/${#cols})*${#cols}
+    del sc${ic}v0
+    objaoper redMeanONOFFRaw${ic} row 0 sc${ic}v0	
+    plot2d sc${ic}v0 (n/32)*250+1250 val n>0 "same $cols[k] marker=fcircle,7 nsta notit"
+end
+settitle "ON-OFF Mean 32bins ${source}/${date} Ch 0 cycle per cycle"
+setaxelabels "Freq. (MHz)" "I (a.u)"
+w2ps
+
+
+newwin 1 1
+graphicatt "xylimits=1250,1500,-0.01,0.01"
+del sc1v1
+objaoper redMeanONOFFRaw1 row 1 sc1v1
+plot2d sc1v1 (n/32)*250+1250 val n>0 "$cols[0] marker=fcircle,7 nsta notit"
+for ic 2:${lastP1cycle}
+    k = ${ic}-floor(${ic}/${#cols})*${#cols}
+    del sc${ic}v1
+    objaoper redMeanONOFFRaw${ic} row 1 sc${ic}v1	
+    plot2d sc${ic}v1 (n/32)*250+1250 val n>0 "same $cols[k] marker=fcircle,7 nsta notit"
+end
+settitle "ON-OFF Mean 32bins ${source}/${date} Ch 1 cycle per cycle"
+setaxelabels "Freq. (MHz)" "I (a.u)"
+w2ps
+
+
+#endif
+
+#####################################
+#Plots RAW ON-OFF  SIGMA REDUCED  chan 0 & 1 separaed and cycle per cycle 
+#####################################
+
+
+#if ( $showFigs[4] == 1 ) then
+echo "Figure 5.........."
+
+newwin 1 1
+graphicatt "xylimits=1250,1500,0,0.01"
+del sc1v0
+objaoper redSigmaONOFFRaw1 row 0 sc1v0
+plot2d sc1v0 (n/32)*250+1250 val n>0 "$cols[0] marker=fcircle,7  nsta notit"
+for ic 2:${lastP1cycle}
+    k = ${ic}-floor(${ic}/${#cols})*${#cols}
+    del sc${ic}v0
+    objaoper redSigmaONOFFRaw${ic} row 0 sc${ic}v0	
+    plot2d sc${ic}v0 (n/32)*250+1250 val n>0 "same $cols[k] marker=fcircle,7 nsta notit"
+end
+settitle "ON-OFF Sigma over 32bins ${source}/${date} Ch 0 cycle per cycle"
+setaxelabels "Freq. (MHz)" "I (a.u)"
+w2ps
+
+newwin 1 1
+graphicatt "xylimits=1250,1500,0,0.01"
+del sc1v1
+objaoper redSigmaONOFFRaw1 row 1 sc1v1
+plot2d sc1v1 (n/32)*250+1250 val n>0 "$cols[0] marker=fcircle,7 nsta notit"
+for ic 2:${lastP1cycle}
+    k = ${ic}-floor(${ic}/${#cols})*${#cols}
+    del sc${ic}v1
+    objaoper redSigmaONOFFRaw${ic} row 1 sc${ic}v1	
+    plot2d sc${ic}v1 (n/32)*250+1250 val n>0 "same $cols[k] marker=fcircle,7 nsta notit"
+end
+settitle "ON-OFF Sigma over 32bins ${source}/${date} Ch 1 cycle per cycle"
+setaxelabels "Freq. (MHz)" "I (a.u)"
+w2ps
+
+#endif
+
+#####################################
+#Plots RAW ON-OFF  MEAN REDUCED  chan 0 & 1 separaed ALL cycles 
+#####################################
+
+#if ( $showFigs[5] == 1 ) then
+echo "Figure 6.........."
+
+newwin 1 1
+graphicatt "xylimits=1250,1500,-0.01,0.01"
+del scallv0
+del scallv1
+
+objaoper redMeanONOFFRawAll row 0 scallv0
+objaoper redMeanONOFFRawAll row 1 scallv1
+plot2d scallv0 (n/32)*250+1250 val n>0 "blue marker=fcircle,7  nsta notit"
+plot2d scallv1 (n/32)*250+1250 val n>0 "red same marker=fcircle,7  nsta notit"
+settitle "ON-OFF Mean 32bins ${source}/${date} Ch 0 (blue) Ch 1 (red) All cycles"
+setaxelabels "Freq. (MHz)" "I (a.u)"
+w2ps
+
+#endif
+
+#####################################
+#Plots RAW ON-OFF  SIGMA REDUCED  chan 0 & 1 separaed and cycle per cycle 
+#####################################
+
+
+#if ( $showFigs[5] == 1 ) then
+echo "Figure 6.........."
+
+newwin 1 1
+graphicatt "xylimits=1250,1500,0,0.001"
+del scallv0
+del scallv1
+objaoper redSigmaONOFFRawAll row 0 scallv0
+objaoper redSigmaONOFFRawAll row 1 scallv1
+plot2d scallv0 (n/32)*250+1250 val n>0 "blue marker=fcircle,7  nsta notit"
+plot2d scallv1 (n/32)*250+1250 val n>0 "red same marker=fcircle,7  nsta notit"
+settitle "ON-OFF Sigma over 32bins ${source}/${date} Ch 0 (blue) Ch 1 (red) All cycles"
+setaxelabels "Freq. (MHz)" "I (a.u)"
+w2ps
+
+#endif
+
+######################
+psclosefile
Index: /BAORadio/AmasNancay/v5/gainmaker.sh
===================================================================
--- /BAORadio/AmasNancay/v5/gainmaker.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/gainmaker.sh	(revision 596)
@@ -0,0 +1,296 @@
+#!/bin/sh -xvf
+#download SCA file, proceed to introspection, and upload results
+DATE=/bin/date
+GREP=/bin/grep
+AWK=/bin/awk
+ECHO=/bin/echo
+WC=/usr/bin/wc
+CAT=/bin/cat
+PRINTF=/usr/bin/printf
+FIND=/usr/bin/find
+MKDIR=/bin/mkdir
+XARGS=/usr/bin/xargs
+SORT=/bin/sort
+RM=/bin/rm
+TR=/usr/bin/tr
+CP=/bin/cp
+LS=/bin/ls
+CHMOD=/bin/chmod
+
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+#set Irods environment    
+. /usr/local/shared/bin/irods_env.sh -noverbose
+
+scriptName="`basename $0`"
+#$ECHO "Processing script ${scriptName} at `date`"
+
+#$ECHO "SHOULD BE RETUNED FOR THE inPath cmd line of analyse.cc (Sorry...): 21/7/11 by JEC"
+#exit 1
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=Off
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -src)  sourceRadio=$2; shift;;
+      -sim) simulationMode=On;;
+	-h)
+	    echo >&2 \
+	    "usage: $0 -src souce [-sim]"
+	    exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+if [ ${simulationMode} = "On" ]; then
+    $ECHO "INFO ${scriptName} running in SIMUL mode"
+fi
+
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+case ${sourceRadio} in
+    Abell85) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    Abell2440) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    Abell1205) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    *) ECHO "FATAL (${scriptName}): process ${sourceRadio} not yet foreseen"
+    exit 1;;
+esac
+
+
+srclower=`${ECHO} ${sourceRadio} | ${TR} "[:upper:]" "[:lower:]" `
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+$LS -l ${tmppublicpath} > /dev/null
+
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/isInteractive.sh
+isInteractive=$(isInteractive)
+if [ ${isInteractive} == "1" ]; then
+  $ECHO "Usage in INTERACTIVE may be destructive... To be used with great care !!!!"
+   exit 0;
+fi
+
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+localpath="${sourceRadio}"
+$MKDIR -p ./${localpath}
+cd ./${localpath}
+
+#save the top directory
+topDir=`pwd`
+
+#Path of the utility scripts
+scriptpath=${SCRIPTPATH}
+
+
+#JEC 1/10/11 Use generic baodaqstatus name 
+#get the daq current irod status
+#tag=`${DATE} +%F`
+#OUT1=${publicpath}/baodaqstatus-${tag}.txt
+OUT1=${publicpath}/baodaqstatus-current.txt
+
+if [ ! -e ${OUT1}  -o ! -r ${OUT1} ]; then
+    $ECHO "FATAL (${scriptName}): ${OUT1} has a problem"
+    exit 1
+#    $RM -f ${tmppublicpath}/statusdaq.finished
+#    ${scriptpath}/statusdaq.sh > ${OUT1}
+#    while [ ! -f "${tmppublicpath}/statusdaq.finished" ]; do
+#	sleep 30
+#    done
+#    $RM ${tmppublicpath}/statusdaq.finished
+#protect against remove/rewriting    
+#    $CHMOD -v 444 ${OUT1} 
+#
+fi
+
+#
+#We forbib to perform the gain for all the sources in one shot!
+#
+#if [ ! "<${sourceRadio}>" = "All" ]; then
+$ECHO "You have selected sourceRadio = $sourceRadio"
+tableau=( `$GREP -i ${sourceRadio} ${OUT1} | $AWK '( NF==4 ) { print $2 }' ` )
+#else
+#    tableau=( `$CAT ${OUT1} | $AWK '( NF==4 ) { print $2 }'`  )
+#fi
+IFS='
+'
+tableau=( $( $PRINTF "%s\n" "${tableau[@]}" | $AWK 'x[$0]++ == 0' ) )
+IFS=$DefaultIFS
+
+
+for i in ${tableau[@]}
+  do
+  $ECHO "DEBUG (${scriptName}): irods root dir $i"
+  dateDAQ=`$ECHO ${i} | $AWK '{split($0,a,"/"); print a[6];}' | $AWK "{sub(/${srclower}/,\"\"); print}"`
+#JEC 1/10/11 Use generic baodaqstatus name 
+#Look if the date has changed since beginning of the job!
+#  curtag=`${DATE} +%F`
+#  if [ "<${curtag}>" != "<${tag}>" ]; then
+#      tag=${curtag}
+#it is necessary to update the daq status as the day has changed during the processing... (batch can take a long time...)
+#      OUT1=${publicpath}/baodaqstatus-${curtag}.txt
+#      $ECHO "We should bring the DAQ status more up to date, this take 1 or 2sec..."
+#      $RM -f ${tmppublicpath}/statusdaq.finished
+#      ${scriptpath}/statusdaq.sh > ${OUT1}
+#      while [ ! -f "${tmppublicpath}/statusdaq.finished" ]; do
+#	  sleep 30
+#      done
+#      $RM ${tmppublicpath}/statusdaq.finished
+#protect against remove/rewriting    
+#      $CHMOD -v 444 ${OUT1} 
+#  fi
+#
+# look if the fits file of the gains already exists
+  alreadyDone=`ils ${i} 2>&1 | $GREP -i "gain_.*\.fits" | $WC -l`
+  if [ ${alreadyDone} -gt 0 ]; then
+      $ECHO "INFO (${scriptName}): Fits file for gains already exists"
+      continue
+  fi
+# Something should be done...
+#look if the files for the input to gain computations have been done
+  somethingTodo=1
+  input4gainOk1=`ils ${i}/Off 2>&1 | $GREP -i "^ERROR" | $WC -l` 
+  input4gainOk2=`ils ${i}/Off 2>&1 | $GREP -i "gaincycle"` 
+  if [ $input4gainOk1 -eq 0 -a "<${input4gainOk2}>" != "<>"  ]; then
+      gaincycle=`$ECHO ${input4gainOk2} | $AWK '($1 == "C-"){print $2}'| $XARGS -i  basename {}`
+      input4gainOk3=`ils ${i}/Off/${gaincycle} 2>&1 | $GREP -i "medfiltmtx" | $WC -l`
+      if [ $input4gainOk3 -gt 0 ]; then
+	  somethingTodo=0
+      fi
+  fi
+  if [ $somethingTodo -eq 1 ]; then
+#
+      $ECHO ">>>>>>>>>>>>>>>> Do proc_script $sourceRadio $dateDAQ GAIN"
+      $RM -f ${tmppublicpath}/proc_script.finished
+      if [ ${simulationMode} = "On" ]; then
+	  $ECHO "SIMUL: ${scriptpath}/proc_script.sh $sourceRadio $dateDAQ GAIN"
+      else      
+	  ${scriptpath}/proc_script.sh $sourceRadio $dateDAQ GAIN
+	  while [ ! -e "${tmppublicpath}/proc_script.finished"  ]; do
+	      $ECHO "INFO (${scriptName}): waiting for ${tmppublicpath}/proc_script.finished"
+	      date +%T
+	      sleep 60
+	  done
+      fi
+      $ECHO "INFO (${scriptName}): proc_script has finished"
+      $RM ${tmppublicpath}/proc_script.finished
+#Todo see if there is errors in the log file before copy
+      $ECHO ">>>>>>>>>>>>>>>> Done proc_script $sourceRadio $dateDAQ GAIN"
+######
+  fi
+######
+  $ECHO ">>>>>>>>>>>>> ANALYSIS Part of ${sourceRadio} ${dateDAQ}"
+#go to the .../source/date-sourcelowercase directory
+  $MKDIR -p ${topDir}/${dateDAQ}${srclower}
+  cd ${topDir}/${dateDAQ}${srclower}
+  aboveOnOffDir=`pwd`
+  $ECHO "DEBUG (${scriptName}): we are in directory: <`pwd`>"
+# So the input files are there, so the fits file can be determined
+  mode="Off"
+  spectraGenDirName=`$ECHO ${gaincycle} | $AWK '{match($0,"[a-zA-Z]+",arr); print arr[0]}'`
+  cycleNumber=`$ECHO ${gaincycle} | $AWK '{match($0,"[0-9]+",arr); print arr[0]}'`
+#care: the gaincycle variable contains the cycle number
+  $ECHO "DEBUG (${scriptName}): START download the fits files"
+  inFileDirectory="./${mode}"
+  $MKDIR -p ${inFileDirectory}
+  irodsDownDir="${i}/${mode}/${gaincycle}"
+  OUT=./getInFits.$$
+  iget -r -f -K ${irodsDownDir} ${inFileDirectory} > ${OUT} 2>&1
+  $LS ${inFileDirectory}/${gaincycle}
+  igetStatus=`$GREP "^ERROR" ${OUT}`
+  if [ "<$igetStatus>" != "<>" ]; then
+      $ECHO "FATAL (${scriptName}): error while iget fits files:"
+      $ECHO $igetStatus
+      continue
+  fi
+  $RM -f ${OUT}
+  $ECHO "DEBUG (${scriptName}): END download the fits files"
+#Get sca files
+  $ECHO "DEBUG (${scriptName}): START call getscafiles.sh ${sourceRadio} ${dateDAQ}"
+  OUT1=./getScaStatus.$$
+  $RM -f ${tmppublicpath}/getscafiles.finished
+  ${scriptpath}/getscafiles.sh ${sourceRadio} ${dateDAQ} > ${OUT1} 2>&1
+  while [ ! -f "${tmppublicpath}/getscafiles.finished" ]; do
+      $ECHO "INFO (${scriptName}): waiting for ${tmppublicpath}/getscafiles.finished"
+      date +%T
+      sleep 30
+  done
+  $RM ${tmppublicpath}/getscafiles.finished
+  $ECHO "DEBUG (${scriptName}): END"
+#
+  getScaStatus=`$GREP "^\(FATAL\|ERROR\)" ${OUT1}`
+#	
+  if [ "<${getScaStatus}>" != "<>" ]; then
+      $ECHO "FATAL (${scriptName}): error to get sca file for $sourceRadio $dateDAQ"
+      $ECHO "DEBUG (${scriptName}): START with cat ${OUT1}"
+      $CAT ${OUT1}
+      $ECHO "DEBUG (${scriptName}): END"
+      continue
+  fi
+  $RM -f ${OUT1}
+  $ECHO "DEBUG (${scriptName}): where am i `pwd`"
+  $LS -lrt
+  
+  scaFile=`$FIND . -name "sca*.sum.trans" | $XARGS -i basename {}`
+#	
+#the default spectra name is medfiltmtx, otherwise use -specname <a_string>
+  logFile="analyse_GAIN_${sourceRadio}_${dateDAQ}.log"
+  $ECHO "DEBUG (${scriptName}): execute the analysis... should not take long. `date`"
+  if [ ${simulationMode} = "On" ]; then
+      $ECHO "SIMUL: ${scriptpath}/Objs/analyse -act gain  -inPath ${iojobpath} -source  ${sourceRadio} -date ${dateDAQ} -sca ${scaFile} -specdir ${spectraGenDirName} -mode ${mode} -numcycle ${cycleNumber},${cycleNumber} -debug 1 >& ${logFile}"
+      cat > ${logFile} <<EOF
+      Ok gain finished
+EOF
+
+  else
+      ${scriptpath}/Objs/analyse -act gain  -inPath ${iojobpath} -source  ${sourceRadio} -date ${dateDAQ} -sca ${scaFile} -specdir ${spectraGenDirName} -mode ${mode} -numcycle ${cycleNumber},${cycleNumber} -debuglev 1 >& ${logFile}
+  fi
+#
+  $ECHO "DEBUG (${scriptName}): analysis finished `date`. Look for errors before saving to Irods"
+  rcstatus=`$GREP -i "OK gain finished" ${logFile} | $WC -l`
+  if [ ${rcstatus} -eq 0 ]; then
+      $ECHO "INFO (${scriptName}): analysis problem for ${sourceRadio} ${dateDAQ}"
+      $ECHO "                      START logfile"
+      $CAT ${logFile}
+      $ECHO "                      END   logFile"
+#clean and leave
+      cd ${aboveOnOffDir}
+      $RM -rf ./*
+      continue
+  fi
+#Save into Irods
+  $ECHO "DEBUG (${scriptName}): START save output files"
+  $LS ${aboveOnOffDir}
+#use -f option of iput ONLY to force override
+  if [ ${simulationMode} = "On" ]; then
+      $ECHO "SIMUL: here we look for gain file and put them in Irods"
+  else
+      $FIND . -name "gain_*" -print | $XARGS -i  iput  -v -K {} ${i}
+  fi
+#save analysis logfile
+  $LS -l ${tmppublicpath} > /dev/null
+  $CP ${logFile} ${tmppublicpath}
+  $ECHO "DEBUG (${scriptName}): END save output files"
+#clean
+  cd ${aboveOnOffDir}
+  $RM -rf ./*
+done
+
+exit 0
Index: /BAORadio/AmasNancay/v5/getAnalyseFiles.sh
===================================================================
--- /BAORadio/AmasNancay/v5/getAnalyseFiles.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/getAnalyseFiles.sh	(revision 596)
@@ -0,0 +1,143 @@
+#!/bin/sh -xvf
+#Perform the ON-OFF analysis
+DATE=/bin/date
+GREP=/bin/grep
+AWK=/bin/awk
+ECHO=/bin/echo
+WC=/usr/bin/wc
+CAT=/bin/cat
+PRINTF=/usr/bin/printf
+FIND=/usr/bin/find
+MKDIR=/bin/mkdir
+XARGS=/usr/bin/xargs
+SORT=/bin/sort
+RM=/bin/rm
+TR=/usr/bin/tr
+CP=/bin/cp
+LS=/bin/ls
+CHMOD=/bin/chmod
+
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+#set Irods environment    
+. /usr/local/shared/bin/irods_env.sh -noverbose
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+#which source to analyse
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+dateSelected=
+simulationMode=Off
+while [ $# -gt 0 ]
+  do
+  case "$1" in
+      -src)  sourceRadio=$2;    shift;;
+      -date) dateSelected=$2;     shift;;
+      -sim)  simulationMode=On;;
+      -h)
+      echo >&2 \
+	  "usage: $0 -src souce -date YYYYMMDD [-sim to trig simulation mode]"
+      exit 1;;
+      *)  break;;	# terminate while loop
+  esac
+  shift
+done
+
+
+if [ ${simulationMode} = "On" ]; then
+    $ECHO "INFO ${scriptName} running in SIMUL mode"
+fi
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+case ${sourceRadio} in
+    Abell85) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    Abell2440) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    Abell1205) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    *) ECHO "FATAL (${scriptName}): process ${sourceRadio} not yet foreseen"
+    exit 1;;
+esac
+
+srclower=`${ECHO} ${sourceRadio} | ${TR} "[:upper:]" "[:lower:]" `
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+#wakeup the NFS disk
+$LS -l ${tmppublicpath} > /dev/null
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+localpath="${sourceRadio}"
+$MKDIR -p ./${localpath}
+cd ./${localpath}
+
+
+#Path of the utility scripts
+scriptpath=${SCRIPTPATH}
+
+OUT1=${publicpath}/baodaqstatus-current.txt
+if [ ! -e ${OUT1}  -o ! -r ${OUT1} ]; then
+    $ECHO "FATAL (${scriptName}): ${OUT1} has a problem"
+    exit 1
+fi
+
+
+
+$ECHO "You have selected sourceRadio = ${sourceRadio} [date = ${dateSelected}]"
+tableau=( `$GREP -i "${dateSelected}${srclower}" ${OUT1} | $AWK '( NF==4 ) { print $2 }' ` )
+IFS='
+' 
+tableau=( $( $PRINTF "%s\n" "${tableau[@]}" | $AWK 'x[$0]++ == 0' ) )
+IFS=$DefaultIFS
+
+$ECHO "We are in directory `pwd`"
+
+for i in ${tableau[@]}
+  do
+#
+  
+  $ECHO "DEBUG: (${scriptName}) irods root dir $i"
+
+  #ON-OFF avec les RAW files normalises 
+  file=`ils ${i} 2>&1 | $GREP -i "diffOnOffRAw_.*\.ppf"`
+  file=`$ECHO $file`
+  if [ "<${file}>" != "<>" ]; then
+      iget -f -v ${i}/${file} 
+  fi
+
+  #ON & OFF RAW files normalises
+  file=`ils ${i} 2>&1 | $GREP -i "dataRAw_.*\.ppf"`
+  file=`$ECHO $file`
+  if [ "<${file}>" != "<>" ]; then
+      iget -f -v ${i}/${file} 
+  fi
+
+  #fichiers de calibrations BAO
+  calibfiles=( `ils ${i} 2>&1 | $GREP -i "calib_.*\.txt" ` )
+  IFS='
+' 
+  calibfiles=( $( $PRINTF "%s\n" "${calibfiles[@]}" | $AWK 'x[$0]++ == 0' )  )
+  IFS=$DefaultIFS
+
+  for j in ${calibfiles[@]}
+    do
+    file=`$ECHO $j`
+    iget -f -v ${i}/${file}
+  done
+  
+done
+
+exit 0
Index: /BAORadio/AmasNancay/v5/getscafiles.sh
===================================================================
--- /BAORadio/AmasNancay/v5/getscafiles.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/getscafiles.sh	(revision 596)
@@ -0,0 +1,143 @@
+#!/bin/sh
+#Get SCA file and summary + transformed date file
+#
+DATE=/bin/date
+GREP=/bin/grep
+AWK=/bin/awk
+ECHO=/bin/echo
+TR=/usr/bin/tr
+MKDIR=/bin/mkdir
+CAT=/bin/cat
+PRINTF=/usr/bin/printf
+RM=/bin/rm
+LS=/bin/ls
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+
+
+if [ ! $# = 2 ]; then
+  $ECHO "usage: ${script
+Name} <source:ex. Abell85> <date:YYYYMMDD>"
+  exit 0
+fi
+
+# Irods environment settings
+#export PATH=$PATH:/home/bao/irods2.5_LinuxSL5
+. /usr/local/shared/bin/irods_env.sh -noverbose
+
+
+sourceRadio=$1
+srclower=`${ECHO} ${sourceRadio} | ${TR} "[:upper:]" "[:lower:]" `
+dateDAQ=$2
+
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+$LS -l ${tmppublicpath} > /dev/null
+
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+localpath="${sourceRadio}/${dateDAQ}${srclower}"
+$MKDIR -p ./${localpath}
+cd ./${localpath}
+
+
+#Path of the utility scripts
+scriptpath=${SCRIPTPATH}
+
+#JEC 1/10/11 Use generic baodaqstatus name 
+#look if the run exists
+#tag=`${DATE} +%F`
+#OUT1=${publicpath}/baodaqstatus-${tag}.txt
+OUT1=${publicpath}/baodaqstatus-current.txt
+
+if [ ! -e ${OUT1} -o ! -r ${OUT1} ]; then
+#    $ECHO "We should bring the DAQ status more up to date, this take 1 or 2sec..."
+#    $RM -f ${tmppublicpath}/statusdaq.finished
+#    ${scriptpath}/statusdaq.sh > ${OUT1}
+#    while [ ! -f "${tmppublicpath}/statusdaq.finished" ]; do
+# 	$ECHO "INFO (${scriptName}); waiting for ${tmppublicpath}/statusdaq.finished"
+# 	date +%T
+# 	sleep 30
+#     done
+#     $RM ${tmppublicpath}/statusdaq.finished
+    $ECHO "FATAL (${scriptName}): ${OUT1} is missing or not readable..."
+    exit 1
+fi
+
+nfiles=`${GREP} "${sourceRadio}.*${dateDAQ}" ${OUT1} | ${AWK} '(NF==4){print $4}'` 
+
+if [ "<${nfiles}>" = "<>" ]; then
+    $ECHO "FATAL (${scriptName}): No run found for <${sourceRadio}> and date <${dateDAQ}>"
+    exit 1
+fi
+
+
+#Look if the run should/can be prepared wrt SCA file transformation 
+OUT2=./scaStatus.$$
+#JEC 29/9/11 avoid finished stuff
+#$RM -f ${tmppublicpath}/scaextractor.finished
+${scriptpath}/scaextractor.sh $sourceRadio > ${OUT2} 2>&1
+#while [ ! -f "${tmppublicpath}/scaextractor.finished" ]; do
+#    $ECHO "INFO (${scriptName}); waiting for ${tmppublicpath}/scaextractor.finished"
+#    date +%T
+#    sleep 30
+#done
+#$RM ${tmppublicpath}/scaextractor.finished
+
+
+status=`$GREP "^FATAL.*${sourceRadio}.*${dateDAQ}" ${OUT2}`
+
+if [ "<$status>" != "<>" ]; then
+    $ECHO "FATAL (${scriptName}): connot proceed further with $sourceRadio $dateDAQ"
+    exit 1
+fi
+$RM $OUT2
+
+#dowload sca files...
+dirIrod="/baoradio/data/AmasNancay/${sourceRadio}/${dateDAQ}${srclower}"
+dirLocal="."
+
+if [ ! -e $dirLocal ]; then
+ $MKDIR -p $dirLocal
+fi
+
+cd $dirLocal
+
+OUT3=./scaFiles.$$
+ils $dirIrod | $GREP -i "sca" > ${OUT3}
+tableau=( `$CAT ${OUT3}`  )
+IFS='
+'
+tableau=( $( $PRINTF "%s\n" "${tableau[@]}" | $AWK 'x[$0]++ == 0' ) )
+IFS=$DefaultIFS
+$RM $OUT3
+
+OUT4=./igetStatus.$$
+for i in ${tableau[@]}
+do
+  if [ ! -e $i ]; then
+    iget -r -f -v -K ${dirIrod}/$i ${dirLocal} > ${OUT4} 2>&1
+  fi
+done
+
+igetStatus=`$GREP "^ERROR" ${OUT4}`
+if [ "<$igetStatus>" != "<>" ]; then
+  $ECHO "FATAL (${scriptName}): error while iget:"
+  $ECHO $igetStatus
+  exit 1
+fi
+
+$RM -f $OUT4
+
+exit 0
Index: /BAORadio/AmasNancay/v5/getsignalfiles.sh
===================================================================
--- /BAORadio/AmasNancay/v5/getsignalfiles.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/getsignalfiles.sh	(revision 596)
@@ -0,0 +1,136 @@
+#!/bin/sh
+#
+#Script sh d'extraction de fichiers d'irod 
+# Auteur: JE Campagne (LAL Orsay)
+# Creation: 2 mai 2011
+# adaptation pour le CC 17 juin 2011
+DATE=/bin/date
+GREP=/bin/grep
+AWK=/bin/awk
+ECHO=/bin/echo
+TR=/usr/bin/tr
+MKDIR=/bin/mkdir
+CAT=/bin/cat
+RM=/bin/rm
+LS=/bin/ls
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+
+
+
+if [ ! $# = 4 ]; then
+  $ECHO "usage: ${scriptName} <source:ex. Abell85> <date:YYYYMMDD> first last"
+  exit 0
+fi
+
+# Irods environment settings
+#export PATH=$PATH:/home/bao/irods2.5_LinuxSL5
+. /usr/local/shared/bin/irods_env.sh -noverbose
+
+sourceRadio=$1
+srclower=`${ECHO} ${sourceRadio} | ${TR} "[:upper:]" "[:lower:]" `
+dateDAQ=$2
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+$LS -l ${tmppublicpath} > /dev/null
+
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+localpath="${sourceRadio}/${dateDAQ}${srclower}"
+$MKDIR -p ./${localpath}
+cd ./${localpath}
+
+#Path of the utility scripts
+scriptpath=${SCRIPTPATH}
+
+
+#determine the sequence of signal files to download
+#JEC 1/10/11 Use generic baodaqstatus name 
+#get the daq current irod status
+#tag=`${DATE} +%F`
+#OUT1=${publicpath}/baodaqstatus-${tag}.txt
+OUT1=${publicpath}/baodaqstatus-current.txt
+
+if [ ! -e ${OUT1} -o ! -r ${OUT1} ]; then
+#     $ECHO "We should bring the DAQ status more up to date, this take few 
+# sec..."
+#     $RM -f ${tmppublicpath}/statusdaq.finished
+#     ${scriptpath}/statusdaq.sh > ${OUT1}
+#     while [ ! -f "${tmppublicpath}/statusdaq.finished" ]; do
+# 	$ECHO "INFO (${scriptName}); waiting for ${tmppublicpath}/statusdaq.finished"
+# 	date +%T
+# 	sleep 30
+#     done
+#     $RM ${tmppublicpath}/statusdaq.finished
+    $ECHO "FATAL (${scriptName}): ${OUT1} is missing or not readable..."
+    exit 1
+fi
+
+nfiles=`${GREP} "${sourceRadio}.*${dateDAQ}" ${OUT1} | ${AWK} '(NF==4){print $4}'` 
+if [ "<${nfiles}>" == "<>" ]; then
+    $ECHO "FATAL (${scriptName}): No run found for <${sourceRadio}> and date <${dateDAQ}>"
+    $CAT $OUT1
+    exit 1
+fi
+
+
+firstFile=$3
+if [ ${firstFile} -gt  ${nfiles} ]; then
+    $ECHO "FATAL (${scriptName}): ${firstFile} >  ${nfiles}"
+    exit 1
+fi
+
+
+lastFile=$4
+if [ ${lastFile} -gt  ${nfiles} ]; then
+    $ECHO "FATAL (${scriptName}): ${lastFile} >  ${nfiles}"
+    exit 1
+fi
+
+if [ ${firstFile} -gt  ${lastFile} ]; then
+    $ECHO "FATAL (${scriptName}): ${firstFile} >  ${lastFile}"
+    exit 1
+fi
+
+
+dirIrod="/baoradio/data/AmasNancay/${sourceRadio}/${dateDAQ}${srclower}"
+dirLocal="."
+
+##$ECHO "Ready to download [${firstFile},${lastFile}] in $dirLocal from $dirIrod"
+#Nb we are in the localpath
+$MKDIR -p Fiber1
+$MKDIR -p Fiber2
+
+OUT2=./igetStatus.$$
+
+n=$firstFile
+while [[ $n -le $lastFile ]]; do
+   iget -r -f -v -K ${dirIrod}/Fiber1/signal$n.fits ${dirLocal}/Fiber1 >${OUT2} 2>&1
+   igetStatus=`$GREP "^ERROR" ${OUT2}`
+   if [ "<$igetStatus>" != "<>" ]; then
+       $ECHO "FATAL (${scriptName}): error while iget:"
+       $ECHO $igetStatus
+       exit 1
+   fi
+   iget -r -f -v -K ${dirIrod}/Fiber2/signal$n.fits ${dirLocal}/Fiber2 >${OUT2} 2>&1
+   igetStatus=`$GREP "^ERROR" ${OUT2}`
+   if [ "<$igetStatus>" != "<>" ]; then
+       $ECHO "FATAL (${scriptName}): error while iget:"
+       $ECHO $igetStatus
+       exit 1
+   fi
+   n=$(($n+1))
+done
+
+exit 0
Index: /BAORadio/AmasNancay/v5/hdrfitsextractor.sh
===================================================================
--- /BAORadio/AmasNancay/v5/hdrfitsextractor.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/hdrfitsextractor.sh	(revision 596)
@@ -0,0 +1,152 @@
+#!/bin/sh
+#download SCA file, proceed to introspection, and upload results
+DATE=/bin/date
+GREP=/bin/grep
+AWK=/bin/awk
+ECHO=/bin/echo
+WC=/usr/bin/wc
+CAT=/bin/cat
+PRINTF=/usr/bin/printf
+MKDIR=/bin/mkdir
+XARGS=/usr/bin/xargs
+SORT=/bin/sort
+RM=/bin/rm
+defaultIFS=$IFS
+
+#set Irods environment    
+. /usr/local/shared/bin/irods_env.sh -noverbose
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+
+#which source to analyse
+sourceRadio=$1
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+localpath="${sourceRadio}"
+$MKDIR -p ./${localpath}
+cd ./${localpath}
+
+
+#Path of the utility scripts
+scriptpath=${SCRIPTPATH}
+
+
+#JEC 1/10/11 Use generic baodaqstatus name 
+#get the daq current irod status
+#tag=`${DATE} +%F`
+#OUT1=${publicpath}/baodaqstatus-${tag}.txt
+OUT1=${publicpath}/baodaqstatus-current.txt
+
+if [ ! -e ${OUT1}  -o ! -r ${OUT1} ]; then
+    $ECHO "FATAL (${scriptName}): ${OUT1} has a problem"
+    exit 1
+fi
+
+#if [ ! -e ${OUT1} ]; then
+#    $ECHO "We should bring the DAQ status more up to date, this take 1 or 2sec..."
+#    ${scriptpath}/statusdaq.sh > ${OUT1}
+#fi
+
+if [ ! "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "You have selected sourceRadio = $sourceRadio"
+    tableau=( `$GREP -i ${sourceRadio} ${OUT1} | $AWK '( NF==4 ) { print $2 }' ` )
+else
+    tableau=( `$CAT ${OUT1} | $AWK '( NF==4 ) { print $2 }'`  )
+fi
+IFS='
+'
+tableau=( $( $PRINTF "%s\n" "${tableau[@]}" | $AWK 'x[$0]++ == 0' ) )
+
+
+workArea="headers"
+$MKDIR -p ./${workArea}
+cd ./${workArea}
+
+
+nloop4dbg=0
+
+
+for i in ${tableau[@]}
+do
+#look if the headers have been already extracted
+  $ECHO "DEBUG (${scriptName}): irods root dir $i"
+  for fibdir in Fiber1 Fiber2; do
+      $ECHO "DEBUG (${scriptName}): Fiber $fibdir"
+#NB: care should be taken to the fact that ILS returns all the instance of the file (HPSS, disk...)
+#    so one should use a trick to count unique instance
+      listOfsig=( `ils ${i}/${fibdir} | $GREP -i "signal" | $XARGS -i basename {} | $SORT -k1.7n` )
+      IFS='
+'
+      listOfsig=( $( $PRINTF "%s\n" "${listOfsig[@]}" | $AWK 'x[$0]++ == 0' ) )
+      nblinesSIG=${#listOfsig[@]}
+      listOfhdr=( `ils ${i}/${fibdir} | $GREP -i "header" | $XARGS -i basename {} | $SORT -k1.7n` )
+      IFS='
+'
+      listOfhdr=( $( $PRINTF "%s\n" "${listOfhdr[@]}" | $AWK 'x[$0]++ == 0' ) )
+      nblinesHDR=${#listOfhdr[@]}
+      $ECHO "(DEBUG) (${scriptName}:  test if $nblinesHDR != $nblinesSIG "
+      if [ $nblinesHDR != $nblinesSIG ]; then
+#do the header extraction
+#build signal files list 
+#loop on signal files
+	  $ECHO "(DEBUG) (${scriptName}):  ${listOfsig[@]}"
+
+	  for sigfname in ${listOfsig[@]}
+	    do
+	    filename=$(basename $sigfname)
+	    extension=${filename##*.}
+	    filename=${filename%.*}
+            number=`$ECHO $filename | $AWK '{len=length("signal");len=len+1;a=substr($1,len);print a}'`
+	    hdrname="header${number}.txt"
+#look if header file already exists: if so skip it
+	    hdrIsthere=`ils ${i}/${fibdir}/${hdrname} 2>&1 | $GREP -i "^ERROR" | $WC -l`
+	    $ECHO "(DEBUG) (${scriptName}): look if ${hdrname}  exist (${hdrIsthere})"
+	    if [ $hdrIsthere -eq 0 ]; then 
+		continue
+	    fi
+#get the signal file
+	    $ECHO "DEBUG (${scriptName}): iget $sigfname (dgg = ${nloop4dbg})"
+            OUT3=./igetlog${nloop4dbg}.$$
+	    iget -f -v -K ${i}/${fibdir}/${sigfname} . >${OUT3} 2>&1
+	    igetStatus=`$GREP "^ERROR" ${OUT3}`
+	    if [ "<$igetStatus>" != "<>" ]; then
+		$ECHO "INFO (${scriptName}): error while iget:"
+		$ECHO $igetStatus
+		continue
+	    fi
+            $RM $OUT3
+#extract the header part of the  signal file
+	    $ECHO "DEBUG (${scriptName}): get header from ${sigfname} and put it in ${hdrname}"
+	    IFS=$defaultIFS
+	    while read -n80 L
+	      do
+	      [ "${L::3}" = "END" ] && break
+	      $ECHO $L
+	    done < ${sigfname} > ${hdrname}
+	    $RM ${sigfname}
+	    nhdrlines=`$WC -l ${hdrname} | $AWK '{print $1}' `
+	    if [  "${nhdrlines}" = "0"  ]; then
+		$ECHO "WARNING (${scriptName}): ${sigfname} has no valid header"
+	    else
+#transfert to irod the header
+		$ECHO "INFO (${scriptName}): transfert ${hdrname} to ${i}/${fibdir}"
+#use -f option ONLY to force override
+		iput  -v -K ${hdrname} ${i}/${fibdir}
+	    fi
+            $RM ${hdrname}
+	    nloop4dbg=$(expr $nloop4dbg + 1)
+	  done
+      else
+	  $ECHO "INFO (${scriptName}): nothing to do for ${i}/${fibdir}"
+      fi
+  done
+done
Index: /BAORadio/AmasNancay/v5/isInteractive.sh
===================================================================
--- /BAORadio/AmasNancay/v5/isInteractive.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/isInteractive.sh	(revision 596)
@@ -0,0 +1,10 @@
+isInteractive()
+{
+  if [ ${ENVIRONMENT} == "INTERACTIVE" -o ${ENVIRONMENT} == "ACCESS" ]; then
+    isInteractive=1
+  else
+    isInteractive=0
+  fi
+
+  echo ${isInteractive}
+}
Index: /BAORadio/AmasNancay/v5/makefile
===================================================================
--- /BAORadio/AmasNancay/v5/makefile	(revision 596)
+++ /BAORadio/AmasNancay/v5/makefile	(revision 596)
@@ -0,0 +1,48 @@
+include $(SOPHYABASE)/include/sophyamake.inc
+
+OBJ = ./Objs/
+EXE = ./Objs/
+
+
+PKGOLIST =
+
+EXELIST = $(EXE)analyse $(EXE)mergeAnaFiles $(EXE)anaTools
+
+EXEOLIST = $(EXE)analyse.o $(EXE)mergeAnaFiles.o $(EXE)anaTools.o
+
+
+all : analyse mergeAnaFiles anaTools
+
+clean :
+	rm -f $(PKGOLIST) $(EXELIST) $(EXEOLIST)
+
+########################################################
+
+#......
+analyse : $(EXE)analyse
+	echo '---analyse made'
+
+$(EXE)analyse : $(OBJ)analyse.o $(PKGOLIST)
+	$(CXXLINK) -o $(EXE)analyse $(OBJ)analyse.o $(PKGOLIST) $(SOPHYAALLSLBLIST)
+
+$(OBJ)analyse.o : analyse.cc $(PKGHLIST)
+	$(CXXCOMPILE) -c  -o $(OBJ)analyse.o analyse.cc 
+
+mergeAnaFiles : $(EXE)mergeAnaFiles
+	echo '---mergeAnaFiles made'
+
+$(EXE)mergeAnaFiles : $(OBJ)mergeAnaFiles.o
+	$(CXXLINK) -o $(EXE)mergeAnaFiles $(OBJ)mergeAnaFiles.o  $(SOPHYAALLSLBLIST)
+
+$(OBJ)mergeAnaFiles.o : mergeAnaFiles.cc
+	$(CXXCOMPILE) -c  -o $(OBJ)mergeAnaFiles.o mergeAnaFiles.cc
+
+anaTools : $(EXE)anaTools
+	echo '---anaTools made'
+
+$(EXE)anaTools : $(OBJ)anaTools.o
+	$(CXXLINK) -o $(EXE)anaTools $(OBJ)anaTools.o  $(SOPHYAALLSLBLIST)
+
+$(OBJ)anaTools.o : anaTools.cc
+	$(CXXCOMPILE) -c  -o $(OBJ)anaTools.o anaTools.cc
+
Index: /BAORadio/AmasNancay/v5/mergeAnaFiles.cc
===================================================================
--- /BAORadio/AmasNancay/v5/mergeAnaFiles.cc	(revision 596)
+++ /BAORadio/AmasNancay/v5/mergeAnaFiles.cc	(revision 596)
@@ -0,0 +1,1200 @@
+// Utilisation de SOPHYA pour faciliter les tests ...
+#include "sopnamsp.h"
+#include "machdefs.h"
+#include <dirent.h>
+#include <matharr.h>
+
+// include standard c/c++
+#include <regex.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <limits>
+#include <iostream>
+#include <fstream>
+#include <string>
+#include <vector>
+#include <map>
+#include <functional>
+#include <algorithm>
+#include <numeric>
+#include <list>
+#include <exception>
+
+// include sophya mesure ressource CPU/memoire ...
+#include "resusage.h"
+#include "ctimer.h"
+#include "timing.h"
+#include "timestamp.h"
+#include "strutilxx.h"
+#include "ntuple.h"
+#include "fioarr.h"
+#include "tarrinit.h"
+#include "histinit.h"
+#include "fitsioserver.h"
+#include "fiosinit.h"
+#include "ppersist.h"
+
+//-----------------------------------------------
+//Usage
+//
+//./Objs/mergeAnaFiles -act meanCalibBAODiffOnOff -inPath /sps/baoradio/AmasNancay/JEC/ -src Abell85 -ppfFile dataRaw -debug 1 -mxcycles 500
+//./Objs/mergeAnaFiles -src Abell85 -act meanCalibBAODiffOnOff -mxcycles 500 -calibfreq 1410 -inPath /sps/baoradio/AmasNancay/JEC/ -ppfFile dataRaw -debug 1 >& mergeAna-500.log
+//
+//
+//-----------------------------------------------
+const sa_size_t NUMBER_OF_CHANNELS = 2;
+const sa_size_t NUMBER_OF_FREQ     = 8192;
+const r_4    LOWER_FREQUENCY       = 1250.0; //MHz
+const r_4    TOTAL_BANDWIDTH       = 250.0;  //MHz
+//Input parameters
+struct Param {
+  int debuglev_;      //debug
+  string inPath_;     //root directory of the input files
+  string outPath_;    //output files are located here
+  string sourceName_; //source name & subdirectory of the input files
+  string ppfFile_;    //generic name of the input files
+  int nSliceInFreq_;  //used by reduceSpectra() fnc
+  string calibFreq_;  //freq. value used for calibration
+  r_4 rcalibFreq_;    //float version
+  string calibBandFreq_;  //band of freq. used for calibration
+  r_4 rcalibBandFreq_;    //float version
+  int maxNumberCycles_;//maximum number of cycles to be treated
+} para;
+//--------------------------------------------------------------
+//Utility functions
+
+sa_size_t freqToChan(r_4 f){
+  return (sa_size_t)((f-LOWER_FREQUENCY)/TOTAL_BANDWIDTH*NUMBER_OF_FREQ);
+}
+//--------
+//COMPUTE the mean value on a freq. range for all channels
+//--------
+void meanInRange(const TMatrix<r_4> mtx, 
+		 sa_size_t chLow,
+		 sa_size_t chHigh, 
+		 TVector<r_4>& vec){
+  
+  sa_size_t nr = mtx.NRows();
+  
+  for (sa_size_t ir=0; ir<nr; ir++){
+    TVector<r_4> tmp(mtx(Range(ir),Range(chLow,chHigh)),false);
+    double mean, sigma;
+    MeanSigma(tmp,mean,sigma);
+    vec(ir) = mean;
+  }
+}
+//---------
+class median_of_empty_list_exception:public std::exception{
+    virtual const char* what() const throw() {
+    return "Attempt to take the median of an empty list of numbers.  "
+      "The median of an empty list is undefined.";
+  }
+};
+template<class RandAccessIter>
+double median(RandAccessIter begin, RandAccessIter end) 
+  throw(median_of_empty_list_exception){
+  if(begin == end){ throw median_of_empty_list_exception(); }
+  std::size_t size = end - begin;
+  std::size_t middleIdx = size/2;
+  RandAccessIter target = begin + middleIdx;
+  std::nth_element(begin, target, end);
+    
+  if(size % 2 != 0){ //Odd number of elements
+    return *target;
+  }else{            //Even number of elements
+    double a = *target;
+    RandAccessIter targetNeighbor= target-1;
+    std::nth_element(begin, targetNeighbor, end);
+    return (a+*targetNeighbor)/2.0;
+  }
+}
+
+//-------------
+//JEC 25/10/11 Perform a median filtering with a sliding window of "halfwidth" half width
+//             It takes care of the edges and is based on the median function (above) 
+void medianFiltering(const TMatrix<r_4> mtx, 
+		     sa_size_t halfwidth,
+		     TMatrix<r_4>& vec) {
+  
+  sa_size_t nr = mtx.NRows();
+  sa_size_t nc = mtx.NCols();
+  sa_size_t chMin = 0;
+  sa_size_t chMax = nc-1;
+  
+  for (sa_size_t ir=0; ir<nr; ir++){
+    for (sa_size_t ic=0; ic<nc; ic++) {
+      sa_size_t chLow = ic-halfwidth;
+      chLow = (chLow >= chMin) ? chLow : chMin;
+      sa_size_t chHigh = ic+halfwidth;
+      chHigh = ( chHigh <= chMax ) ? chHigh : chMax;
+      TVector<r_4> tmp(mtx(Range(ir),Range(chLow,chHigh)),false);
+      vector<r_4> val;
+      tmp.FillTo(val);
+      vec(ir,ic) = median(val.begin(),val.end());
+    }
+  }
+}
+//-------------
+void split(const string& str, const string& delimiters , vector<string>& tokens) {
+    // Skip delimiters at beginning.
+    string::size_type lastPos = str.find_first_not_of(delimiters, 0);
+    // Find first "non-delimiter".
+    string::size_type pos     = str.find_first_of(delimiters, lastPos);
+
+    while (string::npos != pos || string::npos != lastPos)
+    {
+        // Found a token, add it to the vector.
+        tokens.push_back(str.substr(lastPos, pos - lastPos));
+        // Skip delimiters.  Note the "not_of"
+        lastPos = str.find_first_not_of(delimiters, pos);
+        // Find next "non-delimiter"
+        pos = str.find_first_of(delimiters, lastPos);
+    }
+}
+//--------------------------------------------------------------
+char *regexp (const char *string, const char *patrn, int *begin, int *end) {    
+        int i, w=0, len;                 
+        char *word = NULL;
+        regex_t rgT;
+        regmatch_t match;
+        regcomp(&rgT,patrn,REG_EXTENDED);
+        if ((regexec(&rgT,string,1,&match,0)) == 0) {
+                *begin = (int)match.rm_so;
+                *end = (int)match.rm_eo;
+                len = *end-*begin;
+                word=(char*)malloc(len+1);
+                for (i=*begin; i<*end; i++) {
+                        word[w] = string[i];
+                        w++; }
+                word[w]=0;
+        }
+        regfree(&rgT);
+        return word;
+}
+//------- 
+sa_size_t round_sa(r_4 r) {
+  return static_cast<sa_size_t>((r > 0.0) ? (r + 0.5) : (r - 0.5));
+}
+//-----
+string StringToLower(string strToConvert){
+  //change each element of the string to lower case
+  for(unsigned int i=0;i<strToConvert.length();i++) {
+    strToConvert[i] = tolower(strToConvert[i]);
+  }
+  return strToConvert;//return the converted string
+}
+//-----
+bool stringCompare( const string &left, const string &right ){
+   if( left.size() < right.size() )
+      return true;
+   for( string::const_iterator lit = left.begin(), rit = right.begin(); lit != left.end() && rit != right.end(); ++lit, ++rit )
+      if( tolower( *lit ) < tolower( *rit ) )
+         return true;
+      else if( tolower( *lit ) > tolower( *rit ) )
+         return false;
+   return false;
+}
+//-----
+list<string> ListOfFileInDir(string dir, string filePettern) throw(string) {
+  list<string> theList;
+
+
+  DIR *dip;
+  struct dirent *dit;
+  string msg;  string fileName;
+  string fullFileName;
+  size_t found;
+
+  if ((dip=opendir(dir.c_str())) == NULL ) {
+    msg = "opendir failed on directory "+dir;
+    throw msg;
+  }
+  while ( (dit = readdir(dip)) != NULL ) {
+    fileName = dit->d_name;
+    found=fileName.find(filePettern);
+    if (found != string::npos) {
+      fullFileName = dir + "/";
+      fullFileName += fileName;
+      theList.push_back(fullFileName);
+    }
+  }//eo while
+  if (closedir(dip) == -1) {
+    msg = "closedir failed on directory "+dir;
+    throw msg;
+  }
+  
+  theList.sort(stringCompare);
+
+  return theList;
+
+}
+//
+class  StringMatch : public unary_function<string,bool> {
+public:
+  StringMatch(const string& pattern): pattern_(pattern){}
+  bool operator()(const string& aStr) const {
+
+
+    int b,e;
+    regexp(aStr.c_str(),pattern_.c_str(),&b,&e);
+
+//     cout << "investigate " << aStr << " to find " << pattern_ 
+// 	 << "[" <<b<<","<<e<<"]" 
+// 	 << endl;
+
+    
+    if (b != 0) return false;
+    if (e != (int)aStr.size()) return false;
+    return true;
+
+  }
+private:
+  string pattern_;
+};
+//-------------------------------------------------------
+//Rebin in frequence + compute mean and sigma
+void reduceSpectra(const TMatrix<r_4>& specMtxInPut, 
+		    TMatrix<r_4>& meanMtx, 
+		    TMatrix<r_4>& sigmaMtx) {
+  sa_size_t nSliceFreq = para.nSliceInFreq_;
+  sa_size_t deltaFreq =  NUMBER_OF_FREQ/nSliceFreq;
+  for (sa_size_t iSlice=0; iSlice<nSliceFreq; iSlice++){
+    sa_size_t freqLow= iSlice*deltaFreq;
+    sa_size_t freqHigh= freqLow + deltaFreq -1;
+    for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS; ++iCh){
+      TVector<r_4> reducedRow;
+      reducedRow = specMtxInPut.SubMatrix(Range(iCh),Range(freqLow,freqHigh)).CompactAllDimensions();
+      double mean; 
+      double sigma;
+      MeanSigma(reducedRow,mean,sigma);
+      meanMtx(iCh,iSlice) = mean;
+      sigmaMtx(iCh,iSlice) = sigma;
+    }//eo loop on channels
+  }//eo loop on slices
+}
+//-------------------------------------------------------
+//Compute the mean of Diff ON-OFF BAO-calibrated spectra and also the mean/sigma of rebinned spectra 
+//
+void meanCalibBAODiffOnOffCycles() throw(string) {
+
+  list<string> listOfFiles;
+  string directoryName;
+  directoryName = para.inPath_ + "/" + para.sourceName_;
+
+  //Make the listing of the directory
+  listOfFiles = ListOfFileInDir(directoryName,para.ppfFile_);
+  
+  list<string>::const_iterator iFile, iFileEnd, iSpec, iSpecEnd;
+  iFileEnd = listOfFiles.end();
+
+  //mean ON-OFF over the list of cycles
+  TMatrix<r_4> meanDiffONOFFovOFF_noCalib(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ);          //set to 0 
+  TMatrix<r_4> meanDiffONOFF_noCalib(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ);          //set to 0 
+  TMatrix<r_4> meanDiffONOFF_perRunCalib(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ);      //set to 0
+  TMatrix<r_4> meanDiffONOFF_perCycleCalib(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ);    //set to 0
+  static const int NINFO=21;
+  char* onffTupleName[NINFO]={"cycle"
+			      ,"onoffRaw0","onoffRaw1"
+			      ,"onoffRun0","onoffRun1"
+			      ,"onoffCycle0","onoffCycle1"
+			      ,"onoffRaw01420","onoffRaw11420"
+			      ,"onoffRun01420","onoffRun11420"
+			      ,"onoffCycle01420","onoffCycle11420"
+			      ,"onoffRaw01420side","onoffRaw11420side"
+			      ,"onoffRun01420side","onoffRun11420side"
+			      ,"onoffCycle01420side","onoffCycle11420side"
+			      ,"onoffRaw0f14001420","onoffRaw1f14001420"
+  };
+  NTuple onoffevolution(NINFO,onffTupleName);
+  r_4 xnt[NINFO];
+
+  //Lower and Higher freq. arround the Calibration Freq. bin to perform mean follow up
+  sa_size_t chCalibLow  = freqToChan(para.rcalibFreq_ - (para.rcalibBandFreq_*0.5));
+  sa_size_t chCalibHigh = freqToChan(para.rcalibFreq_ + (para.rcalibBandFreq_*0.5));
+  //Lower and Higher freq.  just arround 1420.4MHz Freq. bin to perform mean follow up
+  sa_size_t ch1420Low  = freqToChan(1420.4-0.2);
+  sa_size_t ch1420High = freqToChan(1420.4+0.2);
+
+  //Lower and Higher freq. on the sides of 1420.4Mhz Freq. bin to perform mean follow up
+  sa_size_t ch1420aLow  = freqToChan(1418);
+  sa_size_t ch1420aHigh = freqToChan(1419);
+  sa_size_t ch1420bLow  = freqToChan(1422);
+  sa_size_t ch1420bHigh = freqToChan(1423);
+  
+  //25/10/11 follow 1400-1420Mhz
+  sa_size_t ch1420 = freqToChan(1420);
+  sa_size_t ch1400 = freqToChan(1400);
+
+  if (para.debuglev_>0){
+    cout << "freq. band for follow up [" <<  chCalibLow << ", "<< chCalibHigh << "]" << endl;
+    cout << "freq. band for follow up [" <<  ch1420Low << ", "<< ch1420High << "]" << endl;
+    cout << "freq. band for follow up [" <<  ch1420aLow << ", "<< ch1420aHigh << "]" << endl;
+    cout << "freq. band for follow up [" <<  ch1420bLow << ", "<< ch1420bHigh << "]" << endl;
+  }
+  
+  //Loop on files/run
+
+  int totalNumberCycles=0; //total number of cycles for normalisation
+  for (iFile = listOfFiles.begin(); iFile != iFileEnd; ++iFile) {
+    if (para.debuglev_>90){
+      cout << "load file <" << *iFile << ">" << endl;
+    }
+
+    vector<string> tokens;
+    split(*iFile,"_",tokens);
+    string dateOfRun = tokens[1];
+    if (para.debuglev_>90){
+      cout << "date <" << dateOfRun << ">" << endl;
+    }
+    vector<string> tokens2;
+    split(tokens[2],".",tokens2);
+    string srcLower = tokens2[0];
+
+
+    
+    PInPersist fin(*iFile);
+    vector<string> vec = fin.GetNameTags();
+
+    vector<string> modeList;
+    modeList.push_back("On");
+    modeList.push_back("Off");
+    vector<string>::const_iterator iMode;
+    
+    map<string, list<int> > cycleModeCollect;
+    
+    for (iMode = modeList.begin(); iMode!=modeList.end(); ++iMode) {
+      list<string> listOfSpectra;
+      //Keep only required PPF objects
+      string matchstr = "specRaw"+(*iMode)+"[0-9]+"; 
+      std::remove_copy_if(
+			  vec.begin(), vec.end(), back_inserter(listOfSpectra),
+			  not1(StringMatch(matchstr))
+			  );
+      
+      listOfSpectra.sort(stringCompare);
+      iSpecEnd = listOfSpectra.end();
+      
+      matchstr = "[0-9]+";
+      //Loop of spectra matrix
+      list<int> listOfCycles;
+      for (iSpec = listOfSpectra.begin(); iSpec!=iSpecEnd;  ++iSpec){
+	int b,e;
+	regexp(iSpec->c_str(),matchstr.c_str(),&b,&e);
+	if (para.debuglev_>90){
+	  cout << " spactra <" << *iSpec << ">" << endl;
+	  cout << " cycle " << iSpec->substr(b) << endl;
+	}
+	listOfCycles.push_back(atoi((iSpec->substr(b)).c_str()));
+      }//end loop spectra
+      cycleModeCollect[*iMode] = listOfCycles;
+    }//end of mode    
+
+    //Take the Intersection of the list Of cycles in mode Off and On    
+    list<int> commonCycles;
+    set_intersection(cycleModeCollect["On"].begin(),
+		     cycleModeCollect["On"].end(),
+		     cycleModeCollect["Off"].begin(),
+		     cycleModeCollect["Off"].end(),
+		     back_inserter(commonCycles)
+		     );
+    
+    if (para.debuglev_>90){
+      cout << "Liste of cycles common to On & Off: <";
+      for (list<int>::iterator i=commonCycles.begin(); i!=commonCycles.end(); ++i){
+	cout << *i << " ";
+      }
+      cout << ">" << endl;
+    }
+    
+    //
+    //Load BAO Calibration factors "per Cycle and Channels"
+    //Compute the mean per Cycle to 
+    //  fill factors "per Run and Channels" with the same cycle list
+    //
+    //
+    //TODO improve the code....
+
+    TMatrix<r_4> calibBAOfactors_Off_Cycle_Ch0;
+    TMatrix<r_4> calibBAOfactors_Off_Cycle_Ch1;
+    TMatrix<r_4> calibBAOfactors_On_Cycle_Ch0;
+    TMatrix<r_4> calibBAOfactors_On_Cycle_Ch1;
+    
+    string calibFileName;
+    ifstream ifs;
+    sa_size_t nr,nc; //values read 
+
+    //OFF Cycle per Channel
+    calibFileName = directoryName + "/" 
+      + "calib_" + dateOfRun + "_" + srcLower + "_Off_" 
+      + para.calibFreq_ +"MHz-Ch0Cycles.txt";
+    if(para.debuglev_>0) cout << "Read Calib file " << calibFileName << endl;
+    ifs.open(calibFileName.c_str());
+    if ( ! ifs.is_open() ) {
+
+      throw calibFileName + " cannot be opened...";
+    }	
+    calibBAOfactors_Off_Cycle_Ch0.ReadASCII(ifs,nr,nc);
+    if(para.debuglev_>9){
+      cout << "(nr,nc): "<< nr << "," << nc << endl;
+      calibBAOfactors_Off_Cycle_Ch0.Print(cout);
+      cout << endl;
+    }
+
+    TMatrix<r_4> calibBAOfactors_Off_Run_Ch0(nr,nc);
+    calibBAOfactors_Off_Run_Ch0.Column(0) = calibBAOfactors_Off_Cycle_Ch0.Column(0);
+    {//Compute the mean
+      TVector<r_4> coef(calibBAOfactors_Off_Cycle_Ch0(Range::all(),Range::last()),false);
+      double mean,sigma;
+      MeanSigma(coef,mean,sigma);
+      calibBAOfactors_Off_Run_Ch0.Column(1).SetCst(mean);
+    }
+    if(para.debuglev_>9){
+      cout << "Fill calib. with mean value " << endl; 
+      calibBAOfactors_Off_Run_Ch0.Print(cout);
+      cout << endl;
+    }
+    ifs.close();
+
+    //
+    calibFileName = directoryName + "/" 
+      + "calib_" + dateOfRun + "_" + srcLower + "_Off_" 
+      + para.calibFreq_ +"MHz-Ch1Cycles.txt";
+    if(para.debuglev_>0) cout << "Read Calib file " << calibFileName << endl;
+    ifs.open(calibFileName.c_str());
+    if ( ! ifs.is_open() ) {
+
+      throw calibFileName + " cannot be opened...";
+    }	
+    calibBAOfactors_Off_Cycle_Ch1.ReadASCII(ifs,nr,nc);
+    if(para.debuglev_>9){
+      cout << "(nr,nc): "<< nr << "," << nc << endl;
+      calibBAOfactors_Off_Cycle_Ch1.Print(cout);
+      cout << endl;
+    }
+    TMatrix<r_4> calibBAOfactors_Off_Run_Ch1(nr,nc);
+    calibBAOfactors_Off_Run_Ch1.Column(0) = calibBAOfactors_Off_Cycle_Ch1.Column(0);
+    {//Compute the mean
+      TVector<r_4> coef(calibBAOfactors_Off_Cycle_Ch1(Range::all(),Range::last()),false);
+      double mean,sigma;
+      MeanSigma(coef,mean,sigma);
+      //      cout << "Mean: " << mean << " sigma " << sigma << endl;
+      calibBAOfactors_Off_Run_Ch1.Column(1).SetCst(mean);
+    }
+    if(para.debuglev_>9){
+      cout << "Fill calib. with mean value " << endl; 
+      calibBAOfactors_Off_Run_Ch1.Print(cout);
+      cout << endl;
+    }
+    ifs.close();
+
+    //ON Cycle per Channel
+    calibFileName = directoryName + "/" 
+      + "calib_" + dateOfRun + "_" + srcLower + "_On_" 
+      + para.calibFreq_ +"MHz-Ch0Cycles.txt";
+    if(para.debuglev_>0) cout << "Read Calib file " << calibFileName << endl;
+    ifs.open(calibFileName.c_str());
+    if ( ! ifs.is_open() ) {
+
+      throw calibFileName + " cannot be opened...";
+    }	
+    calibBAOfactors_On_Cycle_Ch0.ReadASCII(ifs,nr,nc);
+    if(para.debuglev_>9){
+      cout << "(nr,nc): "<< nr << "," << nc << endl;
+      calibBAOfactors_On_Cycle_Ch0.Print(cout);
+      cout << endl;      
+    }
+
+    TMatrix<r_4> calibBAOfactors_On_Run_Ch0(nr,nc);
+    calibBAOfactors_On_Run_Ch0.Column(0) = calibBAOfactors_On_Cycle_Ch0.Column(0);
+    {//Compute the mean
+      TVector<r_4> coef(calibBAOfactors_On_Cycle_Ch0(Range::all(),Range::last()),false);
+      double mean,sigma;
+      MeanSigma(coef,mean,sigma);
+      //      cout << "Mean: " << mean << " sigma " << sigma << endl;
+      calibBAOfactors_On_Run_Ch0.Column(1).SetCst(mean);
+    }
+    if(para.debuglev_>9){
+      cout << "Fill calib. with mean value " << endl; 
+      calibBAOfactors_On_Run_Ch0.Print(cout);
+      cout << endl;
+    }
+    ifs.close();
+
+    
+    calibFileName = directoryName + "/" 
+      + "calib_" + dateOfRun + "_" + srcLower + "_On_" 
+      + para.calibFreq_ +"MHz-Ch1Cycles.txt";
+    if(para.debuglev_>0) cout << "Read Calib file " << calibFileName << endl;
+    ifs.open(calibFileName.c_str());
+    if ( ! ifs.is_open() ) {
+      throw calibFileName + " cannot be opened...";
+    }	
+    calibBAOfactors_On_Cycle_Ch1.ReadASCII(ifs,nr,nc);
+    if(para.debuglev_>9){
+      cout << "(nr,nc): "<< nr << "," << nc << endl;
+      calibBAOfactors_On_Cycle_Ch1.Print(cout);
+      cout << endl;
+    }
+    TMatrix<r_4> calibBAOfactors_On_Run_Ch1(nr,nc);
+    calibBAOfactors_On_Run_Ch1.Column(0) = calibBAOfactors_On_Cycle_Ch1.Column(0);
+    {//Compute the mean
+      TVector<r_4> coef(calibBAOfactors_On_Cycle_Ch1(Range::all(),Range::last()),false);
+      double mean,sigma;
+      MeanSigma(coef,mean,sigma);
+      //      cout << "Mean: " << mean << " sigma " << sigma << endl;
+      calibBAOfactors_On_Run_Ch1.Column(1).SetCst(mean);
+    }
+    if(para.debuglev_>9){
+      cout << "Fill calib. with mean value " << endl; 
+      calibBAOfactors_On_Run_Ch1.Print(cout);
+      cout << endl;
+    }
+
+    ifs.close();
+    
+    //link <cycle> - <calibration coefficient>
+    //We cannot rely on identical cycle list of the OFF and ON calibration
+    map<int,r_4> calibBAO_Off_Run_Ch0;
+    map<int,r_4> calibBAO_Off_Run_Ch1;
+    map<int,r_4> calibBAO_On_Run_Ch0;
+    map<int,r_4> calibBAO_On_Run_Ch1;
+
+    map<int,r_4> calibBAO_Off_Cycle_Ch0;
+    map<int,r_4> calibBAO_Off_Cycle_Ch1;
+    map<int,r_4> calibBAO_On_Cycle_Ch0;
+    map<int,r_4> calibBAO_On_Cycle_Ch1;
+
+    //per Run based BAO coefficients
+    nr = calibBAOfactors_Off_Run_Ch0.NRows();
+    for (sa_size_t ir=0; ir<nr; ++ir){
+//       cout << "Calib. Off Run Ch0 cycle ["<< calibBAOfactors_Off_Run_Ch0(ir,0)<<"], val "
+// 	   << calibBAOfactors_Off_Run_Ch0(ir,1) << endl;
+
+      calibBAO_Off_Run_Ch0[(int)calibBAOfactors_Off_Run_Ch0(ir,0)]
+	= calibBAOfactors_Off_Run_Ch0(ir,1);
+      calibBAO_Off_Cycle_Ch0[(int)calibBAOfactors_Off_Cycle_Ch0(ir,0)]
+	= calibBAOfactors_Off_Cycle_Ch0(ir,1);
+      calibBAO_Off_Run_Ch1[(int)calibBAOfactors_Off_Run_Ch1(ir,0)]
+	= calibBAOfactors_Off_Run_Ch1(ir,1);
+      calibBAO_Off_Cycle_Ch1[(int)calibBAOfactors_Off_Cycle_Ch1(ir,0)]
+	= calibBAOfactors_Off_Cycle_Ch1(ir,1);
+    }//eo loop on coef Off
+    
+    nr = calibBAOfactors_On_Run_Ch0.NRows();
+    for (sa_size_t ir=0; ir<nr; ++ir){
+      calibBAO_On_Run_Ch0[(int)calibBAOfactors_On_Run_Ch0(ir,0)]
+	= calibBAOfactors_On_Run_Ch0(ir,1);
+      calibBAO_On_Cycle_Ch0[(int)calibBAOfactors_On_Cycle_Ch0(ir,0)]
+	= calibBAOfactors_On_Cycle_Ch0(ir,1);
+      calibBAO_On_Run_Ch1[(int)calibBAOfactors_On_Run_Ch1(ir,0)]
+	= calibBAOfactors_On_Run_Ch1(ir,1);
+      calibBAO_On_Cycle_Ch1[(int)calibBAOfactors_On_Cycle_Ch1(ir,0)]
+	= calibBAOfactors_On_Cycle_Ch1(ir,1);
+    }//eo loop on coef On
+      
+    //Loop on cyles
+    for (list<int>::iterator ic=commonCycles.begin(); ic!=commonCycles.end(); ++ic){
+
+      //Look if the cycle has been calibrated...
+      bool isCycleCalibrated = 
+	( calibBAO_On_Run_Ch0.count(*ic)    *
+	  calibBAO_On_Run_Ch1.count(*ic)    *
+	  calibBAO_Off_Run_Ch0.count(*ic)   *
+	  calibBAO_Off_Run_Ch1.count(*ic)   *
+	  calibBAO_On_Cycle_Ch0.count(*ic)  *
+	  calibBAO_On_Cycle_Ch1.count(*ic)  *
+	  calibBAO_Off_Cycle_Ch0.count(*ic) *
+	  calibBAO_Off_Cycle_Ch1.count(*ic) ) != 0 ? true : false;
+
+      if(para.debuglev_>9) {
+	cout << "Calibration coefficients for cycle "<<*ic << endl; 
+	if (isCycleCalibrated) {
+	  cout << "Cycle calibrated " << endl;
+	  cout << "Off Run Ch0 " << calibBAO_Off_Run_Ch0[*ic] << " "
+	       << "Ch1 " << calibBAO_Off_Run_Ch1[*ic] << "\n"
+	       << "On Run Ch0 " << calibBAO_On_Run_Ch0[*ic] << " "
+	       << "Ch1 " << calibBAO_On_Run_Ch1[*ic] << "\n"
+	       << "Off Cycle Ch0 " << calibBAO_Off_Cycle_Ch0[*ic] << " "
+	       << "Ch1 " << calibBAO_Off_Cycle_Ch1[*ic] << "\n"
+	       << "On Cycle Ch0 " << calibBAO_On_Cycle_Ch0[*ic] << " "
+	       << "Ch1 " << calibBAO_On_Cycle_Ch1[*ic] << endl;
+	} else {
+	  cout << "Cycle NOT calibrated " << endl;
+	}
+      }//debug
+
+
+      if ( ! isCycleCalibrated ) continue;
+      
+      string ppftag;
+      //load ON phase
+      stringstream cycle;
+      cycle << *ic;
+      
+      ppftag = "specRawOn"+cycle.str();
+      TMatrix<r_4> aSpecOn(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ);
+      fin.GetObject(aSpecOn,ppftag);
+
+      TMatrix<r_4> aSpecOn_BAOCalibRun(aSpecOn,false);
+      aSpecOn_BAOCalibRun(Range(0),Range::all()) /= calibBAO_On_Run_Ch0[*ic];
+      aSpecOn_BAOCalibRun(Range(1),Range::all()) /= calibBAO_On_Run_Ch1[*ic];
+
+      TMatrix<r_4> aSpecOn_BAOCalibCycle(aSpecOn,false);
+      aSpecOn_BAOCalibCycle(Range(0),Range::all()) /= calibBAO_On_Cycle_Ch0[*ic];
+      aSpecOn_BAOCalibCycle(Range(1),Range::all()) /= calibBAO_On_Cycle_Ch1[*ic];
+      
+      ppftag = "specRawOff"+cycle.str();
+      TMatrix<r_4> aSpecOff(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ);
+      fin.GetObject(aSpecOff,ppftag);
+
+      TMatrix<r_4> aSpecOff_BAOCalibRun(aSpecOff,false);
+      aSpecOff_BAOCalibRun(Range(0),Range::all()) /= calibBAO_Off_Run_Ch0[*ic];
+      aSpecOff_BAOCalibRun(Range(1),Range::all()) /= calibBAO_Off_Run_Ch1[*ic];
+
+      TMatrix<r_4> aSpecOff_BAOCalibCycle(aSpecOff,false);
+      aSpecOff_BAOCalibCycle(Range(0),Range::all()) /= calibBAO_Off_Cycle_Ch0[*ic];
+      aSpecOff_BAOCalibCycle(Range(1),Range::all()) /= calibBAO_Off_Cycle_Ch1[*ic];
+
+
+      //Perform the difference ON-OFF with the different calibration options
+      TMatrix<r_4> diffOnOff_noCalib = aSpecOn - aSpecOff;
+      meanDiffONOFF_noCalib += diffOnOff_noCalib;
+      
+      //JEC 29/10/11 add ON-OFF/OFF
+      TMatrix<r_4> diffOnOffOvOff_noCalib(diffOnOff_noCalib,false); //do not share data
+      TMatrix<r_4> aSpecOffFitltered(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ);
+      sa_size_t halfWidth = 35; //number of freq. bin for the 1/2 width of the filtering window
+      medianFiltering(aSpecOff,halfWidth,aSpecOffFitltered);
+      
+      diffOnOffOvOff_noCalib.Div(aSpecOffFitltered); //division in place
+      meanDiffONOFFovOFF_noCalib += diffOnOffOvOff_noCalib;
+
+      TMatrix<r_4> diffOnOff_perRunCalib = aSpecOn_BAOCalibRun - aSpecOff_BAOCalibRun;
+      meanDiffONOFF_perRunCalib += diffOnOff_perRunCalib;
+
+      TMatrix<r_4> diffOnOff_perCycleCalib = aSpecOn_BAOCalibCycle - aSpecOff_BAOCalibCycle;
+      meanDiffONOFF_perCycleCalib += diffOnOff_perCycleCalib;
+
+      //
+      totalNumberCycles++;
+      //Fill NTuple
+      xnt[0] = totalNumberCycles;
+ 
+      //Follow up arround the Calibration Freq.
+      TVector<r_4> meanInRange_CalibFreq_noCalib(NUMBER_OF_CHANNELS);
+      meanInRange(diffOnOff_noCalib,chCalibLow,chCalibHigh,meanInRange_CalibFreq_noCalib);
+      xnt[1] = meanInRange_CalibFreq_noCalib(0);
+      xnt[2] = meanInRange_CalibFreq_noCalib(1);
+
+      TVector<r_4> meanInRange_CalibFreq_perRunCalib(NUMBER_OF_CHANNELS);
+      meanInRange(diffOnOff_perRunCalib,chCalibLow,chCalibHigh,meanInRange_CalibFreq_perRunCalib);
+      xnt[3] = meanInRange_CalibFreq_perRunCalib(0);
+      xnt[4] = meanInRange_CalibFreq_perRunCalib(1);
+
+      TVector<r_4> meanInRange_CalibFreq_perCycleCalib(NUMBER_OF_CHANNELS);
+      meanInRange(diffOnOff_perCycleCalib,chCalibLow,chCalibHigh,meanInRange_CalibFreq_perCycleCalib);
+      xnt[5] = meanInRange_CalibFreq_perCycleCalib(0);
+      xnt[6] = meanInRange_CalibFreq_perCycleCalib(1);
+
+
+      //Follow up arround the 1420.4MHz Freq.
+      TVector<r_4> meanInRange_1420Freq_noCalib(NUMBER_OF_CHANNELS);
+      meanInRange(diffOnOff_noCalib,ch1420Low,ch1420High,meanInRange_1420Freq_noCalib);
+      xnt[7] = meanInRange_1420Freq_noCalib(0);
+      xnt[8] = meanInRange_1420Freq_noCalib(1);
+
+      TVector<r_4> meanInRange_1420Freq_perRunCalib(NUMBER_OF_CHANNELS);
+      meanInRange(diffOnOff_perRunCalib,ch1420Low,ch1420High,meanInRange_1420Freq_perRunCalib);
+      xnt[9] = meanInRange_1420Freq_perRunCalib(0);
+      xnt[10] = meanInRange_1420Freq_perRunCalib(1);
+
+      TVector<r_4> meanInRange_1420Freq_perCycleCalib(NUMBER_OF_CHANNELS);
+      meanInRange(diffOnOff_perCycleCalib,ch1420Low,ch1420High,meanInRange_1420Freq_perCycleCalib);
+      xnt[11] = meanInRange_1420Freq_perCycleCalib(0);
+      xnt[12] = meanInRange_1420Freq_perCycleCalib(1);
+
+
+      //Follow up below the 1420.4MHz Freq.
+      TVector<r_4> meanInRange_1420aFreq_noCalib(NUMBER_OF_CHANNELS);
+      meanInRange(diffOnOff_noCalib,ch1420aLow,ch1420aHigh,meanInRange_1420aFreq_noCalib);
+      TVector<r_4> meanInRange_1420bFreq_noCalib(NUMBER_OF_CHANNELS);
+      meanInRange(diffOnOff_noCalib,ch1420bLow,ch1420bHigh,meanInRange_1420bFreq_noCalib);
+
+      xnt[13] = (meanInRange_1420aFreq_noCalib(0) + meanInRange_1420bFreq_noCalib(0))/2.;
+      xnt[14] = (meanInRange_1420aFreq_noCalib(1) + meanInRange_1420bFreq_noCalib(1))/2.;
+
+
+      TVector<r_4> meanInRange_1420aFreq_perRun(NUMBER_OF_CHANNELS);
+      meanInRange(diffOnOff_perRunCalib,ch1420aLow,ch1420aHigh,meanInRange_1420aFreq_perRun);
+      TVector<r_4> meanInRange_1420bFreq_perRun(NUMBER_OF_CHANNELS);
+      meanInRange(diffOnOff_perRunCalib,ch1420bLow,ch1420bHigh,meanInRange_1420bFreq_perRun);
+
+      xnt[15] = (meanInRange_1420aFreq_perRun(0) + meanInRange_1420bFreq_perRun(0))/2.;
+      xnt[16] = (meanInRange_1420aFreq_perRun(1) + meanInRange_1420bFreq_perRun(1))/2.;
+
+
+      TVector<r_4> meanInRange_1420aFreq_perCycle(NUMBER_OF_CHANNELS);
+      meanInRange(diffOnOff_perCycleCalib,ch1420aLow,ch1420aHigh,meanInRange_1420aFreq_perCycle);
+      TVector<r_4> meanInRange_1420bFreq_perCycle(NUMBER_OF_CHANNELS);
+      meanInRange(diffOnOff_perCycleCalib,ch1420bLow,ch1420bHigh,meanInRange_1420bFreq_perCycle);
+
+      xnt[17] = (meanInRange_1420aFreq_perCycle(0) + meanInRange_1420bFreq_perCycle(0))/2.;
+      xnt[18] = (meanInRange_1420aFreq_perCycle(1) + meanInRange_1420bFreq_perCycle(1))/2.;
+
+
+      //JEC 25/10/11 follow 1400-1420 MHz bande protege et n'inclue pas le 1420.4Mhz de la Galaxie
+      TVector<r_4> meanInRange_1400a1420Freq_noCalib(NUMBER_OF_CHANNELS);
+      meanInRange(diffOnOff_noCalib,ch1400,ch1420,meanInRange_1400a1420Freq_noCalib);
+      xnt[19] = meanInRange_1400a1420Freq_noCalib(0);
+      xnt[20] = meanInRange_1400a1420Freq_noCalib(1);
+      
+
+      
+      //store infos to Ntuple
+      onoffevolution.Fill(xnt);
+
+      //Quit if enough
+      if (totalNumberCycles >= para.maxNumberCycles_) break;	
+
+    }//eo loop on cycles
+    if (totalNumberCycles >= para.maxNumberCycles_) break;	    
+  
+  }//eo loop on spectra in a file
+  cout << "End of jobs: we have treated " << totalNumberCycles << " cycles" << endl;
+  //Normalisation
+  if(totalNumberCycles > 0){
+    //JEC 29/10 add ON-OFF/OFF
+    meanDiffONOFFovOFF_noCalib  /= (r_4)totalNumberCycles;
+    meanDiffONOFF_noCalib       /= (r_4)totalNumberCycles;
+    meanDiffONOFF_perRunCalib   /= (r_4)totalNumberCycles;
+    meanDiffONOFF_perCycleCalib /= (r_4)totalNumberCycles;
+  }  
+  
+  //Compute the reduced version of the mean and sigma
+  TMatrix<r_4> meanRedMtx_noCalib(NUMBER_OF_CHANNELS,para.nSliceInFreq_);
+  TMatrix<r_4> sigmaRedMtx_noCalib(NUMBER_OF_CHANNELS,para.nSliceInFreq_);
+  reduceSpectra(meanDiffONOFF_noCalib,meanRedMtx_noCalib,sigmaRedMtx_noCalib);
+
+  TMatrix<r_4> meanRedMtx_perRunCalib(NUMBER_OF_CHANNELS,para.nSliceInFreq_);
+  TMatrix<r_4> sigmaRedMtx_perRunCalib(NUMBER_OF_CHANNELS,para.nSliceInFreq_);
+  reduceSpectra(meanDiffONOFF_perRunCalib,meanRedMtx_perRunCalib,sigmaRedMtx_perRunCalib);
+
+  TMatrix<r_4> meanRedMtx_perCycleCalib(NUMBER_OF_CHANNELS,para.nSliceInFreq_);
+  TMatrix<r_4> sigmaRedMtx_perCycleCalib(NUMBER_OF_CHANNELS,para.nSliceInFreq_);
+  reduceSpectra(meanDiffONOFF_perCycleCalib,meanRedMtx_perCycleCalib,sigmaRedMtx_perCycleCalib);
+
+  {//save the results
+    stringstream tmp;
+    tmp << totalNumberCycles;
+    string fileName = para.outPath_+"/onoffsurvey_"+StringToLower(para.sourceName_)+"-"+tmp.str()+"Cycles.ppf";
+
+    POutPersist fos(fileName);
+    cout << "Save output in " << fileName << endl;
+
+    string tag = "meanNoCalib";
+    fos << PPFNameTag(tag) << meanDiffONOFF_noCalib;
+    
+    //JEC 29/10/11
+    tag = "meanOvOffNoCalib";
+    fos << PPFNameTag(tag) << meanDiffONOFFovOFF_noCalib;
+
+    tag = "meanPerRunCalib";
+    fos << PPFNameTag(tag) << meanDiffONOFF_perRunCalib;
+    tag = "meanPerCycleCalib";
+    fos << PPFNameTag(tag) << meanDiffONOFF_perCycleCalib;
+
+    tag = "redmeanNoCalib";
+    fos << PPFNameTag(tag) << meanRedMtx_noCalib;
+    tag = "redsigmaNoCalib";
+    fos << PPFNameTag(tag) << sigmaRedMtx_noCalib;
+
+    tag = "redmeanPerRunCalib";
+    fos << PPFNameTag(tag) << meanRedMtx_perRunCalib;
+    tag = "redsigmaPerRunCalib";
+    fos << PPFNameTag(tag) << sigmaRedMtx_perRunCalib;
+
+    tag = "redmeanPerCycleCalib";
+    fos << PPFNameTag(tag) << meanRedMtx_perCycleCalib;
+    tag = "redsigmaPerCycleCalib";
+    fos << PPFNameTag(tag) << sigmaRedMtx_perCycleCalib;
+    
+    tag = "onoffevol";
+    fos << PPFNameTag(tag) << onoffevolution;    
+  }//end of save
+}
+//-------------------------------------------------------
+//Compute the mean of Diff ON-OFF Raw spectra and also the mean/sigma of rebinned spectra 
+//Used like:
+//
+void meanRawDiffOnOffCycles() throw(string) {
+  list<string> listOfFiles;
+  string directoryName;
+  directoryName = para.inPath_ + "/" + para.sourceName_;
+
+  //Make the listing of the directory
+  listOfFiles = ListOfFileInDir(directoryName,para.ppfFile_);
+  
+  list<string>::const_iterator iFile, iFileEnd, iSpec, iSpecEnd;
+  iFileEnd = listOfFiles.end();
+  
+  StringMatch match("specONOFFRaw[0-9]+"); //Tag of the PPF objects
+  TMatrix<r_4> meanOfSpectra(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ);
+  uint_4 nSpectra=0;
+  //Loop on files
+  for (iFile = listOfFiles.begin(); iFile != iFileEnd; ++iFile) {
+    if (para.debuglev_>90){
+      cout << "load file <" << *iFile << ">" << endl;
+    }
+    PInPersist fin(*iFile);
+    vector<string> vec = fin.GetNameTags();
+    list<string> listOfSpectra;
+    //Keep only required PPF objects
+    std::remove_copy_if(
+			vec.begin(), vec.end(), back_inserter(listOfSpectra),
+			not1(match)
+			);
+   
+    listOfSpectra.sort(stringCompare);
+    iSpecEnd = listOfSpectra.end();
+    //Loop of spectra matrix
+    for (iSpec = listOfSpectra.begin(); iSpec !=iSpecEnd;  ++iSpec){
+      if (para.debuglev_>90){
+	cout << " spactra <" << *iSpec << ">" << endl;
+      }
+      TMatrix<r_4> aSpec(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ);
+      fin.GetObject(aSpec,*iSpec);
+      //How to see if the GetObject is ok?? Ask Reza
+      nSpectra++;
+      meanOfSpectra+=aSpec;
+    }//eo loop on spectra in a file
+  }//eo loop on files
+  
+  //Normalisation
+  if(nSpectra>0)meanOfSpectra/=(r_4)(nSpectra);
+
+  //Compute the reduced version of the mean and sigma
+  TMatrix<r_4> meanRedMtx(NUMBER_OF_CHANNELS,para.nSliceInFreq_);
+  TMatrix<r_4> sigmaRedMtx(NUMBER_OF_CHANNELS,para.nSliceInFreq_);
+  reduceSpectra(meanOfSpectra,meanRedMtx,sigmaRedMtx);
+
+  {//Save the result
+    stringstream tmp;
+    tmp << nSpectra;
+    string fileName = para.outPath_+"/meanDiffOnOffRaw_"+StringToLower(para.sourceName_)+"-"+tmp.str()+"Cycles.ppf";
+    cout << "Save mean based on " <<  nSpectra << " cycles " << endl;
+    POutPersist fos(fileName);
+
+    string tag = "mean";
+    fos << PPFNameTag(tag) << meanOfSpectra;
+    tag = "meanred";
+    fos << PPFNameTag(tag) << meanRedMtx;
+    tag = "sigmared";
+    fos << PPFNameTag(tag) << sigmaRedMtx;
+  }
+}
+//-------------------------------------------------------
+//Compute the median of Diff ON-OFF Raw spectra and also the mean/sigma of rebinned spectra 
+//Used like:
+//
+void medianRawDiffOnOffCycles() throw(string) {
+  list<string> listOfFiles;
+  string directoryName;
+  directoryName = para.inPath_ + "/" + para.sourceName_;
+
+  //Make the listing of the directory
+  listOfFiles = ListOfFileInDir(directoryName,para.ppfFile_);
+  
+  list<string>::const_iterator iFile, iFileEnd, iSpec, iSpecEnd;
+  iFileEnd = listOfFiles.end();
+  
+
+  TArray<r_4> tableOfSpectra(NUMBER_OF_FREQ,NUMBER_OF_CHANNELS,para.maxNumberCycles_); //para.maxNumberCycles_ should be large enough...
+
+  StringMatch match("specONOFFRaw[0-9]+"); //Tag of the PPF objects
+  uint_4 nSpectra=0;
+  //Loop on files
+  for (iFile = listOfFiles.begin(); iFile != iFileEnd; ++iFile) {
+    if (para.debuglev_>90){
+      cout << "load file <" << *iFile << ">" << endl;
+    }
+    PInPersist fin(*iFile);
+    vector<string> vec = fin.GetNameTags();
+    list<string> listOfSpectra;
+    //Keep only required PPF objects
+    std::remove_copy_if(
+			vec.begin(), vec.end(), back_inserter(listOfSpectra),
+			not1(match)
+			);
+   
+    listOfSpectra.sort(stringCompare);
+    iSpecEnd = listOfSpectra.end();
+    //Loop of spectra matrix
+    for (iSpec = listOfSpectra.begin(); iSpec !=iSpecEnd && (sa_size_t)nSpectra < para.maxNumberCycles_ ;  ++iSpec){
+      if (para.debuglev_>90){
+	cout << " spactra <" << *iSpec << ">" << endl;
+      }
+      TMatrix<r_4> aSpec(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ);
+      fin.GetObject(aSpec,*iSpec);
+
+      tableOfSpectra(Range::all(),Range::all(),Range(nSpectra)) = aSpec;
+
+      nSpectra++;
+    }//eo loop on spectra in a file
+  }//eo loop on files
+  
+
+ 
+  TMatrix<r_4> medianOfSpectra(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ);
+  //Compute the median for each freq. and Channel
+  for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS; iCh++){
+    for (sa_size_t freq =0; freq<NUMBER_OF_FREQ; freq++){
+      TVector<r_4> tmp0(tableOfSpectra(Range(freq),Range(iCh),Range(0,nSpectra-1)).CompactAllDimensions());
+      vector<r_4> tmp;
+      tmp0.FillTo(tmp);
+      medianOfSpectra(iCh,freq) = median(tmp.begin(),tmp.end());
+    }
+  }
+
+
+  //Compute the reduced version of the mean and sigma
+  TMatrix<r_4> meanRedMtx(NUMBER_OF_CHANNELS,para.nSliceInFreq_);
+  TMatrix<r_4> sigmaRedMtx(NUMBER_OF_CHANNELS,para.nSliceInFreq_);
+  reduceSpectra(medianOfSpectra,meanRedMtx,sigmaRedMtx);
+
+
+  sa_size_t f1320=freqToChan(1320.);
+  sa_size_t f1345=freqToChan(1345.);
+  sa_size_t f1355=freqToChan(1355.);
+  sa_size_t f1380=freqToChan(1380.);
+  //Compute baseline arround 1350Mhz on [1320-1345] U [1355-1380]
+  if (para.debuglev_>9){
+    cout << "Compute baseline arround 1350Mhz on [1320-1345] U [1355-1380]" << endl;
+  }
+  TVector<r_4>meanMed(NUMBER_OF_CHANNELS);
+  for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS; ++iCh){
+    double meanMed1;
+    double sigmaMed1;
+    TVector<r_4> band1;
+    band1 = medianOfSpectra(Range(iCh),Range(f1320,f1345)).CompactAllDimensions();
+    MeanSigma(band1,meanMed1,sigmaMed1);
+    double meanMed2;
+    double sigmaMed2;
+    TVector<r_4> band2;
+    band2 = medianOfSpectra(Range(iCh),Range(f1355,f1380)).CompactAllDimensions();
+    MeanSigma(band2,meanMed2,sigmaMed2);
+    meanMed(iCh) = (meanMed1+meanMed2)*0.5;
+  }  
+  meanMed.Print(cout);
+  cout << endl;
+
+  
+  //Compute the sigma in the range 1320MHz-1380MHz
+  if (para.debuglev_>9){
+    cout << "Compute the sigma in the range 1320MHz-1380MHz" << endl;
+  }
+  TVector<r_4>sigmaMed(NUMBER_OF_CHANNELS);
+  sa_size_t redf1320=(sa_size_t)((1320.0-LOWER_FREQUENCY)/TOTAL_BANDWIDTH*para.nSliceInFreq_);
+  sa_size_t redf1380=(sa_size_t)((1380.0-LOWER_FREQUENCY)/TOTAL_BANDWIDTH*para.nSliceInFreq_);
+
+  for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS; ++iCh){
+    double meanSigma;
+    double sigmaSigma;
+    TVector<r_4> band;
+    band = sigmaRedMtx(Range(iCh),Range(redf1320,redf1380)).CompactAllDimensions();
+    MeanSigma(band,meanSigma,sigmaSigma);
+    meanSigma *= sqrt(para.nSliceInFreq_); //to scale to orignal spectra
+    sigmaMed(iCh) = meanSigma;
+  }
+  sigmaMed.Print(cout);
+  cout << endl;
+
+  
+  
+  if (para.debuglev_>9){
+    cout << "Compute medianOfSpectraNorm" << endl;
+  }
+  TMatrix<r_4> medianOfSpectraNorm(medianOfSpectra,false); //do not share the data...
+  for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS; ++iCh){
+    medianOfSpectraNorm.Row(iCh) -= meanMed(iCh);
+    medianOfSpectraNorm.Row(iCh) /= sigmaMed(iCh);
+  }
+
+  
+
+  {//Save the result
+    stringstream tmp;
+    tmp << nSpectra;
+    string fileName = para.outPath_+"/medianDiffOnOffRaw_"+StringToLower(para.sourceName_)+"-"+tmp.str()+"Cycles.ppf";
+    cout << "Save median based on " <<  nSpectra << " cycles " << endl;
+    POutPersist fos(fileName);
+
+    string tag = "median";
+    fos << PPFNameTag(tag) << medianOfSpectra;
+
+    tag = "medianNorm";
+    fos << PPFNameTag(tag) << medianOfSpectraNorm;
+    
+
+    tag = "meanmedred";
+    fos << PPFNameTag(tag) << meanRedMtx;
+    tag = "sigmamedred";
+    fos << PPFNameTag(tag) << sigmaRedMtx;
+    tag = "cycleVsfreq";
+    
+    TArray<r_4> tarr(tableOfSpectra(Range::all(),Range::all(),Range(0,nSpectra-1)));
+    fos << PPFNameTag(tag) << tarr;
+  }
+}
+
+//-------------------------------------------------------
+int main(int narg, char* arg[]) {
+  
+  int rc = 0; //return code
+  string msg; //message used in Exceptions
+
+
+
+  //default value for initial parameters (see Para structure on top of the file)
+  string debuglev = "0";
+  string action = "meanDiffOnOff";
+  string inputPath = "."; 
+  string outputPath = "."; 
+  string sourceName = "Abell85";
+  string ppfFile;
+  string nSliceInFreq = "32";
+  string typeOfCalib="perRun";
+  string calibFreq = "1346";
+  string calibBandFreq="6.25";
+  string mxcycles;
+
+  //  bool okarg=false;
+  int ka=1;
+  while (ka<narg) {
+    if (strcmp(arg[ka],"-h")==0) {
+      cout << "Usage:  -act [meanRawDiffOnOff]|medianRawDiffOnOff|meanCalibBAODiffOnOff\n"
+	   << " -mxcycles <number> (max. number of cycles to be treated)\n"
+	   << " -calibfreq <number> (cf. freq. used by calibration operation)\n"
+	   << " -calibbandfreq <number> (cf. band of freq. used by calibration operation)\n"
+	   << " -src [Abell85]\n" 
+	   << " -inPath [.]|<top_root_dir of the ppf file>\n" 
+	   << " (ex. /sps/baoradio/AmasNancay/JEC/\n " 
+	   << " -outPath [.]|<dir of the output> \n"
+	   << " -nSliceInFreq [32]|<number of bin in freq. to cumulate>\n"
+	   << " -ppfFile <generic name of the input ppf files> (ex. diffOnOffRaw)\n"
+	   << " -debug <level> "
+	   << endl;
+      return 0;
+    }
+    else if (strcmp(arg[ka],"-debug")==0) {
+      debuglev=arg[ka+1];
+      ka+=2;
+    }
+    else if (strcmp(arg[ka],"-act")==0) {
+      action=arg[ka+1];
+      ka+=2;
+    }
+    else if (strcmp(arg[ka],"-calibfreq")==0) {
+      calibFreq=arg[ka+1];
+      ka+=2;
+    }    
+    else if (strcmp(arg[ka],"-calibbandfreq")==0) {
+      calibBandFreq=arg[ka+1];
+      ka+=2;
+    }    
+    else if (strcmp(arg[ka],"-mxcycles")==0) {
+      mxcycles=arg[ka+1];
+      ka+=2;
+    }    
+    else if (strcmp(arg[ka],"-inPath")==0) {
+      inputPath=arg[ka+1];
+      ka+=2;
+    }
+    else if (strcmp(arg[ka],"-outPath")==0) {
+      outputPath=arg[ka+1];
+      ka+=2;
+    }
+    else if (strcmp(arg[ka],"-src")==0) {
+      sourceName=arg[ka+1];
+      ka+=2;
+    }
+    else if (strcmp(arg[ka],"-ppfFile")==0) {
+      ppfFile=arg[ka+1];
+      ka+=2;
+    }
+    else if (strcmp(arg[ka],"-nSliceInFreq")==0) {
+      nSliceInFreq=arg[ka+1];
+      ka+=2;
+    }
+    else ka++;
+  }//eo while
+
+  para.debuglev_   = atoi(debuglev.c_str());
+  para.inPath_     = inputPath;
+  para.outPath_    = outputPath;
+  para.sourceName_ = sourceName;
+  para.ppfFile_    = ppfFile;
+  para.nSliceInFreq_ = atoi(nSliceInFreq.c_str());
+  para.calibFreq_   = calibFreq;
+  para.calibBandFreq_ = calibBandFreq;
+  para.rcalibFreq_   = atof(calibFreq.c_str());
+  para.rcalibBandFreq_ = atof(calibBandFreq.c_str());
+  if (mxcycles != "") {
+    para.maxNumberCycles_ = atoi(mxcycles.c_str());
+  } else {
+    para.maxNumberCycles_ = std::numeric_limits<int>::max();
+  }
+
+  cout << "Dump Initial parameters ............" << endl;
+  cout << " action = " << action << "\n"
+       << " maxNumberCycles = " << para.maxNumberCycles_ << "\n"
+       << " inputPath = " << para.inPath_  << "\n" 
+       << " outputPath = " <<  para.outPath_ << "\n"
+       << " sourceName = " << para.sourceName_ << "\n"
+       << " ppfFile = " <<  para.ppfFile_ << "\n"
+       << " nSliceInFreq = " << para.nSliceInFreq_  << "\n"
+       << " calibFreq = " <<  para.calibFreq_ << "\n"
+       << " calibBandFreq = " <<  para.calibBandFreq_ << "\n"
+       << " debuglev = "  << para.debuglev_   << "\n";
+  cout << "...................................." << endl;
+
+  if ( "" == ppfFile ) {
+    cerr << "mergeAnaFiles.cc: you have forgotten ppfFile option"
+	 << endl;
+    return 999;
+  }
+
+
+  try {
+
+//     int b,e;
+//     char *match=regexp("truc0machin","[a-z]+[0-9]*",&b,&e);
+//     printf("->%s<-\n(b=%d e=%d)\n",match,b,e);
+
+    if ( action == "meanRawDiffOnOff" ) {
+      meanRawDiffOnOffCycles();
+    } else if (action == "medianRawDiffOnOff") {
+      medianRawDiffOnOffCycles();
+    } else if (action == "meanCalibBAODiffOnOff") {
+      meanCalibBAODiffOnOffCycles();
+    } else {
+      msg = "Unknown action " + action;
+      throw msg;
+    }
+
+
+  }  catch (std::exception& sex) {
+    cerr << "mergeRawOnOff.cc std::exception :"  << (string)typeid(sex).name() 
+	 << "\n msg= " << sex.what() << endl;
+    rc = 78;
+  }
+  catch ( string str ) {
+    cerr << "mergeRawOnOff.cc Exception raised: " << str << endl;
+  }
+  catch (...) {
+    cerr << "mergeRawOnOff.cc catched unknown (...) exception  " << endl; 
+    rc = 79; 
+  } 
+
+  return 0;
+
+}
Index: /BAORadio/AmasNancay/v5/mergeRawOnOff.pic
===================================================================
--- /BAORadio/AmasNancay/v5/mergeRawOnOff.pic	(revision 596)
+++ /BAORadio/AmasNancay/v5/mergeRawOnOff.pic	(revision 596)
@@ -0,0 +1,93 @@
+defscript sumSpec
+
+set source "Abell${1}"
+set srclower "abell${1}"
+set date $2
+# implicitement firstcycle =1
+set lastcycle $3
+lastP1cycle = ${lastcycle}+1
+
+openppf ${toppath}/${source}/${date}${srclower}/diffOnOffRaw_${date}_${srclower}.ppf
+
+#specONOFFRaw<i>       Matrix 2 x 8192 : i=0...
+
+for ic 1:${lastP1cycle}
+    del sOnOffv0
+    del sOnOffv1
+    objaoper specONOFFRaw${ic} row 0 sOnOffv0	
+    objaoper specONOFFRaw${ic} row 1 sOnOffv1	
+    c++exec specONOFFv0+=sOnOffv0; specONOFFv1+=sOnOffv1;
+end
+
+
+endscript
+
+
+########################################################################
+#MAIN
+########################################################################
+set cols ( blue red black green purple orange cyan violet yellow )
+
+set toppath "."
+set source "Abell${1}"
+set srclower "abell${1}"
+
+#The output spectra 
+#newvec specONOFFv0 8192
+#newvec specONOFFv1 8192
+
+c++exec TVector<r_4> specONOFFv0(8192,2); TVector<r_4> specONOFFv1(8192,2); \
+	KeepObj(specONOFFv0);KeepObj(specONOFFv1);
+
+#set the runs to merge
+
+set dateTag ( 20110507 20110602 20110729 20110806 )
+set nCycles ( 24 14 27 26 )
+line2vec tmpvec $nCycles
+
+#do It
+for i 0:${tmpvec.size}
+  sumSpec 85 $dateTag[i] $nCycles[i]
+end
+c++exec specONOFFv0/=tmpvec.Sum(); specONOFFv1/=tmpvec.Sum();
+
+
+#########
+newwin 1 1
+graphicatt "xylimits=1250,1500,-0.01,0.01"
+plot2d   specONOFFv0    (n/8192)*250+1250 val n>0 "same blue cpts nsta notit"
+plot2d   specONOFFv1    (n/8192)*250+1250 val n>0 "same red cpts nsta notit"
+settitle "ON-OFF  ${source} Ch 0 (blue) Ch 1 (red) ${tmpvec.sum} cycles"
+setaxelabels "Freq. (MHz)" "I (a.u)"
+
+#########
+#Perform the frequancy rebinning to compute MEAN & SIGMA
+#########
+c++compile reducing        
+c++link reducing.so doreduc
+
+cp specONOFFv0 specv0
+cp specONOFFv1 specv1
+call doreduc
+
+newwin 1 1
+graphicatt "xylimits=1250,1500,-0.01,0.01"
+ del redMeanv0                                                                      
+ del redMeanv1                                                                      
+ objaoper reducedMeanDiffOnOff row 0 redMeanv0                                      
+ objaoper reducedMeanDiffOnOff row 1 redMeanv1                                      
+ plot2d redMeanv0 (n/32)*250+1250 val n>0 "blue marker=fcircle,7 nsta notit"        
+ plot2d redMeanv1 (n/32)*250+1250 val n>0 "same red marker=fcircle,7 nsta notit"
+settitle "ON-OFF  ${source} Ch 0 (blue) Ch 1 (red) ${tmpvec.sum} cycles"
+setaxelabels "Freq. (MHz)" "I (a.u)"
+
+newwin 1 1
+graphicatt "xylimits=1250,1500,0,0.001"
+ del redSigmav0                                                                      
+ del redSigmav1                                                                      
+ objaoper reducedSigmaDiffOnOff row 0 redSigmav0                                      
+ objaoper reducedSigmaDiffOnOff row 1 redSigmav1                                      
+ plot2d redSigmav0 (n/32)*250+1250 val n>0 "blue marker=fcircle,7 nsta notit"        
+ plot2d redSigmav1 (n/32)*250+1250 val n>0 "same red marker=fcircle,7 nsta notit"
+settitle "ON-OFF  ${source} Ch 0 (blue) Ch 1 (red) ${tmpvec.sum} cycles"
+setaxelabels "Freq. (MHz)" "I (a.u)"
Index: /BAORadio/AmasNancay/v5/mkarchive.sh
===================================================================
--- /BAORadio/AmasNancay/v5/mkarchive.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/mkarchive.sh	(revision 596)
@@ -0,0 +1,184 @@
+#!/bin/sh
+#make an archive of the processing
+DATE=/bin/date
+GREP=/bin/grep
+AWK=/bin/awk
+ECHO=/bin/echo
+WC=/usr/bin/wc
+CAT=/bin/cat
+PRINTF=/usr/bin/printf
+FIND=/usr/bin/find
+MKDIR=/bin/mkdir
+XARGS=/usr/bin/xargs
+SORT=/bin/sort
+RM=/bin/rm
+TR=/usr/bin/tr
+CP=/bin/cp
+LS=/bin/ls
+CHMOD=/bin/chmod
+
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+#set Irods environment    
+. /usr/local/shared/bin/irods_env.sh -noverbose
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+#which source to analyse
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+dateSelected=
+prependTag=""
+appendTag=""
+simulationMode=Off
+mvgain=No
+while [ $# -gt 0 ]
+  do
+  case "$1" in
+      -src)  sourceRadio=$2;    shift;;
+      -date) dateSelected=$2;     shift;;
+      -ppTag) prependTag=$2; shift;;
+      -apTag) appendTag=$2; shift;;
+      -sim)  simulationMode=On;;
+      -all)  mvgain=Yes;;
+      -h)
+      echo >&2 \
+	  "usage: $0 -src souce -date YYYYMMDD -ppTag <tag> -apTag <tag>  [-sim to trig simulation mode]"
+      exit 1;;
+      *)  break;;	# terminate while loop
+  esac
+  shift
+done
+
+
+if [ ${simulationMode} = "On" ]; then
+    $ECHO "INFO ${scriptName} running in SIMUL mode"
+fi
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+if [ "<${prependTag}>" = "<>" -a "<${appendTag}>" = "<>"  ]; then
+    $ECHO "FATAL: choose either a prepend Tag or a append Tag"
+    exit
+fi
+
+
+case ${sourceRadio} in
+    Abell85) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    Abell2440) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    Abell1205) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    *) ECHO "FATAL (${scriptName}): process ${sourceRadio} not yet foreseen"
+    exit 1;;
+esac
+
+srclower=`${ECHO} ${sourceRadio} | ${TR} "[:upper:]" "[:lower:]" `
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+#wakeup the NFS disk
+$LS -l ${tmppublicpath} > /dev/null
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+localpath="${sourceRadio}"
+$MKDIR -p ./${localpath}
+cd ./${localpath}
+
+
+#Path of the utility scripts
+scriptpath=${SCRIPTPATH}
+
+OUT1=${publicpath}/baodaqstatus-current.txt
+if [ ! -e ${OUT1}  -o ! -r ${OUT1} ]; then
+    $ECHO "FATAL (${scriptName}): ${OUT1} has a problem"
+    exit 1
+fi
+
+
+
+$ECHO "You have selected sourceRadio = ${sourceRadio} [date = ${dateSelected}]"
+tableau=( `$GREP -i "${dateSelected}${srclower}" ${OUT1} | $AWK '( NF==4 ) { print $2 }' ` )
+IFS='
+' 
+tableau=( $( $PRINTF "%s\n" "${tableau[@]}" | $AWK 'x[$0]++ == 0' ) )
+IFS=$DefaultIFS
+
+$ECHO "We are in directory `pwd`"
+
+for i in ${tableau[@]}
+  do
+#
+  
+  $ECHO "DEBUG: (${scriptName}) irods root dir $i"
+
+  
+
+  #make a new archive directory
+  archiveDir=${prependTag}Arch${appendTag}
+
+  archExist=`ils ${i} 2>&1 | $GREP -i ".*C-.*${archiveDir}"| $WC -l`
+  if [ ${archExist} -gt 0 ]; then
+      $ECHO "FATAL: ${archiveDir} already exit in ${i}"
+      exit 1
+  fi
+
+  imkdir -v ${i}/${archiveDir}
+  
+  #Move the Off and On directory
+  imv -v ${i}/Off ${i}/${archiveDir}/Off
+  imv -v ${i}/On ${i}/${archiveDir}/On
+  
+  #recreate On and Off directories
+  imkdir -v ${i}/Off 
+  imkdir -v ${i}/On
+ 
+  #mv the fichiers de calibrations BAO
+  calibfiles=( `ils ${i} 2>&1 | $GREP -i "calib_.*\.txt" ` )
+  IFS='
+' 
+  calibfiles=( $( $PRINTF "%s\n" "${calibfiles[@]}" | $AWK 'x[$0]++ == 0' )  )
+  IFS=$DefaultIFS
+
+  for j in ${calibfiles[@]}
+    do
+    file=`$ECHO $j`
+    imv -v ${i}/${file} ${i}/${archiveDir}/${file}
+  done
+  
+  #mv the ppf files
+  ppffiles=( `ils ${i} 2>&1 | $GREP -i ".*\.ppf" ` )
+  IFS='
+' 
+  ppffiles=( $( $PRINTF "%s\n" "${ppffiles[@]}" | $AWK 'x[$0]++ == 0' )  )
+  IFS=$DefaultIFS
+
+  for j in ${ppffiles[@]}
+    do
+    file=`$ECHO $j`
+    imv -v ${i}/${file} ${i}/${archiveDir}/${file}
+  done
+
+  #save the gain file
+  gainfile=`ils ${i} 2>&1 | $GREP -i "gain.*\.fits"`
+  file=`$ECHO ${gainfile}`
+  if [ "<${mvgain}>" = "<No>" ]; then
+      icp -v ${i}/${file} ${i}/${archiveDir}/${file}
+  else
+      imv -v ${i}/${file} ${i}/${archiveDir}/${file}
+  fi
+
+done
+
+exit 0
Index: /BAORadio/AmasNancay/v5/onoffmaker.sh
===================================================================
--- /BAORadio/AmasNancay/v5/onoffmaker.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/onoffmaker.sh	(revision 596)
@@ -0,0 +1,460 @@
+#!/bin/sh -xvf
+#Perform the ON-OFF analysis
+DATE=/bin/date
+GREP=/bin/grep
+AWK=/bin/awk
+ECHO=/bin/echo
+WC=/usr/bin/wc
+CAT=/bin/cat
+PRINTF=/usr/bin/printf
+FIND=/usr/bin/find
+MKDIR=/bin/mkdir
+XARGS=/usr/bin/xargs
+SORT=/bin/sort
+RM=/bin/rm
+TR=/usr/bin/tr
+CP=/bin/cp
+LS=/bin/ls
+CHMOD=/bin/chmod
+
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+#set Irods environment    
+. /usr/local/shared/bin/irods_env.sh -noverbose
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+#which source to analyse
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+dateSelected=
+freqBAOCalib=1346
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=Off
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -src)  sourceRadio=$2;    shift;;
+      -date) dateSelected=$2;     shift;;
+      -freq) freqBAOCalib=$2;   shift;;
+      -sim)  simulationMode=On;;
+	-h)
+	    echo >&2 \
+	    "usage: $0 -src souce -date YYYYMMDD [-freq freq in MHz (default ${freqBAOCalib})] [-sim to trig simulation mode]"
+	    exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+if [ ${simulationMode} = "On" ]; then
+    $ECHO "INFO ${scriptName} running in SIMUL mode"
+fi
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+case ${sourceRadio} in
+    Abell85) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    Abell2440) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    Abell1205) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    *) ECHO "FATAL (${scriptName}): process ${sourceRadio} not yet foreseen"
+    exit 1;;
+esac
+
+srclower=`${ECHO} ${sourceRadio} | ${TR} "[:upper:]" "[:lower:]" `
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+#wakeup the NFS disk
+$LS -l ${tmppublicpath} > /dev/null
+#clean previous spurious files
+$RM -f ${tmppublicpath}/*.finished
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/isInteractive.sh
+isInteractive=$(isInteractive)
+if [ ${isInteractive} == "1" ]; then
+  $ECHO "Usage in INTERACTIVE may be destructive... To be used with great care !!!!"
+   exit 0;
+fi
+
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+localpath="${sourceRadio}"
+$MKDIR -p ./${localpath}
+cd ./${localpath}
+
+#save the top directory
+topDir=`pwd`
+
+#Path of the utility scripts
+scriptpath=${SCRIPTPATH}
+
+#JEC 1/10/11 Use generic baodaqstatus name 
+#get the daq current irod status
+#tag=`${DATE} +%F`
+#OUT1=${publicpath}/baodaqstatus-${tag}.txt
+OUT1=${publicpath}/baodaqstatus-current.txt
+
+if [ ! -e ${OUT1}  -o ! -r ${OUT1} ]; then
+    $ECHO "FATAL (${scriptName}): ${OUT1} has a problem"
+    exit 1
+#    $ECHO "We should bring the DAQ status more up to date, this take 1 or 2sec..."
+#    $RM -f ${tmppublicpath}/statusdaq.finished
+#    ${scriptpath}/statusdaq.sh > ${OUT1}
+#    while [ ! -f "${tmppublicpath}/statusdaq.finished" ]; do
+#	sleep 30
+#    done
+#    $RM ${tmppublicpath}/statusdaq.finished
+#protect against remove/rewriting    
+#    $CHMOD -v 444 ${OUT1} 
+fi
+
+
+#Nb: if we want to implement a loop on sources we have to take care of srclower...
+
+$ECHO "You have selected sourceRadio = ${sourceRadio} [date = ${dateSelected}]"
+tableau=( `$GREP -i "${dateSelected}${srclower}" ${OUT1} | $AWK '( NF==4 ) { print $2 }' ` )
+IFS='
+' 
+tableau=( $( $PRINTF "%s\n" "${tableau[@]}" | $AWK 'x[$0]++ == 0' ) )
+IFS=$DefaultIFS
+
+
+for i in ${tableau[@]}
+  do
+#
+# start a "fresh" session  
+  cd ${topDir}
+  $LS | $XARGS -i $RM -rf {}
+  
+  $ECHO "DEBUG: (${scriptName}) irods root dir $i"
+  dateDAQ=`$ECHO ${i} | $AWK '{split($0,a,"/"); print a[6];}' | $AWK "{sub(/${srclower}/,\"\"); print}"`
+
+  $ECHO "DEBUG: (${scriptName}): we are in directory `pwd` the topDir=${topDir}"
+  $LS -lrt
+
+
+#JEC 1/10/11 Use generic baodaqstatus name 
+#Look if the date has changed since beginning of the job!
+#  curtag=`${DATE} +%F`
+#  if [ "<${curtag}>" != "<${tag}>" ]; then
+#      tag=${curtag}
+#it is necessary to update the daq status as the day has changed during the processing... (batch can take a long time...)
+#      OUT1=${publicpath}/baodaqstatus-${curtag}.txt
+#      $ECHO "We should bring the DAQ status more up to date, this take 1 or 2sec..."
+#      $RM -f ${tmppublicpath}/statusdaq.finished
+#      ${scriptpath}/statusdaq.sh > ${OUT1}
+#      while [ ! -f "${tmppublicpath}/statusdaq.finished" ]; do
+#	  sleep 30
+#      done
+#      $RM ${tmppublicpath}/statusdaq.finished
+#protect against remove/rewriting    
+#      $CHMOD -v 444 ${OUT1} 
+#  fi
+#
+# look if the gain & calibration files exist
+#
+  gainDone=`ils ${i} 2>&1 | $GREP -i "gain_.*\.fits" | $WC -l`
+  if [ ! ${gainDone} -gt 0 ]; then
+      $ECHO "FATAL (${scriptName}): gain file DOES NOT exist skip `basename $i` "
+      continue
+  fi
+
+  calibDone=`ils ${i} 2>&1 | $GREP -i "calib_.*\.txt" | $WC -l`
+  if [ ! ${calibDone} -gt 0 ]; then
+      $ECHO "FATAL (${scriptName}): calibration files DO NOT exist skip `basename $i` "
+      continue
+  fi
+#
+  somethingTodo=1
+  input4dataOff=`ils ${i}/Off 2>&1 | $GREP -i "datacycle" | $AWK 'BEGIN{FS="C- "}{print $2}' | $XARGS -i basename {} | $SORT -k1.10n`  
+  input4dataOn=`ils ${i}/On 2>&1 | $GREP -i "datacycle" | $AWK 'BEGIN{FS="C- "}{print $2}' | $XARGS -i basename {} | $SORT -k1.10n`  
+#
+  if [ "<${input4dataOff}>" != "<>" -a "<${input4dataOn}>" != "<>"  ]; then
+#look at the content of the datacycle directory as may be the previous batch job has crashed
+      tableauOff=( `$ECHO ${input4dataOff}` )
+      IFS='
+'
+      tableauOff=( $( $PRINTF "%s\n" "${tableauOff[@]}" | $AWK 'x[$0]++ == 0' ) )
+      IFS=$DefaultIFS
+#
+      nTotFilesOff=0
+      for j in ${tableauOff[@]}
+	do
+	nFiles=`ils ${i}/Off/${j} | $GREP -i "medfiltmtx" | $WC -l`
+	nTotFilesOff=`expr ${nTotFilesOff} + ${nFiles}`
+      done
+#
+      tableauOn=( `$ECHO ${input4dataOn}` )
+      IFS='
+      '
+      tableauOn=( $( $PRINTF "%s\n" "${tableauOn[@]}" | $AWK 'x[$0]++ == 0' ) )
+      IFS=$DefaultIFS
+#
+      nTotFilesOn=0
+      for j in ${tableauOn[@]}
+	do
+	nFiles=`ils ${i}/On/${j} | $GREP -i "medfiltmtx" | $WC -l`
+	nTotFilesOn=`expr ${nTotFilesOn} + ${nFiles}`
+      done
+      diffOnOff=`expr ${nTotFilesOff} - ${nTotFilesOn}`
+      if [ ${diffOnOff} -lt 0 ]; then
+	  zero=0
+	  diffOnOff=`expr ${zero} - ${diffOnOff}` 
+      fi
+#allow files differences
+      if [  ${nTotFilesOff} -gt 0 -a ${nTotFilesOn} -gt 0  ]; then
+	  somethingTodo=0
+	  $ECHO "DEBUG (${scriptName}): $sourceRadio $dateDAQ has <${nTotFilesOff}> Off-files and <${nTotFilesOn}> On-files but OK"
+      else
+	  $ECHO "INFO (${scriptName}): $sourceRadio $dateDAQ has <${nTotFilesOff}> Off-files and <${nTotFilesOn}> On-files => one should rebuild has something is wrong"
+      fi
+# 
+  fi 
+  if [ ${somethingTodo} -eq 1 ]; then
+#
+      $ECHO ">>>>>>>>>>>>>>>> Do $sourceRadio $dateDAQ ANALOFF"
+      $RM -f ${tmppublicpath}/proc_script.finished
+      if [ ${simulationMode} = "On" ]; then
+	  $ECHO "SIMUL: ${scriptpath}/proc_script.sh $sourceRadio $dateDAQ OFF"
+      else
+	  ${scriptpath}/proc_script.sh $sourceRadio $dateDAQ OFF
+	  while [ ! -e "${tmppublicpath}/proc_script.finished"  ]; do
+	      $ECHO "INFO (${scriptName}): waiting for ${tmppublicpath}/proc_script.finished"
+	      date +%T
+	      sleep 60
+	  done
+      fi
+      $ECHO "INFO (${scriptName}): proc_script has finished"
+      $ECHO ">>>>>>>>>>>> Done $sourceRadio $dateDAQ OFF"
+      $ECHO ">>>>>>>>>>>>>>>> Do $sourceRadio $dateDAQ ON"
+      $RM ${tmppublicpath}/proc_script.finished
+      
+      if [ ${simulationMode} = "On" ]; then
+	  $ECHO "SIMUL: ${scriptpath}/proc_script.sh $sourceRadio $dateDAQ ON"
+      else
+	  ${scriptpath}/proc_script.sh $sourceRadio $dateDAQ ON
+	  while [ ! -e "${tmppublicpath}/proc_script.finished"  ]; do
+	      $ECHO "INFO (${scriptName}): waiting for ${tmppublicpath}/proc_script.finished"
+	      date +%T
+	      sleep 60
+	  done
+      fi
+      $ECHO "INFO (${scriptName}): proc_script has finished"
+      $RM ${tmppublicpath}/proc_script.finished
+#Todo see if there is errors in the log file before copy
+      $ECHO ">>>>>>>>>>>> Done $sourceRadio $dateDAQ ON"
+######
+  else
+######
+      $ECHO ">>>>>>>>>>>>> ANALYSIS Part of ${sourceRadio} ${dateDAQ}"
+      #go to the .../source/date-sourcelowercase directory
+#download Off/datacycle<> and On/datacycle<> directories
+      $MKDIR -p ${topDir}/${dateDAQ}${srclower}
+      cd ${topDir}/${dateDAQ}${srclower}
+      aboveOnOffDir=`pwd`
+      $ECHO "DEBUG (${scriptName}): we are in directory: <`pwd`>"
+#
+      mode="Off"
+      $ECHO "DEBUG (${scriptName}): START download the ${mode} data fits files"
+      inFileDirectory="./${mode}"
+      $MKDIR -p ${inFileDirectory}
+      listOfDataCycle=( `ils ${i}/${mode} 2>&1 | $GREP -i "datacycle"|$AWK 'BEGIN{FS="C- "}{print $2}' | $XARGS -i basename {} | $SORT -k1.10n` )
+      IFS='
+'
+      listOfDataCycle=( $( $PRINTF "%s\n" "${listOfDataCycle[@]}" | $AWK 'x[$0]++ == 0' ) )
+      IFS=$DefaultIFS
+
+      firstCycleOff=`$ECHO ${listOfDataCycle[0]} | $AWK '{match($0,"[0-9]+",arr); print arr[0]}'`
+      nCyclesOff=`expr ${#listOfDataCycle[*]} - 1`
+
+      lastCycleOff=`$ECHO ${listOfDataCycle[${nCyclesOff}]} | $AWK '{match($0,"[0-9]+",arr); print arr[0]}'`
+
+      listOfDataCycle=( "${listOfDataCycle[@]/#/${i}/${mode}/}" )
+
+      
+      for j in ${listOfDataCycle[@]}
+	do
+	irodsDownDir="${j}"
+	OUT=./getInFits.$$
+	iget -r -f -K ${irodsDownDir} ${inFileDirectory} > ${OUT} 2>&1
+	igetStatus=`$GREP "^ERROR" ${OUT}`
+	if [ "<$igetStatus>" != "<>" ]; then
+	    $ECHO "FATAL (${scriptName}): error while iget fits files:"
+	    $ECHO $igetStatus
+	    $ECHO " ==> skip this run $sourceRadio $dateDAQ"
+	    continue
+	fi
+	$RM -f ${OUT}
+      done
+      $ECHO "DEBUG (${scriptName}): END download the ${mode} data fits files"
+#
+      mode="On"
+      $ECHO "DEBUG (${scriptName}): START download the ${mode} data fits files"
+      inFileDirectory="./${mode}"
+      $MKDIR -p ${inFileDirectory}
+
+      listOfDataCycle=( `ils ${i}/${mode} 2>&1 | $GREP -i "datacycle" |$AWK 'BEGIN{FS="C- "}{print $2}' | $XARGS -i basename {} | $SORT -k1.10n` )
+      IFS='
+'
+      listOfDataCycle=( $( $PRINTF "%s\n" "${listOfDataCycle[@]}" | $AWK 'x[$0]++ == 0' ) )
+      IFS=$DefaultIFS
+
+      firstCycleOn=`$ECHO ${listOfDataCycle[0]} | $AWK '{match($0,"[0-9]+",arr); print arr[0]}'`
+      nCyclesOn=`expr ${#listOfDataCycle[*]} - 1`
+
+      lastCycleOn=`$ECHO ${listOfDataCycle[${nCyclesOn}]} | $AWK '{match($0,"[0-9]+",arr); print arr[0]}'`
+
+      listOfDataCycle=( "${listOfDataCycle[@]/#/${i}/${mode}/}" )
+
+
+#
+#Check if there is the same number of cycles in Off and On mode
+#      
+#first cycle = max(firstCycleOn, firstCycleOff)
+#last  cycle = min(lastCycleOn,lastCycleOff)
+
+      if [ ${firstCycleOn} -eq ${firstCycleOff} -a ${lastCycleOn} -eq ${lastCycleOff} ]; then
+	  firstCycle=${firstCycleOff}
+	  lastCycle=${lastCycleOff}
+      else
+	  $ECHO "INFO (${scriptName}): missmatch between Off and On mode"
+	  $ECHO "${firstCycleOn} != ${firstCycleOff} OR ${lastCycleOn} != ${lastCycleOff}"
+	  firstCycle=${firstCycleOff}
+	  if [ ${firstCycleOn} -gt ${firstCycle} ]; then
+	      firstCycle=${firstCycleOn}
+	  fi
+	  lastCycle=${lastCycleOff}
+	  if [ ${lastCycleOn} -lt ${lastCycle} ]; then
+	      lastCycle=${lastCycleOn}
+	  fi
+      fi
+      $ECHO "INFO (${scriptName}): use cycles [${firstCycle}, ${lastCycle}]"
+      
+
+      for j in ${listOfDataCycle[@]}
+	do
+	irodsDownDir="${j}"
+	OUT=./getInFits.$$
+	iget -r -f -K ${irodsDownDir} ${inFileDirectory} > ${OUT} 2>&1
+	igetStatus=`$GREP "^ERROR" ${OUT}`
+	if [ "<$igetStatus>" != "<>" ]; then
+	    $ECHO "FATAL (${scriptName}): error while iget fits files:"
+	    $ECHO $igetStatus
+	    $ECHO " ==> skip this run $sourceRadio $dateDAQ"
+	    continue
+	fi
+	$RM -f ${OUT}
+      done
+      $ECHO "DEBUG (${scriptName}): END download the ${mode} data fits files"
+#Get sca file
+      $ECHO "DEBUG (${scriptName}): START call getscafiles.sh ${sourceRadio} ${dateDAQ}"
+      OUT1=./getScaStatus.$$
+      $RM -f ${tmppublicpath}/getscafiles.finished
+      ${scriptpath}/getscafiles.sh ${sourceRadio} ${dateDAQ} > ${OUT1} 2>&1
+      while [ ! -f "${tmppublicpath}/getscafiles.finished" ]; do
+	  $ECHO "INFO (${scriptName}): waiting for ${tmppublicpath}/getscafiles.finished"
+	  date +%T
+	  sleep 30
+      done
+      $RM ${tmppublicpath}/getscafiles.finished
+      $ECHO "DEBUG (${scriptName}): END"
+#
+      getScaStatus=`$GREP "^\(FATAL\|ERROR\)" ${OUT1}`
+#	
+      if [ "<${getScaStatus}>" != "<>" ]; then
+	  $ECHO "FATAL (${scriptName}): error to get sca file for $sourceRadio $dateDAQ"
+	  $ECHO "DEBUG (${scriptName}): START with cat ${OUT1}"
+	  $CAT ${OUT1}
+	  $ECHO "DEBUG (${scriptName}): END"
+	  continue
+      fi
+      $RM -f ${OUT1}
+
+      scaFile=`$FIND . -name "sca*.sum.trans" | $XARGS -i basename {}`
+
+
+#Get the calibration files
+      OUT2=./calibFiles.$$
+      ils ${i} | ${GREP} -i "calib.*\.txt" > ${OUT2}
+      listeOfCalib=( `$CAT ${OUT2}` )
+      IFS='
+'
+      listeOfCalib=( $( $PRINTF "%s\n" "${listeOfCalib[@]}" | $AWK 'x[$0]++ == 0' ) )
+      IFS=$DefaultIFS
+      $RM $OUT2
+      for fcal in ${listeOfCalib[@]}
+      do
+	OUT3=./getCalib.$$
+	iget -f -K -v ${i}/${fcal} ${aboveOnOffDir}> ${OUT3} 2>&1
+	igetStatus=`$GREP "^ERROR" ${OUT3}`
+	if [ "<$igetStatus>" != "<>" ]; then
+	    $ECHO "FATAL (${scriptName}): error while iget calib files:"
+	    $ECHO $igetStatus
+	    exit 1
+	fi
+	$RM -f ${OUT3}
+      done
+      
+#prepare job submission
+      cd ${aboveOnOffDir}
+#the default spectra name is medfiltmtx, otherwise use -specname <a_string>
+
+      logFile="analyse_DATA_${sourceRadio}_${dateDAQ}.log"
+      $ECHO "DEBUG (${scriptName}): execute the analysis... should not take long. `date`"
+      if [ ${simulationMode} = "On" ]; then
+	  $ECHO "SIMUL: ${scriptpath}/Objs/analyse -act dataOnOff -inPath ${iojobpath}  -source  ${sourceRadio} -date ${dateDAQ} -sca ${scaFile} -specdir datacycle -numcycle ${firstCycle},${lastCycle} -debuglev 1 -freqBAOCalib ${freqBAOCalib} >& ${logFile}"
+	  cat > ${logFile} <<EOF
+	  Ok calibration finished
+EOF
+      else
+	  ${scriptpath}/Objs/analyse -act dataOnOff -inPath ${iojobpath}  -source  ${sourceRadio} -date ${dateDAQ} -sca ${scaFile} -specdir datacycle -numcycle ${firstCycle},${lastCycle} -debuglev 1 -freqBAOCalib ${freqBAOCalib} >& ${logFile}
+      fi
+      $ECHO "DEBUG (${scriptName}): analysis finished `date`. Look for errors before saving to Irods"
+      rcstatus=`$GREP -i "Ok dataOnOff finished" ${logFile} | $WC -l`
+      if [ ${rcstatus} -eq 0 ]; then
+	  $ECHO "INFO (${scriptName}): analysis problem for ${sourceRadio} ${dateDAQ}"
+	  $ECHO "                      START logfile"
+	  $CAT ${logFile}
+	  $ECHO "                      END   logFile"
+#clean and leave
+	  cd ${aboveOnOffDir}
+	  $LS | $XARGS -i $RM -rf {}
+	  continue
+      fi
+#Save into Irods
+      $ECHO "DEBUG (${scriptName}): START save output files"
+      $LS ${aboveOnOffDir}
+#use -f option for iput ONLY to force override
+      if [ ${simulationMode} = "On" ]; then
+	  $ECHO "SIMUL: here we look for calib file and put them in Irods"
+      else
+	  $LS -lrth
+	  $FIND . -name "dataRaw_*" -print | $XARGS -i  iput  -v -K {} ${i}
+	  $FIND . -name "dataBAOCalib_*" -print | $XARGS -i  iput  -v -K {} ${i}
+	  $FIND . -name "dataBAORTCalib_*" -print | $XARGS -i  iput  -v -K {} ${i}
+	  $FIND . -name "diffOnOff_*" -print | $XARGS -i  iput  -v -K {} ${i}
+      fi
+#save analysis logfile
+      $LS -l ${tmppublicpath} > /dev/null
+      $CP ${logFile} ${tmppublicpath}
+      $ECHO "DEBUG (${scriptName}): END save output files"
+#clean up to avoid scratch SIZE EXCEED LIMIT
+      cd ${aboveOnOffDir}
+      $LS | $XARGS -i $RM -rf {}
+  fi
+done
+
+exit 0
Index: /BAORadio/AmasNancay/v5/plotDiffOnOff.pic
===================================================================
--- /BAORadio/AmasNancay/v5/plotDiffOnOff.pic	(revision 596)
+++ /BAORadio/AmasNancay/v5/plotDiffOnOff.pic	(revision 596)
@@ -0,0 +1,116 @@
+#$1: source
+#$2: nber of cycles
+#$3: number of freq. combined for reducing mean/sigma
+
+set source $1
+set ncycles $2
+set nFreqBin $3
+set action $4
+
+set defatt "font=helvetica,bold,20 fixedfontsize"
+
+
+
+if ( ${action} == "mean" ) then
+
+openppf meanDiffOnOffRaw_${source}-${ncycles}Cycles.ppf
+
+
+##General Mean
+del s0 s1
+objaoper mean row 0 s0
+objaoper mean row 1 s1
+graphicatt "${defatt} xylimits=1250,1500,-0.01,0.01"
+newwin 1 1
+plot2d s0 (n/8192)*250+1250 val n>0 "cpts blue nsta notit"
+plot2d s1 (n/8192)*250+1250 val n>0 "same cpts red nsta notit"
+settitle "$source (${ncycles} cycles) Ch 0 (blue) Ch 1 (red)" ' ' $defatt
+setaxelabels "Freq. (MHz)" "<(ON-OFF)[r,c]/Gain[r]>_{r,c}" $defatt
+
+
+
+##Reduced Mean
+newwin 1 1
+del rs0 rs1
+objaoper meanred row 0 rs0
+objaoper meanred row 1 rs1
+plot2d rs0 (n/${nFreqBin})*250+1250 val n>0 "marker=fcircle,5 blue nsta notit"
+plot2d rs1 (n/${nFreqBin})*250+1250 val n>0 "same marker=fcircle,5 red nsta notit"
+settitle "$source (${ncycles} cycles) Ch 0 (blue) Ch 1 (red)" ' ' $defatt
+setaxelabels "Freq. (MHz)" "<(ON-OFF)[r,c]/Gain[r]>_{r,c} Rebin(${nFreqBin})" $defatt
+
+
+##Reduced Mean
+newwin 1 1
+del rss0 rss1
+objaoper sigmared row 0 rss0
+objaoper sigmared row 1 rss1
+plot2d rss0 (n/${nFreqBin})*250+1250 val n>0 "marker=fcircle,5 blue nsta notit"
+plot2d rss1 (n/${nFreqBin})*250+1250 val n>0 "same marker=fcircle,5 red nsta notit"
+settitle "$source (${ncycles} cycles) Ch 0 (blue) Ch 1 (red)" ' ' $defatt 
+setaxelabels "Freq. (MHz)" "Sigma[(ON-OFF)[r,c]/Gain[r]] Rebin(${nFreqBin})" $defatt
+
+######
+else
+######
+
+openppf medianDiffOnOffRaw_${source}-${ncycles}Cycles.ppf
+
+
+##General Median
+del s0 s1
+objaoper median row 0 s0
+objaoper median row 1 s1
+graphicatt "xylimits=1250,1500,-0.01,0.01"
+newwin 1 1
+plot2d s0 (n/8192)*250+1250 val n>0 "cpts blue nsta notit"
+plot2d s1 (n/8192)*250+1250 val n>0 "same cpts red nsta notit"
+settitle "$source (${ncycles} cycles) Ch 0 (blue) Ch 1 (red)" ' ' $defatt
+setaxelabels "Freq. (MHz)" "Median[(ON-OFF)[r,c]/Gain[r]]"  $defatt
+
+
+##Reduced Mean of the median
+newwin 1 1
+del rs0 rs1
+objaoper meanmedred row 0 rs0
+objaoper meanmedred row 1 rs1
+graphicatt "xylimits=1250,1500,-0.01,0.01"
+plot2d rs0 (n/${nFreqBin})*250+1250 val n>0 "marker=fcircle,5 blue nsta notit"
+plot2d rs1 (n/${nFreqBin})*250+1250 val n>0 "same marker=fcircle,5 red nsta notit"
+settitle "$source (${ncycles} cycles) Ch 0 (blue) Ch 1 (red)" ' ' $defatt
+setaxelabels "Freq. (MHz)" "Mean Median[(ON-OFF)[r,c]/Gain[r]] Rebin(${nFreqBin})" $defatt
+
+
+##Reduced Sigma of the median
+newwin 1 1
+del rss0 rss1
+objaoper sigmamedred row 0 rss0
+objaoper sigmamedred row 1 rss1
+graphicatt "xylimits=1250,1500,0,0.01"
+plot2d rss0 (n/${nFreqBin})*250+1250 val n>0 "marker=fcircle,5 blue nsta notit"
+plot2d rss1 (n/${nFreqBin})*250+1250 val n>0 "same marker=fcircle,5 red nsta notit"
+settitle "$source (${ncycles} cycles) Ch 0 (blue) Ch 1 (red)" ' ' $defatt
+setaxelabels "Freq. (MHz)" "Sigma Median[(ON-OFF)[r,c]/Gain[r]] Rebin(${nFreqBin})" $defatt
+
+
+##Normalized General Median
+del ngms0 ngms1
+objaoper medianNorm row 0 ngms0
+objaoper medianNorm row 1 ngms1
+graphicatt "xylimits=1250,1500,-2,2"
+newwin 1 1
+plot2d ngms0 (n/8192)*250+1250 val n>0 "cpts blue nsta notit"
+plot2d ngms1 (n/8192)*250+1250 val n>0 "same cpts red nsta notit"
+settitle "$source (${ncycles} cycles) Ch 0 (blue) Ch 1 (red)" ' ' $defatt
+setaxelabels "Freq. (MHz)" "Norm Median[(ON-OFF)[r,c]/Gain[r]]"  $defatt
+
+del prod
+c++exec TVector<r_4>prod(ngms0.NElts(),BaseArray::RowVector); prod=ngms0&&ngms1;KeepObj(prod);
+newwin 1 1
+plot2d prod (n/8192)*250+1250 val n>0 "cpts blue nsta notit"
+settitle "$source (${ncycles} cycles)" ' ' $defatt
+setaxelabels "Freq. (MHz)" "Product Norm Median[(ON-OFF)[r,c]/Gain[r]]"  $defatt
+ 
+
+endif
+
Index: /BAORadio/AmasNancay/v5/proc_script.sh
===================================================================
--- /BAORadio/AmasNancay/v5/proc_script.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/proc_script.sh	(revision 596)
@@ -0,0 +1,498 @@
+#!/bin/sh -xvf
+#Basic tuning of system fuction used.
+AWK=/bin/awk
+SED=/bin/sed
+GREP=/bin/grep
+WC=/usr/bin/wc
+RM=/bin/rm
+CAT=/bin/cat
+TOUCH=/bin/touch
+DATE=/bin/date
+ECHO=/bin/echo
+LS=/bin/ls
+MKDIR=/bin/mkdir
+TR=/usr/bin/tr
+FIND=/usr/bin/find
+PRINTF=/usr/bin/printf
+XARGS=/usr/bin/xargs
+SORT=/bin/sort
+QSUB=qsub
+
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+######
+# Local functions
+######
+usage() {
+  echo "usage: $scriptName <source> <YYYYMMDD-directory> <type of process>"
+  echo "      -<source> as Abell85"
+  echo "      -<YYYYMMDD-directory> as 20110428"
+  echo "      -<type of process> as GAIN|CALIBON|CALIBOFF|ON|OFF"
+}
+######
+# argument test
+######
+if [ ! $# = 3 ]; then
+  usage
+  exit 1
+fi
+sourceRadio=$1
+srclower=`${ECHO} ${sourceRadio} | ${TR} "[:upper:]" "[:lower:]" `
+dateDAQ=$2
+typeofproc=$3
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+$LS -l ${tmppublicpath} > /dev/null
+
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+localpath="${sourceRadio}/${dateDAQ}${srclower}"
+$MKDIR -p ./${localpath}
+cd ./${localpath}
+mainDirectory=`pwd`
+
+
+#Path of the utility scripts
+scriptpath=${SCRIPTPATH}
+
+
+#select file per cycle
+#$ECHO "Select files process..."
+#keep only lines with structure: cycle_number first,last,step
+#Get sca files
+$ECHO "DEBUG (${scriptName}): START call getscafiles.sh ${sourceRadio} ${dateDAQ}"
+OUT1=./getScaStatus.$$
+$RM -f ${tmppublicpath}/getscafiles.finished
+${scriptpath}/getscafiles.sh ${sourceRadio} ${dateDAQ} > ${OUT1} 2>&1
+while [ ! -f "${tmppublicpath}/getscafiles.finished" ]; do
+    $ECHO "INFO (${scriptName}): waiting for ${tmppublicpath}/getscafiles.finished"
+    date +%T
+    sleep 30
+done
+$RM ${tmppublicpath}/getscafiles.finished
+$ECHO "DEBUG (${scriptName}): END"
+
+
+getScaStatus=`$GREP "^\(FATAL\|ERROR\)" ${OUT1}`
+
+if [ "<${getScaStatus}>" != "<>" ]; then
+  $ECHO "FATAL (${scriptName}): error to get sca file for $sourceRadio $dateDAQ"
+  $ECHO "DEBUG (${scriptName}): START with cat ${OUT1}"
+  $CAT ${OUT1}
+  $ECHO "DEBUG (${scriptName}): END"
+  exit 1
+fi
+
+
+scaFileSummarized=`$FIND . -name "sca*.sum" -print`
+if [ "<${scaFileSummarized}>" = "<>" ]; then
+  $ECHO "FATAL (${scriptName}): strange sca file summarized not available: $sourceRadio $dateDAQ"
+  $ECHO "DEBUG (${scriptName}): START with cat ${OUT1}"
+  $CAT ${OUT1}
+  $ECHO "DEBUG (${scriptName}): END"
+  exit 1
+fi
+$RM ${OUT1}
+
+scaFileSummarized=`basename $scaFileSummarized`
+
+#set Irods environment
+. /usr/local/shared/bin/irods_env.sh -noverbose
+#download header files to be used for signal files selction
+$MKDIR -p ./Fiber1
+dirFiberfile=`pwd`/Fiber1
+
+dirIrods="/baoradio/data/AmasNancay/${sourceRadio}/${dateDAQ}${srclower}/Fiber1"
+
+listOfFiles=( `ils ${dirIrods} | $GREP -i "header" | $XARGS -i basename {} | $SORT -k1.7n` )
+IFS='
+'
+listOfFiles=( $( $PRINTF "%s\n" "${listOfFiles[@]}" | $AWK 'x[$0]++ == 0' ) )
+IFS=$DefaultIFS
+
+#
+$ECHO "DEBUG (${scriptName}): Download if necessary the headers"
+#
+for ifile in ${listOfFiles[@]}
+do
+#test if the headers have not yet been downloaded
+  if [ ! -e ${dirFiberfile}/${ifile} ]; then
+      OUT2=./getheaders.$$
+      iget -f -K ${dirIrods}/${ifile} ${dirFiberfile} >${OUT2} 2>&1
+      igetStatus=`$GREP "^ERROR" ${OUT2}`
+      if [ "<$igetStatus>" != "<>" ]; then
+	  $ECHO "FATAL (${scriptName}): error while iget:"
+	  $ECHO $igetStatus
+	  exit 1
+      fi
+      $RM -f $OUT2
+  fi
+done
+#
+$ECHO "DEBUG (${scriptName}): START call select.sh ${scaFileSummarized} ${dirFiberfile} ${typeofproc}"
+#
+#Get list of file to process
+headerFileSelected=./selectSignal.$$
+$RM -f ${tmppublicpath}/select.finished
+${scriptpath}/select.sh ${scaFileSummarized} ${dirFiberfile} ${typeofproc} | $GREP "^#[0-9]" | $SED "s/^#//" > $headerFileSelected
+while [ ! -f "${tmppublicpath}/select.finished" ]; do
+    $ECHO "INFO (${scriptName}): waiting for ${tmppublicpath}/select.finished"
+    date +%T
+    sleep 30
+done
+$RM ${tmppublicpath}/select.finished
+#
+$ECHO "DEBUG (${scriptName}): END"
+#
+$ECHO "DEBUG (${scriptName}): START filling cycleArray, filesArray"
+#
+declare -a cycleArray
+declare -a filesArray
+$ECHO "DEBUG (${scriptName}): IFS value between<>: <$IFS>"
+IFS=$DefaultIFS
+$ECHO "DEBUG (${scriptName}): START cat $headerFileSelected"
+$CAT $headerFileSelected
+$ECHO "DEBUG (${scriptName}): END cat $headerFileSelected"
+
+while read v1 v2
+do
+ cycleArray[${#cycleArray[*]}]=$v1
+ filesArray[${#filesArray[*]}]=$v2
+done < $headerFileSelected
+
+if [ ${#cycleArray[*]} -eq 0 -o ${#filesArray[*]} -eq 0 ]; then
+   $ECHO "FATAL (${scriptName}): no header file selected (${#cycleArray[*]}, ${#filesArray[*]})"
+   exit 1
+else
+   $ECHO "DEBUG (${scriptName}): non zero elements found for cycleArray and filesArray" 
+fi
+
+#
+$ECHO "DEBUG (${scriptName}): number of elements <${#cycleArray[*]}> <${#filesArray[*]}>"
+$ECHO "DEBUG (${scriptName}): END"
+#
+# (timeShift)
+#Add 3sec to start ON / OFF
+#Substract 4sec to start DAB ON / OFF
+#
+#Take care: Cycle numbering starts at 1 in SCAFiles while Arrays index start at 0
+#
+#for GAIN the reference cycle takes the middle of the run
+#
+#nwinmean donne le nombre de fenetre tspwin utilise pour faire calculer la moyenne des medianes de chaque fenetre
+#This is the nimber of paquets of the time window which change according to processing type
+$ECHO "DEBUG (${scriptName}): START switch on $typeofproc"
+#
+case "$typeofproc" in
+    GAIN)
+      $ECHO "process signal files for GAIN phase"
+      ingain=""
+      freqfilter="-freqfilter -"
+      nwinmean="1"
+      tspwin="5120"
+      dirName="Off"
+      cyclebasename="gaincycle"
+      indexStartHour="6"
+      timeShift="-4"
+      timeDuration="14"
+      firstCycleId=`expr  ${#cycleArray[*]} / 2`
+      firstCycleId=`expr ${firstCycleId} - 1`
+      lastp1CycleId=`expr ${firstCycleId} + 1`
+      ;;
+    ON)
+      $ECHO "process signal files for ON phases"
+      ingain="-gain gain_${dateDAQ}_${srclower}.fits"
+      freqfilter="-freqfilter 16"
+      nwinmean="5"
+      tspwin="5120"
+      dirName="On"
+      cyclebasename="datacycle"
+      indexStartHour="4"
+      timeShift="3"
+      timeDuration="30"
+      firstCycleId="0"
+      lastp1CycleId="${#cycleArray[@]}"
+      ;;
+    OFF)
+      $ECHO "process signal files for OFF phases"
+      ingain="-gain gain_${dateDAQ}_${srclower}.fits"
+      freqfilter="-freqfilter 16"
+      nwinmean="5"
+      tspwin="5120"
+      dirName="Off"
+      cyclebasename="datacycle"
+      indexStartHour="8"
+      timeShift="3"
+      timeDuration="30"
+      firstCycleId="0"
+      lastp1CycleId="${#cycleArray[@]}"
+      ;;
+    CALIBON)
+      $ECHO "process signal files for CALIBRATION ON phases"
+      ingain="-gain gain_${dateDAQ}_${srclower}.fits"
+      freqfilter="-freqfilter 16"
+      nwinmean="1"
+      tspwin="1024"
+      dirName="On"
+      cyclebasename="calibcycle"
+      indexStartHour="2"
+      timeShift="-4"
+      timeDuration="14"
+      firstCycleId="0"
+      lastp1CycleId="${#cycleArray[@]}"
+      ;;
+    CALIBOFF)
+      $ECHO "process signal files for CALIBRATION OFF phases"
+      ingain="-gain gain_${dateDAQ}_${srclower}.fits"
+      freqfilter="-freqfilter 16"
+      nwinmean="1"
+      tspwin="1024"
+      dirName="Off"
+      cyclebasename="calibcycle"
+      indexStartHour="6"
+      timeShift="-4"
+      timeDuration="14"
+      firstCycleId="0"
+      lastp1CycleId="${#cycleArray[@]}"
+      ;;
+    *)
+    $ECHO "FATAL (${scriptName}): type of processing"
+    usage
+    exit 1
+    ;;
+esac
+#
+$ECHO "DEBUG (${scriptName}): END"
+#
+#
+#Compute time windows (Warning usage of GMT date)
+#
+$ECHO "DEBUG (${scriptName}): START compute time windows"
+OUT=./baotiming.$$
+${AWK} -v datesys=${DATE} -v type=${indexStartHour} -v shift=${timeShift} '
+BEGIN {FS=","}
+{
+  phaseStart=$type
+  cmd=sprintf("%s +%%s -d  \"%s\" ",datesys,phaseStart);
+  (cmd | getline phstart);
+  close(cmd);
+  newstart = phstart+shift;
+  cmd=sprintf("%s +%%T -d \"1970-01-01 %s sec GMT\"",datesys,newstart);
+  (cmd | getline newStart);
+  close(cmd);
+  print $1,newStart,phaseStart;
+}
+'  ${scaFileSummarized} > ${OUT}
+#
+$ECHO "DEBUG (${scriptName}): END"
+#
+$ECHO "DEBUG (${scriptName}): START cat ${OUT}"
+$CAT ${OUT}
+$ECHO "DEBUG (${scriptName}): END cat ${OUT}"
+#
+$ECHO "DEBUG (${scriptName}): START filling cylceArrayBis timeArray"
+#
+declare -a cycleArrayBis
+declare -a timeArray
+$ECHO "DEBUG (${scriptName}): IFS value between<>: <$IFS>"
+IFS=$DefaultIFS
+#select the selected cycles
+idtofind="0"
+while read v1 v2 v3
+do
+ if [ ${idtofind} -lt ${#cycleArray[*]} ]; then
+    if [ ${v1} = ${cycleArray[${idtofind}]} ]; then
+	cycleArrayBis[${#cycleArrayBis[*]}]=$v1
+	timeArray[${#timeArray[*]}]=$v2
+	idtofind=`expr ${idtofind} + 1`
+    fi
+ fi
+done < ${OUT}
+$ECHO "DEBUG (${scriptName}): number of elements ${#cycleArrayBis[*]} ${#timeArray[*]}"
+$ECHO "DEBUG (${scriptName}): END"
+
+
+#########################
+# specmfib exe
+#########################
+prg="/afs/in2p3.fr/throng/baoradio/Library/Progs/TAcq/Objs/specmfib"
+if [ ! -e $prg ]; then
+    $ECHO "FATAL (${scriptName}): $prg not found"
+    exit 1
+fi
+
+
+dirFiberfile=${iojobpath}/${localpath}
+
+curDir=`pwd`
+#
+$ECHO "DEBUG (${scriptName}): in principle $dirFiberfile == $curDir "
+#
+#force single channel
+forceSingle="-singlechan"
+#debug
+prtlevel="1"
+
+
+#Loop on cycles to write batch script and send to batch queue
+##
+$ECHO "DEBUG (${scriptName}): START loop on cycles ${firstCycleId} to ${lastp1CycleId}"
+
+for ((i=${firstCycleId};i<${lastp1CycleId};i++)); do
+#
+$ECHO "DEBUG (${scriptName}): process cycle $i"
+#time window selection
+    tmproc="-tmproc ${timeArray[${i}]},${timeDuration}"
+#cycle <name><number>
+    cycle="${cyclebasename}${cycleArray[${i}]}"
+#signal files selection
+    infiles="${filesArray[${i}]}"
+#
+#Prepare BQS parameters: MEMORY, CPU...#
+    infilesArray=( `$ECHO $infiles | $AWK 'BEGIN {FS=","} {for(i=1;i<NF;i++)print $i;}'` )
+    IFS='
+    '
+    infilesArray=( $( printf "%s\n" "${infilesArray[@]}" | awk 'x[$0]++ == 0' ) )
+    IFS=$DefaultIFS
+    firstFile=${infilesArray[0]}
+    lastFile=${infilesArray[1]}
+#compute Scratch Size MB (400MB per signal files), CPU Time
+    nFiles=`expr ${lastFile} - ${firstFile} + 1`
+# Fiber 1 & Fiber 2 => double the number of files
+    nFiles=`expr ${nFiles} \* 2`
+#add number of spectra generated (cf. (Nbrepaquets_per_files * nFiles /tspwin) * 100KB
+    nSpectra=`expr ${nFiles} \* 25600 /  ${tspwin}`
+#Guess formula to reserved the amount of space needed in scratch
+    scratchSize=`expr ${nFiles} \* 500 + ${nSpectra} \* 200 / 1000 + 5`
+# 60sec/signal_file * empirical_conversion_factor (=50)
+    cpu=`expr ${nFiles} \* 60 \* 50`
+#Virtual Memory (MB) Nb: at CCIN2P3 the reasonable max is 1GB
+    virtualmem=1000
+#Job and batch names
+    jobBatchName="${sourceRadio}-${dateDAQ}-${typeofproc}-cycle${cycleArray[${i}]}"
+    jobScriptName="${jobBatchName}.sh"
+    jobLogName="${jobBatchName}.log"
+#
+$ECHO "DEBUG (${scriptName}): start writing ${jobScriptName}"
+#
+#
+#write the script to be send to Batch
+#
+    $CAT > ${jobScriptName} <<EOF
+#!/bin/sh -xvf
+#    jobBatchName=$jobBatchName
+#    jobScriptName=$jobScriptName
+#    jobLogName=$jobLogName
+    scriptName=$jobScriptName
+
+    . /afs/in2p3.fr/home/throng/baoradio/setup.sh
+    . /usr/local/shared/bin/irods_env.sh -noverbose
+
+    iojobpath=\${TMPBATCH}
+    cd \${iojobpath}
+    localpath=${sourceRadio}/${dateDAQ}${srclower}
+    $MKDIR -p ./\${localpath}
+    cd ./\${localpath}
+
+    curDir=\`pwd\`
+#get gain file if necessary
+    if [ ${typeofproc} != "GAIN" ]; then
+	OUT2=./igetStatus.$$
+	iget /baoradio/data/AmasNancay/${localpath}/gain_${dateDAQ}_${srclower}.fits >\${OUT2} 2>&1
+	igetStatus=\`$GREP "^ERROR" \${OUT2}\`
+	if [ "<\${igetStatus}>" != "<>" ]; then
+	    $ECHO "FATAL (\${scriptName}): error while iget:"
+	    $ECHO \$igetStatus
+	    exit 1
+	fi
+        $RM \${OUT2}
+    fi    
+#get signals files
+    OUT3=./getsignals.$$
+    $RM -f ${tmppublicpath}/getsignalfiles.finished
+    ${scriptpath}/getsignalfiles.sh ${sourceRadio} ${dateDAQ} ${firstFile}  ${lastFile} > \${OUT3} 2>&1
+    while [ ! -f "${tmppublicpath}/getsignalfiles.finished" ]; do
+	$ECHO "INFO (\${scriptName}): waiting for ${tmppublicpath}/getsignalfiles.finished"
+	date +%T
+	sleep 30
+    done
+    $RM ${tmppublicpath}/getsignalfiles.finished
+
+    getSignals=\`$GREP "^FATAL" \${OUT3}\`
+    if [ "<\$getSignals>" != "<>" ]; then
+	$ECHO "FATAL (\${scriptName}): error while get signals"
+	$ECHO \$getSignals
+	exit 1
+    fi
+    $RM \${OUT3}
+#location of the signal file
+    fibfile="\${curDir} 1,2"
+#
+    outDir=\${curDir}/${dirName}/${cycle}
+    $MKDIR -p \${outDir}
+
+#
+# where ami...
+#
+    $ECHO "We are here \`pwd\` to send the batch"
+    $LS -lrth
+    $FIND . -name "igetStatus.*" | $XARGS -i  $CAT {}
+    $LS ./Fiber1 | $WC -l
+    $LS ./Fiber2 | $WC -l
+    $LS -lR \${outDir}
+
+#Note: here act=gain means only that specmfib will use median-like algorithms (not only for gains...)
+    $prg -act gain $forceSingle $freqfilter  -prt $prtlevel -out \${outDir} -nmean $nwinmean $ingain $tmproc -tspwin ${tspwin},0,0 -in $infiles \${fibfile}
+
+    $ECHO    \${outDir}
+    $LS -lrt \${outDir}
+
+#save results to Irods (use option -f ONLY to force override)
+    iput -v -K -r \${curDir}/${dirName} /baoradio/data/AmasNancay/\${localpath}
+#
+#clean the signal files which can at the end of the day fill completly the scratch directory of the batch work/AmasNancayer
+    $RM -f \${iojobpath}/\${localpath}/Fiber1/signal*.fits
+    $RM -f \${iojobpath}/\${localpath}/Fiber2/signal*.fits
+    exit 0
+EOF
+#
+#The EOF tag MUST BEGIN the line, this is the end of the script
+#
+    $ECHO "DEBUG (${scriptName}); START listing of script to be send to batch queue"
+    $CAT -v ${jobScriptName}
+    $ECHO "DEBUG (${scriptName}): END listing"
+#
+#send to BATCH
+#
+    $ECHO "DEBUG (${scriptName}): START send to batch listing"
+#
+    $RM -f ${tmppublicpath}/${jobBatchName}.finished
+
+##26/9/11 JEC use option -h to trig manualy the job on the queue...
+    qsub -h -l u_sps_baoradio,u_irods,u_irods_baoradio,T=${cpu},M=${virtualmem}MB,scratch=${scratchSize}MB,platform=LINUX -eo -o ${tmppublicpath}/${jobLogName} -N ${jobBatchName}  ${jobScriptName}
+
+#    while [ ! -f "${tmppublicpath}/${jobBatchName}.finished" ]; do
+#	$ECHO "INFO (${scriptName}); waiting for ${tmppublicpath}/${jobBatchName}.finished"
+#	date +%T
+#	sleep 600
+#    done
+#    $RM ${tmppublicpath}/${jobBatchName}.finished
+    $ECHO "DEBUG (${scriptName}): end send to batch listing"
+#end loop on cycles
+done
+#
+$ECHO "DEBUG (${scriptName}): END loop on cycles"
+#
+exit 0
Index: /BAORadio/AmasNancay/v5/proc_specmfib.sh
===================================================================
--- /BAORadio/AmasNancay/v5/proc_specmfib.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/proc_specmfib.sh	(revision 596)
@@ -0,0 +1,584 @@
+#!/bin/sh -xvf
+#Basic tuning of system fuction used.
+AWK=/bin/awk
+SED=/bin/sed
+GREP=/bin/grep
+WC=/usr/bin/wc
+RM=/bin/rm
+CAT=/bin/cat
+TOUCH=/bin/touch
+DATE=/bin/date
+ECHO=/bin/echo
+LS=/bin/ls
+MKDIR=/bin/mkdir
+TR=/usr/bin/tr
+FIND=/usr/bin/find
+PRINTF=/usr/bin/printf
+XARGS=/usr/bin/xargs
+SORT=/bin/sort
+QSUB=qsub
+
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+######
+# Local functions
+######
+usage() {
+  echo "usage: $scriptName <source> <YYYYMMDD-directory> <type of process>"
+  echo "      -<source> as Abell85"
+  echo "      -<YYYYMMDD-directory> as 20110428"
+  echo "      -<type of process> as GAIN|CALIBON|CALIBOFF|ON|OFF"
+}
+######
+# argument test
+######
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+#action: gain|mspec (gain: gain-like doucble median filtering
+#                   mspec: mean+sigma wo filetring)
+action="gain"
+sourceRadio=
+dateSelected=
+typeofproc=
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=Off
+#
+#first and last cycle to process
+#
+firstCycle=
+lastCycle=
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -act)  action=$2;         shift;;
+      -src)  sourceRadio=$2;    shift;;
+      -date) dateSelected=$2;   shift;;
+      -type) typeofproc=$2;     shift;;
+      -fcycle) firstCycle=$2;   shift;;
+      -lcycle) lastCycle=$2;    shift;;
+      -sim)  simulationMode=On;;
+	-h)
+	    echo >&2 \
+	    "usage: $0 [-act <action> ] -src souce -date YYYYMMDD -type type [-fcycle firstCycle] [-lcycle lastCycle] [-sim to trig simulation mode]"
+	    exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+#Check input
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+if [ "<${dateSelected}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the date option (-date)"
+    exit 1
+fi
+
+if [ "<${typeofproc}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the type option (-type)"
+    exit 1
+
+fi
+#else
+#    offtype=`$ECHO ${typeofproc} | $GREP -i OFF | $WC -l`
+#    ontype=`$ECHO ${typeofproc} | $GREP -i ON | $WC -l`
+#    if [ "<${offtype}>" = "<1>" -a  "<${ontype}>" = "<0>" ]; then
+#	datatype="OFF"
+#    elif [ "<${offtype}>" = "<0>" -a  "<${ontype}>" = "<1>" ]; then
+#	datatype="ON"
+#    else
+#	$ECHO "FATAL: not supported: -type ${typeofproc}"
+#	exit 1
+#    fi
+#fi
+
+
+srclower=`${ECHO} ${sourceRadio} | ${TR} "[:upper:]" "[:lower:]" `
+
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+$LS -l ${tmppublicpath} > /dev/null
+
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+localpath="${sourceRadio}/${dateSelected}${srclower}"
+$MKDIR -p ./${localpath}
+cd ./${localpath}
+mainDirectory=`pwd`
+
+
+#Path of the utility scripts
+scriptpath=${SCRIPTPATH}
+
+
+#select file per cycle
+#$ECHO "Select files process..."
+#keep only lines with structure: cycle_number first,last,step
+#Get sca files
+$ECHO "DEBUG (${scriptName}): START call getscafiles.sh ${sourceRadio} ${dateSelected}"
+OUT1=./getScaStatus.$$
+#JEC 29/9/11 avoid finished stuff
+#$RM -f ${tmppublicpath}/getscafiles.finished
+${scriptpath}/getscafiles.sh ${sourceRadio} ${dateSelected} > ${OUT1} 2>&1
+#while [ ! -f "${tmppublicpath}/getscafiles.finished" ]; do
+#    $ECHO "INFO (${scriptName}): waiting for ${tmppublicpath}/getscafiles.finished"
+#    date +%T
+#    sleep 30
+#done
+#$RM -f ${tmppublicpath}/getscafiles.finished
+$ECHO "DEBUG (${scriptName}): END"
+
+
+getScaStatus=`$GREP "^\(FATAL\|ERROR\)" ${OUT1}`
+
+if [ "<${getScaStatus}>" != "<>" ]; then
+  $ECHO "FATAL (${scriptName}): error to get sca file for $sourceRadio $dateSelected"
+  $ECHO "DEBUG (${scriptName}): START with cat ${OUT1}"
+  $CAT ${OUT1}
+  $ECHO "DEBUG (${scriptName}): END"
+  exit 1
+fi
+
+
+scaFileSummarized=`$FIND . -name "sca*.sum" -print`
+if [ "<${scaFileSummarized}>" = "<>" ]; then
+  $ECHO "FATAL (${scriptName}): strange sca file summarized not available: $sourceRadio $dateSelected"
+  $ECHO "DEBUG (${scriptName}): START with cat ${OUT1}"
+  $CAT ${OUT1}
+  $ECHO "DEBUG (${scriptName}): END"
+  exit 1
+fi
+$RM ${OUT1}
+
+scaFileSummarized=`basename $scaFileSummarized`
+
+#set Irods environment
+. /usr/local/shared/bin/irods_env.sh -noverbose
+#download header files to be used for signal files selction
+$MKDIR -p ./Fiber1
+dirFiberfile=`pwd`/Fiber1
+
+dirIrods="/baoradio/data/AmasNancay/${sourceRadio}/${dateSelected}${srclower}/Fiber1"
+
+listOfFiles=( `ils ${dirIrods} | $GREP -i "header" | $XARGS -i basename {} | $SORT -k1.7n` )
+IFS='
+'
+listOfFiles=( $( $PRINTF "%s\n" "${listOfFiles[@]}" | $AWK 'x[$0]++ == 0' ) )
+IFS=$DefaultIFS
+
+#
+$ECHO "DEBUG (${scriptName}): Download if necessary the headers"
+#
+for ifile in ${listOfFiles[@]}
+do
+#test if the headers have not yet been downloaded
+  if [ ! -e ${dirFiberfile}/${ifile} ]; then
+      OUT2=./getheaders.$$
+      iget -f -K ${dirIrods}/${ifile} ${dirFiberfile} >${OUT2} 2>&1
+      igetStatus=`$GREP "^ERROR" ${OUT2}`
+      if [ "<$igetStatus>" != "<>" ]; then
+	  $ECHO "FATAL (${scriptName}): error while iget:"
+	  $ECHO $igetStatus
+	  exit 1
+      fi
+      $RM -f $OUT2
+  fi
+done
+#
+$ECHO "DEBUG (${scriptName}): START call select.sh ${scaFileSummarized} ${dirFiberfile} ${typeofproc}"
+#
+#Get list of file to process
+headerFileSelected=./selectSignal.$$
+#JEC 29/9/11 avoid finished stuff
+#$RM -f ${tmppublicpath}/select.finished
+${scriptpath}/select.sh ${scaFileSummarized} ${dirFiberfile} ${typeofproc} | $GREP "^#[0-9]" | $SED "s/^#//" > $headerFileSelected
+#while [ ! -f "${tmppublicpath}/select.finished" ]; do
+#    $ECHO "INFO (${scriptName}): waiting for ${tmppublicpath}/select.finished"
+#    date +%T
+#    sleep 30
+#done
+#$RM ${tmppublicpath}/select.finished
+#
+$ECHO "DEBUG (${scriptName}): END"
+#
+$ECHO "DEBUG (${scriptName}): START filling cycleArray, filesArray"
+#
+declare -a cycleArray
+declare -a filesArray
+$ECHO "DEBUG (${scriptName}): IFS value between<>: <$IFS>"
+IFS=$DefaultIFS
+$ECHO "DEBUG (${scriptName}): START cat $headerFileSelected"
+$CAT $headerFileSelected
+$ECHO "DEBUG (${scriptName}): END cat $headerFileSelected"
+
+while read v1 v2
+do
+ cycleArray[${#cycleArray[*]}]=$v1
+ filesArray[${#filesArray[*]}]=$v2
+done < $headerFileSelected
+
+if [ ${#cycleArray[*]} -eq 0 -o ${#filesArray[*]} -eq 0 ]; then
+   $ECHO "FATAL (${scriptName}): no header file selected (${#cycleArray[*]}, ${#filesArray[*]})"
+   exit 1
+else
+   $ECHO "DEBUG (${scriptName}): non zero elements found for cycleArray and filesArray" 
+fi
+
+#
+$ECHO "DEBUG (${scriptName}): number of elements <${#cycleArray[*]}> <${#filesArray[*]}>"
+$ECHO "DEBUG (${scriptName}): END"
+#
+# (timeShift)
+#Add 3sec to start ON / OFF
+#Substract 4sec to start DAB ON / OFF
+#
+#Take care: Cycle numbering starts at 1 in SCAFiles while Arrays index start at 0
+#
+#for GAIN the reference cycle takes the middle of the run
+#
+#nwinmean donne le nombre de fenetre tspwin utilise pour faire calculer la moyenne des medianes de chaque fenetre
+#This is the nimber of paquets of the time window which change according to processing type
+$ECHO "DEBUG (${scriptName}): START switch on $typeofproc"
+#
+case "$typeofproc" in
+    GAIN)
+      $ECHO "process signal files for GAIN phase"
+      ingain=""
+      freqfilter="-freqfilter -"
+      nwinmean="1"
+      tspwin="5120"
+      dirName="Off"
+      cyclebasename="gaincycle"
+      indexStartHour="6"
+      timeShift="-4"
+      timeDuration="14"
+      firstCycleId=`expr  ${#cycleArray[*]} / 2`
+      firstCycleId=`expr ${firstCycleId} - 1`
+      lastp1CycleId=`expr ${firstCycleId} + 1`
+      ;;
+    GAINNF)
+      $ECHO "process signal files for GAIN phase wo Freq FILTERING"
+      ingain=""
+      freqfilter="-freqfilter 4"
+      nwinmean="1"
+      tspwin="5120"
+      dirName="Off"
+      cyclebasename="gainf4cycle"
+      indexStartHour="6"
+      timeShift="-4"
+      timeDuration="14"
+      firstCycleId=`expr  ${#cycleArray[*]} / 2`
+      firstCycleId=`expr ${firstCycleId} - 1`
+      lastp1CycleId=`expr ${firstCycleId} + 1`
+      ;;
+    ON)
+      $ECHO "process signal files for ON phases"
+      ingain="-gain gain_${dateSelected}_${srclower}.fits"
+      freqfilter=""
+      nwinmean="5"
+      tspwin="5120"
+      dirName="On"
+      cyclebasename="datacycle"
+      indexStartHour="4"
+      timeShift="3"
+      timeDuration="30"
+      firstCycleId="0"
+      lastp1CycleId="${#cycleArray[@]}"
+      ;;
+    OFF)
+      $ECHO "process signal files for OFF phases"
+      ingain="-gain gain_${dateSelected}_${srclower}.fits"
+      freqfilter=""
+      nwinmean="5"
+      tspwin="5120"
+      dirName="Off"
+      cyclebasename="datacycle"
+      indexStartHour="8"
+      timeShift="3"
+      timeDuration="30"
+      firstCycleId="0"
+      lastp1CycleId="${#cycleArray[@]}"
+      ;;
+    MEANOFF)
+      $ECHO "process signal files for OFF phases (MEAN)"
+      ingain="-gain gain_${dateSelected}_${srclower}.fits"
+      freqfilter=""
+      nwinmean="25000"
+      tspwin="0"
+      dirName="Off"
+      cyclebasename="meancycle"
+      indexStartHour="8"
+      timeShift="3"
+      timeDuration="30"
+      firstCycleId="0"
+      lastp1CycleId="${#cycleArray[@]}"
+      ;;
+    MEANON)
+      $ECHO "process signal files for ON phases (MEAN)"
+      ingain="-gain gain_${dateSelected}_${srclower}.fits"
+      freqfilter=""
+      nwinmean="25000"
+      tspwin="0"
+      dirName="On"
+      cyclebasename="meancycle"
+      indexStartHour="4"
+      timeShift="3"
+      timeDuration="30"
+      firstCycleId="0"
+      lastp1CycleId="${#cycleArray[@]}"
+      ;;
+    CALIBON)
+      $ECHO "process signal files for CALIBRATION ON phases"
+      ingain="-gain gain_${dateSelected}_${srclower}.fits"
+      freqfilter="-freqfilter -"
+      nwinmean="1"
+      tspwin="1024"
+      dirName="On"
+      cyclebasename="calibcycle"
+      indexStartHour="2"
+      timeShift="-4"
+      timeDuration="14"
+      firstCycleId="0"
+      lastp1CycleId="${#cycleArray[@]}"
+      ;;
+    CALIBOFF)
+      $ECHO "process signal files for CALIBRATION OFF phases"
+      ingain="-gain gain_${dateSelected}_${srclower}.fits"
+      freqfilter="-freqfilter -"
+      nwinmean="1"
+      tspwin="1024"
+      dirName="Off"
+      cyclebasename="calibcycle"
+      indexStartHour="6"
+      timeShift="-4"
+      timeDuration="14"
+      firstCycleId="0"
+      lastp1CycleId="${#cycleArray[@]}"
+      ;;
+    *)
+    $ECHO "FATAL (${scriptName}): type of processing"
+    usage
+    exit 1
+    ;;
+esac
+#
+$ECHO "DEBUG (${scriptName}): END"
+#
+#
+#Compute time windows (Warning usage of GMT date)
+#
+$ECHO "DEBUG (${scriptName}): START compute time windows"
+OUT=./baotiming.$$
+${AWK} -v datesys=${DATE} -v type=${indexStartHour} -v shift=${timeShift} '
+BEGIN {FS=","}
+{
+  phaseStart=$type
+  cmd=sprintf("%s +%%s -d  \"%s\" ",datesys,phaseStart);
+  (cmd | getline phstart);
+  close(cmd);
+  newstart = phstart+shift;
+  cmd=sprintf("%s +%%T -d \"1970-01-01 %s sec GMT\"",datesys,newstart);
+  (cmd | getline newStart);
+  close(cmd);
+  print $1,newStart,phaseStart;
+}
+'  ${scaFileSummarized} > ${OUT}
+#
+$ECHO "DEBUG (${scriptName}): END"
+#
+$ECHO "DEBUG (${scriptName}): START cat ${OUT}"
+$CAT ${OUT}
+$ECHO "DEBUG (${scriptName}): END cat ${OUT}"
+#
+$ECHO "DEBUG (${scriptName}): START filling cylceArrayBis timeArray"
+#
+declare -a cycleArrayBis
+declare -a timeArray
+$ECHO "DEBUG (${scriptName}): IFS value between<>: <$IFS>"
+IFS=$DefaultIFS
+#select the selected cycles
+idtofind="0"
+while read v1 v2 v3
+do
+ if [ ${idtofind} -lt ${#cycleArray[*]} ]; then
+    if [ ${v1} = ${cycleArray[${idtofind}]} ]; then
+	cycleArrayBis[${#cycleArrayBis[*]}]=$v1
+	timeArray[${#timeArray[*]}]=$v2
+	idtofind=`expr ${idtofind} + 1`
+    fi
+ fi
+done < ${OUT}
+$ECHO "DEBUG (${scriptName}): number of elements ${#cycleArrayBis[*]} ${#timeArray[*]}"
+$ECHO "DEBUG (${scriptName}): END"
+
+
+#########################
+# specmfib exe
+#########################
+prg="/afs/in2p3.fr/throng/baoradio/Library/Progs/TAcq/Objs/specmfib"
+if [ ! -e $prg ]; then
+    $ECHO "FATAL (${scriptName}): $prg not found"
+    exit 1
+fi
+
+
+dirFiberfile=${iojobpath}/${localpath}
+
+curDir=`pwd`
+#
+$ECHO "DEBUG (${scriptName}): in principle $dirFiberfile == $curDir "
+#
+#force single channel
+forceSingle="-singlechan"
+#debug
+prtlevel="1"
+
+
+#Loop on cycles
+##
+$ECHO "DEBUG (${scriptName}): START loop on cycles Ids ${firstCycleId} to ${lastp1CycleId}"
+
+#write the script to be send to Batch
+#get gain file if necessary
+if [ ${typeofproc} != "GAIN" ]; then
+    OUT2=./igetStatus.$$
+    iget /baoradio/data/AmasNancay/${localpath}/gain_${dateSelected}_${srclower}.fits >${OUT2} 2>&1
+    igetStatus=`$GREP "^ERROR" ${OUT2}`
+    if [ "<${igetStatus}>" != "<>" ]; then
+	$ECHO "FATAL (${scriptName}): error while iget:"
+	$ECHO $igetStatus
+	exit 1
+    fi
+    $RM ${OUT2}
+fi    
+
+
+for ((i=${firstCycleId};i<${lastp1CycleId};i++)); do
+#
+
+####
+# Check daq status
+#JEC 1/10/11 Use generic baodaqstatus name 
+####
+#get the daq current irod status
+#tag=`${DATE} +%F`
+#OUT1=${publicpath}/baodaqstatus-${tag}.txt
+OUT1=${publicpath}/baodaqstatus-current.txt
+
+if [ ! -e ${OUT1}  -o ! -r ${OUT1} ]; then
+    $ECHO "FATAL (${scriptName}): ${OUT1} has a problem"
+    exit 1
+#    $ECHO "We should bring the DAQ status more up to date, this take 1 or 2min..."
+#JEC 29/9/11 avoid finished stuff
+#    $RM -f ${tmppublicpath}/statusdaq.finished
+#    ${scriptpath}/statusdaq.sh > ${OUT1}
+#    while [ ! -f "${tmppublicpath}/statusdaq.finished" ]; do
+#	sleep 30
+#    done
+#    $RM ${tmppublicpath}/statusdaq.finished
+#protect against remove/rewriting    
+#    $CHMOD -v 444 ${OUT1} 
+fi
+
+#time window selection
+    tmproc="-tmproc ${timeArray[${i}]},${timeDuration}"
+#cycle <number>
+    cycle="${cycleArray[${i}]}"
+    if [ "<${firstCycle}>" != "<>" -a "<${lastCycle}>" != "<>" ]; then
+	if [ ${cycle} -lt ${firstCycle} -o ${cycle} -gt ${lastCycle} ]; then
+	    continue
+	fi
+    fi
+    $ECHO "DEBUG (${scriptName}): process cycle $cycle"
+
+#cycle <name><number>
+    cycle="${cyclebasename}${cycleArray[${i}]}"
+#signal files selection
+    infiles="${filesArray[${i}]}"
+#
+#Prepare BQS parameters: MEMORY, CPU...#
+    infilesArray=( `$ECHO $infiles | $AWK 'BEGIN {FS=","} {for(i=1;i<NF;i++)print $i;}'` )
+    IFS='
+    '
+    infilesArray=( $( printf "%s\n" "${infilesArray[@]}" | awk 'x[$0]++ == 0' ) )
+    IFS=$DefaultIFS
+    firstFile=${infilesArray[0]}
+    lastFile=${infilesArray[1]}
+#
+#
+#
+#get signals files
+    OUT3=./getsignals.$$
+#JEC 29/9/11 avoid finished stuff
+#    $RM -f ${tmppublicpath}/getsignalfiles.finished
+    ${scriptpath}/getsignalfiles.sh ${sourceRadio} ${dateSelected} ${firstFile}  ${lastFile} > ${OUT3} 2>&1
+#    while [ ! -f "${tmppublicpath}/getsignalfiles.finished" ]; do
+#	$ECHO "INFO (${scriptName}): waiting for ${tmppublicpath}/getsignalfiles.finished"
+#	date +%T
+#	sleep 30
+#    done
+#    $RM ${tmppublicpath}/getsignalfiles.finished
+
+    getSignals=`$GREP "^FATAL" ${OUT3}`
+    if [ "<$getSignals>" != "<>" ]; then
+	$ECHO "FATAL (${scriptName}): error while get signals"
+	$ECHO $getSignals
+	exit 1
+    fi
+    $RM ${OUT3}
+
+#location of the signal file
+    fibfile="${curDir} 1,2"
+#
+    outDir=${curDir}/${dirName}/${cycle}
+    $MKDIR -p ${outDir}
+
+#
+# where ami...
+#
+    $ECHO "We are here `pwd`"
+    $LS -lrth
+    $FIND . -name "igetStatus.*" | $XARGS -i  $CAT {}
+    $LS ./Fiber1 | $WC -l
+    $LS ./Fiber2 | $WC -l
+    $LS -lR ${outDir}
+
+#Note: here act=gain means only that specmfib will use median-like algorithms (not only for gains...)
+    $prg -act ${action} $forceSingle $freqfilter  -prt $prtlevel -out ${outDir} -nmean $nwinmean $ingain $tmproc -tspwin ${tspwin},0,0 -in $infiles ${fibfile}
+
+    $ECHO    ${outDir}
+    $LS -lrt ${outDir}
+
+#save results to Irods (use option -f ONLY to force override)
+    iput -v -K -r -f ${curDir}/${dirName} /baoradio/data/AmasNancay/${localpath}
+#
+#clean the signal files which can at the end of the day fill completly the scratch directory of the batch work/AmasNancayer
+    $RM -rf ${iojobpath}/${localpath}/Fiber1
+    $RM -rf ${iojobpath}/${localpath}/Fiber2
+#    $RM -rf ${iojobpath}/${localpath}/${typeofproc} JEC 25/10/11
+    $RM -rf ${curDir}/${dirName}
+#
+#
+
+#end loop on cycles
+done
+#
+$ECHO "DEBUG (${scriptName}): END loop on cycles"
+
+exit 0
Index: /BAORadio/AmasNancay/v5/rawonoffmaker.sh
===================================================================
--- /BAORadio/AmasNancay/v5/rawonoffmaker.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/rawonoffmaker.sh	(revision 596)
@@ -0,0 +1,330 @@
+#!/bin/sh
+#Perform the ON-OFF analysis
+DATE=/bin/date
+GREP=/bin/grep
+AWK=/bin/awk
+ECHO=/bin/echo
+WC=/usr/bin/wc
+CAT=/bin/cat
+PRINTF=/usr/bin/printf
+FIND=/usr/bin/find
+MKDIR=/bin/mkdir
+XARGS=/usr/bin/xargs
+SORT=/bin/sort
+RM=/bin/rm
+TR=/usr/bin/tr
+CP=/bin/cp
+LS=/bin/ls
+CHMOD=/bin/chmod
+
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+#set Irods environment    
+. /usr/local/shared/bin/irods_env.sh -noverbose
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+#which source to analyse
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+dateSelected=
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=Off
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -src)  sourceRadio=$2;    shift;;
+      -date) dateSelected=$2;     shift;;
+      -sim)  simulationMode=On;;
+	-h)
+	    echo >&2 \
+	    "usage: $0 -src souce -date YYYYMMDD [-freq freq in MHz (default ${freqBAOCalib})] [-sim to trig simulation mode]"
+	    exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+if [ ${simulationMode} = "On" ]; then
+    $ECHO "INFO ${scriptName} running in SIMUL mode"
+fi
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+case ${sourceRadio} in
+    Abell85) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    Abell2440) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    Abell1205) $ECHO "INFO (${scriptName}): process ${sourceRadio}";;
+    *) ECHO "FATAL (${scriptName}): process ${sourceRadio} not yet foreseen"
+    exit 1;;
+esac
+
+srclower=`${ECHO} ${sourceRadio} | ${TR} "[:upper:]" "[:lower:]" `
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+#wakeup the NFS disk
+$LS -l ${tmppublicpath} > /dev/null
+#clean previous spurious files
+$RM -f ${tmppublicpath}/*.finished
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/isInteractive.sh
+isInteractive=$(isInteractive)
+if [ ${isInteractive} == "1" ]; then
+  $ECHO "Usage in INTERACTIVE may be destructive... To be used with great care !!!!"
+   exit 0;
+fi
+
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+localpath="${sourceRadio}"
+$MKDIR -p ./${localpath}
+cd ./${localpath}
+
+#save the top directory
+topDir=`pwd`
+
+#Path of the utility scripts
+scriptpath=${SCRIPTPATH}
+
+#get the daq current irod status
+#tag=`${DATE} +%F`
+#OUT1=${publicpath}/baodaqstatus-${tag}.txt
+####JEC 1/10/11 tag=`${DATE} +%F`
+#Use generic baodaqstatus name 
+OUT1=${publicpath}/baodaqstatus-current.txt
+
+if [ ! -e ${OUT1}  -o ! -r ${OUT1} ]; then
+    $ECHO "FATAL (${scriptName}): ${OUT1} has a problem"
+    exit 1
+#JEC 29/9/11 avoid finished stuff
+#    $RM -f ${tmppublicpath}/statusdaq.finished
+#    ${scriptpath}/statusdaq.sh > ${OUT1}
+#    while [ ! -f "${tmppublicpath}/statusdaq.finished" ]; do
+#	sleep 30
+#    done
+#    $RM ${tmppublicpath}/statusdaq.finished
+#protect against remove/rewriting    
+#    $CHMOD -v 444 ${OUT1} 
+fi
+
+
+
+
+#Nb: if we want to implement a loop on sources we have to take care of srclower...
+
+$ECHO "You have selected sourceRadio = ${sourceRadio} [date = ${dateSelected}]"
+tableau=( `$GREP -i "${dateSelected}${srclower}" ${OUT1} | $AWK '( NF==4 ) { print $2 }' ` )
+IFS='
+' 
+tableau=( $( $PRINTF "%s\n" "${tableau[@]}" | $AWK 'x[$0]++ == 0' ) )
+IFS=$DefaultIFS
+
+
+for i in ${tableau[@]}
+  do
+#
+# start a "fresh" session  
+  cd ${topDir}
+  $LS | $XARGS -i $RM -rf {}
+  
+  $ECHO "DEBUG: (${scriptName}) irods root dir $i"
+  dateDAQ=`$ECHO ${i} | $AWK '{split($0,a,"/"); print a[6];}' | $AWK "{sub(/${srclower}/,\"\"); print}"`
+
+  $ECHO "DEBUG: (${scriptName}): we are in directory `pwd` the topDir=${topDir}"
+  $LS -lrt
+
+#JEC 1/10/11 Use generic baodaqstatus name 
+#Look if the date has changed since beginning of the job!
+#  curtag=`${DATE} +%F`
+#  if [ "<${curtag}>" != "<${tag}>" ]; then
+#      tag=${curtag}
+#it is necessary to update the daq status as the day has changed during the processing... (batch can take a long time...)
+#      OUT1=${publicpath}/baodaqstatus-${curtag}.txt
+#     $ECHO "We should bring the DAQ status more up to date, this take 1 or 2sec..."
+#      $RM -f ${tmppublicpath}/statusdaq.finished
+#      ${scriptpath}/statusdaq.sh > ${OUT1}
+#      while [ ! -f "${tmppublicpath}/statusdaq.finished" ]; do
+#	  sleep 30
+#      done
+#      $RM ${tmppublicpath}/statusdaq.finished
+#protect against remove/rewriting    
+#      $CHMOD -v 444 ${OUT1} 
+#  fi
+#
+# look if the gain & calibration files exist
+#
+  gainDone=`ils ${i} 2>&1 | $GREP -i "gain_.*\.fits" | $WC -l`
+  if [ ! ${gainDone} -gt 0 ]; then
+      $ECHO "FATAL (${scriptName}): gain file DOES NOT exist skip `basename $i` "
+      continue
+  fi
+
+#
+  somethingTodo=1
+  input4dataOff=`ils ${i}/Off 2>&1 | $GREP -i "datacycle" | $AWK 'BEGIN{FS="C- "}{print $2}' | $XARGS -i basename {} | $SORT -k1.10n`  
+  input4dataOn=`ils ${i}/On 2>&1 | $GREP -i "datacycle" | $AWK 'BEGIN{FS="C- "}{print $2}' | $XARGS -i basename {} | $SORT -k1.10n`  
+#
+  if [ "<${input4dataOff}>" != "<>" -a "<${input4dataOn}>" != "<>"  ]; then
+#look at the content of the datacycle directory as may be the previous batch job has crashed
+      tableauOff=( `$ECHO ${input4dataOff}` )
+      IFS='
+'
+      tableauOff=( $( $PRINTF "%s\n" "${tableauOff[@]}" | $AWK 'x[$0]++ == 0' ) )
+      IFS=$DefaultIFS
+#
+      nTotFilesOff=0
+      for j in ${tableauOff[@]}
+	do
+	nFiles=`ils ${i}/Off/${j} | $GREP -i "medfiltmtx" | $WC -l`
+	nTotFilesOff=`expr ${nTotFilesOff} + ${nFiles}`
+      done
+#
+      tableauOn=( `$ECHO ${input4dataOn}` )
+      IFS='
+      '
+      tableauOn=( $( $PRINTF "%s\n" "${tableauOn[@]}" | $AWK 'x[$0]++ == 0' ) )
+      IFS=$DefaultIFS
+#
+      nTotFilesOn=0
+      for j in ${tableauOn[@]}
+	do
+	nFiles=`ils ${i}/On/${j} | $GREP -i "medfiltmtx" | $WC -l`
+	nTotFilesOn=`expr ${nTotFilesOn} + ${nFiles}`
+      done
+      diffOnOff=`expr ${nTotFilesOff} - ${nTotFilesOn}`
+      if [ ${diffOnOff} -lt 0 ]; then
+	  zero=0
+	  diffOnOff=`expr ${zero} - ${diffOnOff}` 
+      fi
+#allow files differences but non zero
+      if [  ${nTotFilesOff} -gt 0 -a ${nTotFilesOn} -gt 0  ]; then
+	  somethingTodo=0
+	  $ECHO "DEBUG (${scriptName}): $sourceRadio $dateDAQ has <${nTotFilesOff}> Off-files and <${nTotFilesOn}> On-files but OK"
+      else
+	  $ECHO "INFO (${scriptName}): $sourceRadio $dateDAQ has <${nTotFilesOff}> Off-files and <${nTotFilesOn}> On-files => one should rebuild has something is wrong"
+      fi
+#
+#look at consecutive cycles
+
+      rmDirectory=0
+
+      cycleIdOff=`$ECHO $input4dataOff | sed 's/datacycle//g'`
+      tableauOff=( `$ECHO ${cycleIdOff}` )
+      IFS='
+'
+      tableauOff=( $( $PRINTF "%s\n" "${tableauOff[@]}" | $AWK 'x[$0]++ == 0' ) )
+      IFS=$DefaultIFS
+      
+      lastIdOff=`expr ${#tableauOff[*]} - 1`
+      ncycleOff=`expr ${tableauOff[${lastIdOff}]} - ${tableauOff[0]} + 1`
+      ncycleOffVerif=${#tableauOff[*]}
+      if [ "<${ncycleOff}>" != "<${ncycleOffVerif}>"  ]; then
+	  $ECHO "$sourceRadio $dateDAQ: There is a lack of OFF cycles in the sequence: ${tableauOff[@]}"
+	  rmDirectory=1
+	  somethingTodo=1
+      else
+	  $ECHO "$sourceRadio $dateDAQ: Ok at least consecutive OFF cycles: ${tableauOff[@]}"
+      fi
+
+      cycleIdOn=`$ECHO $input4dataOn | sed 's/datacycle//g'`
+      tableauOn=( `$ECHO ${cycleIdOn}` )
+      IFS='
+'
+      tableauOn=( $( $PRINTF "%s\n" "${tableauOn[@]}" | $AWK 'x[$0]++ == 0' ) )
+      IFS=$DefaultIFS
+      
+      lastIdOn=`expr ${#tableauOn[*]} - 1`
+      ncycleOn=`expr ${tableauOn[${lastIdOn}]} - ${tableauOn[0]} + 1`
+      ncycleOnVerif=${#tableauOn[*]}
+      if [ "<${ncycleOn}>" != "<${ncycleOnVerif}>"  ]; then
+	  $ECHO "$sourceRadio $dateDAQ: There is a lack of ON cycles in the sequence: ${tableauOn[@]}"
+	  rmDirectory=1
+	  somethingTodo=1
+      else
+	  $ECHO "$sourceRadio $dateDAQ: Ok at least consecutive ON cycles:  ${tableauOn[@]}"
+      fi
+
+      if [ "<${cycleIdOff}>" != "<${cycleIdOn}>" ]; then
+	  $ECHO "$sourceRadio $dateDAQ: cycles seq. missmatch ON and OFF"
+	  rmDirectory=1
+	  somethingTodo=1	  
+      fi
+# 
+  fi 
+########
+  if [ ${somethingTodo} -eq 1 ]; then
+#
+      $ECHO ">>>>>>>>>>>>>>>> Do $sourceRadio $dateDAQ ANALOFF"
+
+      if [ ${rmDirectory} -eq 1 ]; then
+#delete datacycle Off
+	  dirToRmOff=`ils ${i}/Off 2>&1 | $GREP -i "datacycle" | $AWK 'BEGIN{FS="C- "}{print $2}'`  
+	  tableauOff=( `$ECHO ${dirToRmOff}` )
+	  IFS='
+'
+	  tableauOff=( $( $PRINTF "%s\n" "${tableauOff[@]}" | $AWK 'x[$0]++ == 0' ) )
+	  IFS=$DefaultIFS
+	  for j in ${tableauOff[@]}
+	    do
+	    irm -f -r -v ${j}
+	  done
+#delete datacycle On
+	  dirToRmOn=`ils ${i}/On 2>&1 | $GREP -i "datacycle" | $AWK 'BEGIN{FS="C- "}{print $2}'`  
+	  tableauOn=( `$ECHO ${dirToRmOn}` )
+	  IFS='
+'
+	  tableauOn=( $( $PRINTF "%s\n" "${tableauOn[@]}" | $AWK 'x[$0]++ == 0' ) )
+	  IFS=$DefaultIFS
+	  for j in ${tableauOn[@]}
+	    do
+	    irm -f -r -v ${j}
+	  done
+      fi
+	  
+      $RM -f ${tmppublicpath}/proc_script.finished
+      if [ ${simulationMode} = "On" ]; then
+	  $ECHO "SIMUL: ${scriptpath}/proc_script.sh $sourceRadio $dateDAQ OFF"
+      else
+	  ${scriptpath}/proc_script.sh $sourceRadio $dateDAQ OFF
+	  while [ ! -e "${tmppublicpath}/proc_script.finished"  ]; do
+	      $ECHO "INFO (${scriptName}): waiting for ${tmppublicpath}/proc_script.finished"
+	      date +%T
+	      sleep 60
+	  done
+      fi
+      $ECHO "INFO (${scriptName}): proc_script has finished"
+      $ECHO ">>>>>>>>>>>> Done $sourceRadio $dateDAQ OFF"
+      $ECHO ">>>>>>>>>>>>>>>> Do $sourceRadio $dateDAQ ON"
+      $RM ${tmppublicpath}/proc_script.finished
+      
+      if [ ${simulationMode} = "On" ]; then
+	  $ECHO "SIMUL: ${scriptpath}/proc_script.sh $sourceRadio $dateDAQ ON"
+      else
+	  ${scriptpath}/proc_script.sh $sourceRadio $dateDAQ ON
+	  while [ ! -e "${tmppublicpath}/proc_script.finished"  ]; do
+	      $ECHO "INFO (${scriptName}): waiting for ${tmppublicpath}/proc_script.finished"
+	      date +%T
+	      sleep 60
+	  done
+      fi
+      $ECHO "INFO (${scriptName}): proc_script has finished"
+      $RM ${tmppublicpath}/proc_script.finished
+#Todo see if there is errors in the log file before copy
+      $ECHO ">>>>>>>>>>>> Done $sourceRadio $dateDAQ ON"
+  fi
+done
+
+exit 0
Index: /BAORadio/AmasNancay/v5/rebining.cc
===================================================================
--- /BAORadio/AmasNancay/v5/rebining.cc	(revision 596)
+++ /BAORadio/AmasNancay/v5/rebining.cc	(revision 596)
@@ -0,0 +1,132 @@
+#include "machdefs.h"
+
+//---- System et stdc++ include files
+#include <stdio.h>
+#include <stdlib.h>
+#include <math.h>
+#include <ctype.h>
+#include <string.h>
+#include <iostream>
+#include <fstream>
+#include <complex>
+
+#include <typeinfo>
+#include <string>
+#include <vector>
+#include <map>
+#include <functional>
+#include <list>
+
+//---- Sophya include files
+#include "sopnamsp.h"
+#include "basetools.h"
+#include "systools.h"
+#include "sutils.h"
+#include "ntools.h"
+#include "array.h"
+#include "histats.h"
+
+//---- Spiapp include files
+#include "nobjmgr.h"
+#include "servnobjm.h"
+
+//---- Include files from additionnal modules
+
+//---- function to compare bits on double 
+int_8 BitCmp64(double v,int_8 flg) 
+{return ((int_8)((v<0.) ? v-0.1 : v+0.1))&flg;} 
+
+//---- function for Adding and displaying Objects  
+void Keep_Object(AnyDataObj & obj, string const & nom) 
+{ 
+  string name = nom; 
+  NamedObjMgr om; 
+  if (om.GetObj(name)) 
+    cerr << "KeepObj()/Warning Already kept object " << endl; 
+  else om.AddObj(obj, name); 
+} 
+
+void Display_Object(AnyDataObj & obj, string const & opt, string const & nom) 
+ { 
+  string name = nom; 
+  NamedObjMgr om; 
+  if (!om.GetObj(name)) 
+    om.AddObj(obj, name); 
+  om.DisplayObj(name, opt); 
+} 
+
+//---- function for getting and setting ObjectManager variables  
+void Set_ObjMgrVar(MuTyV v, string const & nom) 
+{ 
+  NamedObjMgr om; 
+  om.SetVar(nom, (string)v); 
+} 
+
+MuTyV Get_ObjMgrVar(const char * nom) 
+{ 
+  string name = nom; NamedObjMgr om; 
+  MuTyV v = om.GetVar(name); 
+  return v; 
+} 
+
+//---- Macro for Objects and variables saving
+#define KeepObj(obj) Keep_Object(obj, #obj)
+#define GetOMVar(var) Get_ObjMgrVar( #var )
+#define SetOMVar(var) Set_ObjMgrVar(var, #var )
+
+//---- Macro Displaying objects and command execution
+#define DispObj(obj, att) Display_Object(obj, att, #obj); 
+
+#define ExecCmd(cmd) srvo.ExecuteCommand(cmd); 
+
+
+
+//-------------------------------------------------//
+//----------------- User Functions ----------------//
+//-------------------------------------------------//
+
+extern "C" {
+  int dorebin( vector<string>& args );
+}
+
+int dorebin( vector<string>& args )
+{
+// Some definitions to help using spiapp;
+NamedObjMgr omg;
+Services2NObjMgr& srvo = *omg.GetServiceObj();
+
+//-------------- Object List --------------
+//Number of objects = 2
+string ___nomobj;
+
+___nomobj = "invec";
+TVector< r_8 > * ___invec = dynamic_cast< TVector< r_8 >  * >(omg.GetObj(___nomobj));
+if(___invec==NULL) throw NullPtrError("CxxExecutor::PutObject: Non existing object invec... please update file");
+TVector< r_8 > & invec = (*___invec);
+
+
+
+
+//--------------------------------------------//
+//----------------- User Code ----------------//
+//--------------------------------------------//
+
+ sa_size_t length=invec.NElts();
+ sa_size_t packFactor=atoi(args[0].c_str());
+ sa_size_t redlength=length/packFactor;
+
+ TVector<r_8> outvec(redlength);
+ for (sa_size_t ibin=0; ibin<redlength; ibin++){
+   sa_size_t binLow= ibin*packFactor;
+   sa_size_t binHigh= binLow + packFactor -1;
+     TVector<r_8> tmp;
+     tmp = invec.SubVector(Range(binLow,binHigh));
+     double mean; 
+     double sigma;
+     MeanSigma(tmp,mean,sigma);
+     outvec(ibin)=mean;
+ }
+ KeepObj(outvec);
+
+return 0;
+}
Index: /BAORadio/AmasNancay/v5/reducing.cc
===================================================================
--- /BAORadio/AmasNancay/v5/reducing.cc	(revision 596)
+++ /BAORadio/AmasNancay/v5/reducing.cc	(revision 596)
@@ -0,0 +1,148 @@
+#include "machdefs.h"
+
+//---- System et stdc++ include files
+#include <stdio.h>
+#include <stdlib.h>
+#include <math.h>
+#include <ctype.h>
+#include <string.h>
+#include <iostream>
+#include <fstream>
+#include <complex>
+
+#include <typeinfo>
+#include <string>
+#include <vector>
+#include <map>
+#include <functional>
+#include <list>
+
+//---- Sophya include files
+#include "sopnamsp.h"
+#include "basetools.h"
+#include "systools.h"
+#include "sutils.h"
+#include "ntools.h"
+#include "array.h"
+#include "histats.h"
+
+//---- Spiapp include files
+#include "nobjmgr.h"
+#include "servnobjm.h"
+
+//---- Include files from additionnal modules
+
+//---- function to compare bits on double 
+int_8 BitCmp64(double v,int_8 flg) 
+{return ((int_8)((v<0.) ? v-0.1 : v+0.1))&flg;} 
+
+//---- function for Adding and displaying Objects  
+void Keep_Object(AnyDataObj & obj, string const & nom) 
+{ 
+  string name = nom; 
+  NamedObjMgr om; 
+  if (om.GetObj(name)) 
+    cerr << "KeepObj()/Warning Already kept object " << endl; 
+  else om.AddObj(obj, name); 
+} 
+
+void Display_Object(AnyDataObj & obj, string const & opt, string const & nom) 
+ { 
+  string name = nom; 
+  NamedObjMgr om; 
+  if (!om.GetObj(name)) 
+    om.AddObj(obj, name); 
+  om.DisplayObj(name, opt); 
+} 
+
+//---- function for getting and setting ObjectManager variables  
+void Set_ObjMgrVar(MuTyV v, string const & nom) 
+{ 
+  NamedObjMgr om; 
+  om.SetVar(nom, (string)v); 
+} 
+
+MuTyV Get_ObjMgrVar(const char * nom) 
+{ 
+  string name = nom; NamedObjMgr om; 
+  MuTyV v = om.GetVar(name); 
+  return v; 
+} 
+
+//---- Macro for Objects and variables saving
+#define KeepObj(obj) Keep_Object(obj, #obj)
+#define GetOMVar(var) Get_ObjMgrVar( #var )
+#define SetOMVar(var) Set_ObjMgrVar(var, #var )
+
+//---- Macro Displaying objects and command execution
+#define DispObj(obj, att) Display_Object(obj, att, #obj); 
+
+#define ExecCmd(cmd) srvo.ExecuteCommand(cmd); 
+
+
+
+//-------------------------------------------------//
+//----------------- User Functions ----------------//
+//-------------------------------------------------//
+
+extern "C" {
+  int doreduc( vector<string>& args );
+}
+
+int doreduc( vector<string>& args )
+{
+// Some definitions to help using spiapp;
+NamedObjMgr omg;
+Services2NObjMgr& srvo = *omg.GetServiceObj();
+
+//-------------- Object List --------------
+//Number of objects = 2
+string ___nomobj;
+
+___nomobj = "specv0";
+TVector< r_4 > * ___specv0 = dynamic_cast< TVector< r_4 >  * >(omg.GetObj(___nomobj));
+if(___specv0==NULL) throw NullPtrError("CxxExecutor::PutObject: Non existing object specv0... please update file");
+TVector< r_4 > & specv0 = (*___specv0);
+
+___nomobj = "specv1";
+TVector< r_4 > * ___specv1 = dynamic_cast< TVector< r_4 >  * >(omg.GetObj(___nomobj));
+if(___specv1==NULL) throw NullPtrError("CxxExecutor::PutObject: Non existing object specv1... please update file");
+TVector< r_4 > & specv1 = (*___specv1);
+
+
+
+//--------------------------------------------//
+//----------------- User Code ----------------//
+//--------------------------------------------//
+
+ sa_size_t NUMBER_OF_CHANNELS = 2;
+ sa_size_t NUMBER_OF_FREQ = 8192;
+ TMatrix<r_4> specMtxInPut(NUMBER_OF_CHANNELS,NUMBER_OF_FREQ);
+ specMtxInPut.Row(0)=specv0;
+ specMtxInPut.Row(1)=specv1;
+
+ //JEC 22/9/11 Mean & Sigma in 32-bins size START
+ sa_size_t nSliceFreq = 32; //TODO: put as an input parameter option ?
+ sa_size_t deltaFreq =  NUMBER_OF_FREQ/nSliceFreq;
+ //JEC 22/9/11 Mean & Sigma in 32-bins size END
+ 
+ TMatrix<r_4> reducedMeanDiffOnOff(NUMBER_OF_CHANNELS,nSliceFreq); //init 0 by default
+ TMatrix<r_4> reducedSigmaDiffOnOff(NUMBER_OF_CHANNELS,nSliceFreq); //init 0 by default
+ for (sa_size_t iSlice=0; iSlice<nSliceFreq; iSlice++){
+   sa_size_t freqLow= iSlice*deltaFreq;
+   sa_size_t freqHigh= freqLow + deltaFreq -1;
+   for (sa_size_t iCh=0; iCh<NUMBER_OF_CHANNELS; ++iCh){
+     TVector<r_4> reducedRow;
+     reducedRow = specMtxInPut.SubMatrix(Range(iCh),Range(freqLow,freqHigh)).CompactAllDimensions();
+     double mean; 
+     double sigma;
+     MeanSigma(reducedRow,mean,sigma);
+     reducedMeanDiffOnOff(iCh,iSlice) = mean;
+     reducedSigmaDiffOnOff(iCh,iSlice) = sigma;
+   }
+ } 
+ KeepObj(reducedMeanDiffOnOff);
+ KeepObj(reducedSigmaDiffOnOff);
+
+return 0;
+}
Index: /BAORadio/AmasNancay/v5/sca.sh
===================================================================
--- /BAORadio/AmasNancay/v5/sca.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/sca.sh	(revision 596)
@@ -0,0 +1,166 @@
+#!/bin/sh
+#
+#Script sh d'extraction de fichier SCA des sequances Diodes a Bruit (DAB) 
+#et Data des cycles ON/OFF
+#Bash script that extract from SCA files the DAB/DATA phases in ON/OFF cycles
+#It is supposed that the sequence is: DAB1 DATA1 DAB2 DATA2
+#and that the DAB1 and DAB2 have equal number of subsequences
+# Auteur: JE Campagne (LAL Orsay)
+# Creation: 11 Avril 2011
+# Revision: 12 Avril 2011
+#  o 12/04/11: mv date format to %Y-%m-%d %T for further treatment by 'date' 
+#              system function 
+
+#Basic tuning of system fuction used.
+AWK=/bin/awk
+SED=/bin/sed
+GREP=/bin/grep
+WC=/usr/bin/wc 
+RM=/bin/rm
+CAT=/bin/cat
+TOUCH=/bin/touch
+DATE=/bin/date
+ECHO=/bin/echo
+LS=/bin/ls
+MKDIR=/bin/mkdir
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+$LS -l ${tmppublicpath} > /dev/null
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+
+if [ ! $# = 1 ]
+    then
+    $ECHO "FATAL  (${scriptName}): usage: ./sca.sh <file>"
+    exit 1
+fi
+
+
+fullfile=$1
+if [ ! -e $fullfile ] 
+    then
+    $ECHO "FATAL (${scriptName}): $fullfile not found: FATAL"
+    exit 1
+fi
+
+#The output file would be in "fullprocfile"
+filename=$(basename $fullfile)
+#extension=${filename##*.}
+filename=${filename%.*}
+extension=".sum"
+fullprocfile=${filename}${extension}
+#create empty output file
+$RM -f $fullprocfile
+$TOUCH $fullprocfile
+
+
+#extract the PERI lines valid for DAB and DATA
+OUT1=./tmp1.$$
+$AWK '
+$1=="PERI" {
+   print "CYCLE",$6,$2,$3,$7,$8
+  }
+' $fullfile > $OUT1
+
+
+#Sequence of the cycle numbers (perform a unique filtering)
+tableau=( `cat $OUT1 | $AWK '{print $2}'` )
+IFS='
+'
+tableau=( $( printf "%s\n" "${tableau[@]}" | awk 'x[$0]++ == 0' ) )
+IFS=$DefaultIFS
+
+#scan each cycle
+OUT2=./tmp2.$$
+for i in ${tableau[@]}
+do
+#extract the DAB calibration phases. Hypothesis: 2 identical sequences 
+  CALIB=./tmp_cycle_${i}_calib.$$
+  $AWK -v cycle=$i '$2==cycle && $5=="-1" {print $0} ' $OUT1 > $CALIB
+  nlines=`$WC $CALIB | $AWK '{print $1}'`
+  start1=1
+  let "end1=nlines/2"
+  let "start2=end1+1"
+  end2=$nlines
+
+#date Start/End of DAB1 
+  $SED -e "${start1}!d" $CALIB | $AWK -v cycle=$i 'BEGIN {ORS=","} {
+    split($4,b,".");   
+    print cycle "," $3,b[1]}' >> ${OUT2}
+  $SED -e "${end1}!d"   $CALIB | $AWK 'BEGIN {ORS=","} {
+    split($4,b,".");   
+    print $3,b[1]}' >> ${OUT2}
+
+
+#date Start/End of DATA1: use date system function to add the duration to
+#compute the End,cf. End = Start + duration 
+  $AWK -v datesys=$DATE -v cycle=$i '$2==cycle && ( $5=="1" ) {
+    split($3,a,"/"); 
+    split($4,b,".");   
+    dateStart=a[2]"/"a[1]"/"a[3] " " b[1];
+    duree=$6 " sec";
+    cmd=sprintf("%s --date \"%s %s\"  \"+%%d/%%m/%%y %%T\" ",datesys,dateStart,duree);
+   (cmd | getline dateEnd);
+    close(cmd);  
+    ORS=","; print a[1]"/"a[2]"/"a[3] " " b[1];
+    ORS=","; print dateEnd;
+  } ' $OUT1 >> ${OUT2}
+ 
+#same as DAB1 for DAB2
+  $SED -e "${start2}!d" $CALIB | $AWK 'BEGIN {ORS=","} {
+    split($4,b,".");   
+    print $3,b[1]}' >> ${OUT2}
+  $SED -e "${end2}!d"   $CALIB | $AWK 'BEGIN {ORS=","} {
+     split($4,b,".");   
+     print $3,b[1]}' >> ${OUT2}
+#same as DATA1 for DATA2
+  $AWK -v datesys=$DATE -v cycle=$i '$2==cycle && ( $5=="2" ) {
+    split($3,a,"/"); 
+    split($4,b,".")   
+    dateStart=a[2]"/"a[1]"/"a[3] " " b[1];
+    duree=$6 " sec";
+    cmd=sprintf("%s --date \"%s %s\"  \"+%%d/%%m/%%y %%T\" ",datesys,dateStart,duree);
+   (cmd | getline dateEnd);
+    close(cmd);  
+    ORS=","; print a[1]"/"a[2]"/"a[3] " " b[1];
+    ORS="\n"; print  dateEnd;
+  } ' $OUT1 >> ${OUT2}
+#clean
+  $RM $CALIB
+done
+
+#transform all the date/time into %Y-%m-%d %T
+$AWK -v datesys=$DATE ' 
+BEGIN { FS=","; OFS="," }
+{
+  for (i=2;i<=NF;i++) {
+    split($i,a,"/");
+    newdate=a[2]"/"a[1]"/"a[3];
+    cmd=sprintf("%s --date \"%s\" \"+%%Y-%%m-%%d %%T\" ",datesys,newdate);
+    (cmd | getline newdate);
+    close(cmd);
+    $i=newdate;
+  } 
+  print $0;
+}' ${OUT2} > ${fullprocfile}
+
+
+#clean
+$RM $OUT1
+$RM $OUT2
+
+exit 0
+
+
+
Index: /BAORadio/AmasNancay/v5/scaIsOk.sh
===================================================================
--- /BAORadio/AmasNancay/v5/scaIsOk.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/scaIsOk.sh	(revision 596)
@@ -0,0 +1,81 @@
+#!/bin/sh
+#download SCA file, proceed to introspection, and upload results
+DATE=/bin/date
+GREP=/bin/grep
+AWK=/bin/awk
+ECHO=/bin/echo
+WC=/usr/bin/wc
+CAT=/bin/cat
+PRINTF=/usr/bin/printf
+MKDIR=/bin/mkdir
+RM=/bin/rm
+LS=/bin/ls
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+
+#set Irods environment    
+. /usr/local/shared/bin/irods_env.sh -noverbose
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+
+#which source to analyse
+sourceRadio=$1
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+$LS -l ${tmppublicpath} > /dev/null
+
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+
+localpath="${sourceRadio}"
+$MKDIR -p ./${localpath}
+cd ./${localpath}
+
+
+#Path of the utility scripts
+scriptpath=${SCRIPTPATH}
+
+
+#JEC 1/10/11 Use generic baodaqstatus name 
+#get the daq current irod status
+#tag=`${DATE} +%F`
+#OUT1=${publicpath}/baodaqstatus-${tag}.txt
+#OUT1=${publicpath}/baodaqstatus-2011-09-11.txt
+OUT1=${publicpath}/baodaqstatus-current.txt
+
+
+if [ ! -e ${OUT1} -o ! -r ${OUT1} ]; then
+    $ECHO "FATAL (${scriptName}): ${OUT1} is missing or not readable..."
+    exit 1
+fi
+
+if [ ! "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "You have selected sourceRadio = $sourceRadio"
+    tableau=( `$GREP -i ${sourceRadio} ${OUT1} | $AWK '( NF==4 ) { print $2 }' ` )
+else
+    tableau=( `$CAT ${OUT1} | $GREP -i "baoradio" | $AWK '( NF==4 ) { print $2 }'`  )
+fi
+IFS='
+'
+tableau=( $( $PRINTF "%s\n" "${tableau[@]}" | $AWK 'x[$0]++ == 0' ) )
+IFS=$DefaultIFS
+
+for i in ${tableau[@]}
+do
+#scrutinize irods directory
+#Nb: we do not care here if ILS returns non unique instance of a file
+  scafile=`ils -l $i 2>&1 | $GREP -i "sca[0-9][0-9]*\.[0-9][0-9]*" | $AWK '{print $NF}'`
+  if [ "<${scafile}>" = "<>" ]; then
+      $ECHO "INFO (${scriptName}): Cannot download a SCA file for `basename $i`"
+  fi
+done
Index: /BAORadio/AmasNancay/v5/scaextractor.sh
===================================================================
--- /BAORadio/AmasNancay/v5/scaextractor.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/scaextractor.sh	(revision 596)
@@ -0,0 +1,133 @@
+#!/bin/sh -xvf
+#download SCA file, proceed to introspection, and upload results
+DATE=/bin/date
+GREP=/bin/grep
+AWK=/bin/awk
+ECHO=/bin/echo
+WC=/usr/bin/wc
+CAT=/bin/cat
+PRINTF=/usr/bin/printf
+MKDIR=/bin/mkdir
+RM=/bin/rm
+LS=/bin/ls
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+
+#set Irods environment    
+. /usr/local/shared/bin/irods_env.sh -noverbose
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+
+#which source to analyse
+sourceRadio=$1
+
+#force recomputation force=Yes
+force=$2
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+$LS -l ${tmppublicpath} > /dev/null
+
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+
+localpath="${sourceRadio}"
+$MKDIR -p ./${localpath}
+cd ./${localpath}
+
+
+#Path of the utility scripts
+scriptpath=${SCRIPTPATH}
+
+
+#JEC 1/10/11 Use generic baodaqstatus name 
+#get the daq current irod status
+#tag=`${DATE} +%F`
+#OUT1=${publicpath}/baodaqstatus-${tag}.txt
+OUT1=${publicpath}/baodaqstatus-current.txt
+
+
+if [ ! -e ${OUT1} -o ! -r ${OUT1} ]; then
+    $ECHO "FATAL (${scriptName}): ${OUT1} has a problem"
+    exit 1
+fi
+
+if [ ! "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "You have selected sourceRadio = $sourceRadio"
+    tableau=( `$GREP -i ${sourceRadio} ${OUT1} | $AWK '( NF==4 ) { print $2 }' ` )
+else
+    tableau=( `$CAT ${OUT1} | $AWK'( NF==4 ) { print $2 }'`  )
+fi
+IFS='
+'
+tableau=( $( $PRINTF "%s\n" "${tableau[@]}" | $AWK 'x[$0]++ == 0' ) )
+IFS=$DefaultIFS
+
+for i in ${tableau[@]}
+do
+OUT2=./baodir.$$
+#scrutinize irods directory
+#Nb: we do not care here if ILS returns non unique instance of a file
+  ils -l $i 2>&1 | $GREP -i "sca" > ${OUT2}
+  $CAT ${OUT2}
+#test if the SCA file has been already processed
+  scatrans=`$GREP -i "sca.*\.sum\.trans" ${OUT2} | $AWK '{print $NF}'`
+#test if the file is empty due to previous processing dysfunction
+  emptyfile=`$GREP -i "sca.*\.sum\.trans" ${OUT2} | $AWK '{print $4}'`
+#  echo "scrutinize directory <$i>: [$nblines] [$scatrans]" 
+  if [ "<${scatrans}>" = "<>" -o "<${emptyfile}>" = "<0>" -o "<${force}>" = "<Yes>" ]; then
+      $ECHO "$i may be non prepared for analysis..."
+      scafile=`$GREP -i "sca[0-9][0-9]*\.[0-9][0-9]*" ${OUT2} | $AWK '{print $NF}'`
+      if [ "<${scafile}>" = "<>" ]; then
+	  $ECHO "WARNING (${scriptName}): Cannot download a SCA file for $i"
+      else
+#get sca file
+        iget -r -f -v -K ${i}/${scafile} ${iojobpath}
+#extract summary (sum extension)
+#JEC 29/9/11 avoid finished stuff
+	$RM -f ${tmppublicpath}/sca.finished
+	${scriptpath}/sca.sh ${scafile}
+#	while [ ! -e "${tmppublicpath}/sca.finished" ]; do
+#	    $ECHO "INFO (${scriptName}); waiting for ${tmppublicpath}/sca.finished"
+#	    date +%T
+#	    sleep 30
+#	done
+	$ECHO "INFO (${scriptName}): sca.sh has finished"
+#	$RM ${tmppublicpath}/sca.finished
+#TODO see if there is errors...
+        scaFileName=$(basename $scafile)
+	scaFileName=${scaFileName%.*}
+#transform the date (sum.trans extension)
+#JEC 29/9/11 avoid finished stuff
+#	$RM -f ${tmppublicpath}/transdate.finished
+        ${scriptpath}/transdate.sh ${scaFileName}.sum
+#	while [ ! -e "${tmppublicpath}/transdate.finished" ]; do
+#	    $ECHO "INFO (${scriptName}); waiting for ${tmppublicpath}/transdate.finished"
+#	    date +%T
+#	    sleep 30
+#	done
+	$ECHO "INFO (${scriptName}): transdate.sh  has finished"
+#	$RM ${tmppublicpath}/transdate.finished
+#TODO see if there is errors...	
+#put back into Irod
+#	$ECHO "INFO (${scriptName}): where am i: `pwd`"
+#	$LS -lrt
+#	$ECHO "INFO (${scriptName}): see up directory"
+#	$LS -lrt ..
+	iput -f -v -K ${iojobpath}/${scaFileName}.sum $i
+	iput -f -v -K ${iojobpath}/${scaFileName}.sum.trans $i
+      fi
+  fi
+$RM ${OUT2}
+done
+
+exit 0
Index: /BAORadio/AmasNancay/v5/select.sh
===================================================================
--- /BAORadio/AmasNancay/v5/select.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/select.sh	(revision 596)
@@ -0,0 +1,229 @@
+#!/bin/sh
+
+#hypothesis: ON = data1 phase, OFF data2 phase
+
+#Basic tuning of system fuction used.
+AWK=/bin/awk
+SED=/bin/sed
+GREP=/bin/grep
+WC=/usr/bin/wc
+RM=/bin/rm
+CAT=/bin/cat
+TOUCH=/bin/touch
+DATE=/bin/date
+ECHO=/bin/echo
+FIND=/usr/bin/find
+XARGS=/usr/bin/xargs
+SORT=/bin/sort
+MKDIR=/bin/mkdir
+LS=/bin/ls
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+
+if [ ! $# = 3 ]; then
+  $ECHO "usage: ${scriptName} <scaXYZ.sum> <signalXYZDirectory> <type of phase:ON|OFF|CALIBON|CALIBOFF>"
+  exit 0
+fi
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+$LS -l ${tmppublicpath} > /dev/null
+
+
+#Path of the utility scripts
+scriptpath=${SCRIPTPATH}
+
+
+OUT1=./selectFits.$$
+
+#inputs x-chexk sca file
+inScaFile=$1
+if [ ! -e $inScaFile ]; then
+  $ECHO "FATAL (${scriptName}): $inScaFile not found"
+  exit 1
+fi
+
+#Where to look at
+inFiberDir=$2
+
+inTypeOfPhase=$3
+case "$inTypeOfPhase" in
+    ON) 
+    $ECHO "INFO (${scriptName}): filter signal files for ON phases";;
+    OFF) 
+    $ECHO "INFO (${scriptName}): filter signal files for OFF phases";;
+    MEANON) 
+    $ECHO "INFO (${scriptName}): filter signal files for MEANON phases";;
+    MEANOFF) 
+    $ECHO "INFO (${scriptName}): filter signal files for MEANOFF phases";;
+    CALIBON) 
+    $ECHO "INFO (${scriptName}): filter signal files for CALIBRATION ON phases";;
+    CALIBOFF) 
+    $ECHO "INFO (${scriptName}): filter signal files for CALIBRATION OFF phases";;
+    GAIN) 
+    $ECHO "INFO (${scriptName}): filter signal files for GAIN = CALIB OFF phases";;
+    GAINNF)
+    $ECHO "INFO (${scriptName}): filter signal files for GAINNF = GAIN wo filt. freq.";;
+    *) 
+    $ECHO "FATAL (${scriptName}): use ON|OFF|MEANON|MEANOFF|CALIBON|CALIBOFF phase tags."
+    exit 1
+    ;;
+esac
+
+
+#################
+#fill the arrays association header file with start/end date&time 
+# arrays
+declare -a sigStart
+declare -a sigEnd
+declare -a sigFile
+
+for fullfile in $( $FIND $inFiberDir -name "header*" | $XARGS -i basename {} | $SORT -k1.7n)
+  do
+  filename=$(basename $fullfile)
+  extension=${filename##*.}
+  filename=${filename%.*}
+  ffn=${inFiberDir}/${filename}.${extension}
+#  echo "process $ffn"
+  while read -n80 L
+    do
+    [ "${L::3}" = "END" ] && break
+    echo $L
+  done < $ffn > $OUT1
+  
+  strStart=`$GREP TMSTART $OUT1 | $AWK '{split($0,a,"/"); split(a[1],b,"="); print b[2];}' | $SED 's/^[ \t]*//;s/[ \t]*$//'  | $SED "s/^\([\"']\)\(.*\)\1\$/\2/g" | $AWK '{split($0,a,"T"); print a[1]" "a[2];}' `
+  
+  strEnd=`$GREP TMEND $OUT1 | $AWK '{split($0,a,"/"); split(a[1],b,"="); print b[2];}' |  $SED 's/^[ \t]*//;s/[ \t]*$//'  | $SED "s/^\([\"']\)\(.*\)\1\$/\2/g" | $AWK '{split($0,a,"T"); print a[1]" "a[2];}' `
+  
+  if [[ -n "$strStart"  &&  -n "$strEnd" ]]; then
+      timeStart=`${DATE} +%s -d "${strStart}"`
+      timeEnd=`${DATE} +%s -d "${strEnd}"`
+#      echo "$fullfile start $strStart   <$timeStart>, end  $strEnd <$timeEnd>"
+      sigStart[${#sigStart[*]}]=$timeStart
+      sigEnd[${#sigEnd[*]}]=$timeEnd
+      sigFile[${#sigFile[*]}]=$filename
+  else
+      $ECHO "WARNING (${scriptName}): $ffn PATHOLOGIQUE"
+  fi
+done
+
+############
+#scan all the cycles 
+#  calib1start=$2; calib1end=$3; 
+#  data1start=$4; data1end=$5;
+#  calib2start=$6; calib2end=$7; 
+#  data2start=$8; data2end=$9;
+#to pass to awk: use a "," as field separator
+awk_sigStart=$( printf "%s," "${sigStart[@]}" )
+awk_sigEnd=$( printf "%s," "${sigEnd[@]}" )
+awk_sigFile=$( printf "%s," "${sigFile[@]}" )
+
+#attention a la derniere "," pour le calcul de nfile
+OUT1=./tmpselect1.$$
+#selection d'une seul cycle pour debug 
+$AWK -v datesys=$DATE -v type=$inTypeOfPhase -v str_sigStart="$awk_sigStart"  -v str_sigEnd="$awk_sigEnd"  -v str_sigFile="$awk_sigFile" '
+BEGIN { 
+  FS=",";
+  split(str_sigStart,a_sigStart,",");
+  split(str_sigEnd,a_sigEnd,",");
+  nfile=split(str_sigFile,a_sigFile,",");
+  delete a_sigFile[nfile];
+  delete a_sigStart[nfile];
+  delete a_sigEnd[nfile];
+  nfile--;  
+
+}
+
+ {
+  cycle=$1; 
+
+  if ( (type == "ON") || (type == "MEANON") ) {
+    phaseStart=$4; phaseEnd=$5;
+    cmd=sprintf("%s +%%s -d \"%s\" ",datesys,phaseStart);
+    (cmd | getline phstart);
+    close(cmd);
+    cmd=sprintf("%s +%%s -d \"%s\" ",datesys,phaseEnd);
+    (cmd | getline phend);
+    close(cmd);
+    # print "Phase: ",type," cycle: ",cycle,": <",phstart,">:<",phend,">";
+    deltaStartSafety=4;
+    deltaEndSafety=-4;
+  }
+  else if ( (type == "OFF") || (type == "MEANOFF") ) {
+    phaseStart=$8; phaseEnd=$9;
+    cmd=sprintf("%s +%%s -d \"%s\" ",datesys,phaseStart);
+    (cmd | getline phstart);
+    close(cmd);
+    cmd=sprintf("%s +%%s -d \"%s\" ",datesys,phaseEnd);
+    (cmd | getline phend);
+    close(cmd);
+    # print "Phase: ",type," cycle: ",cycle,": <",phstart,">:<",phend,">";
+    deltaStartSafety=4;
+    deltaEndSafety=-4;
+  } 
+  else if ( type == "CALIBON" ) {
+    phaseStart=$2; phaseEnd=$3;
+    print "Phase: ",type," cycle: ",cycle,": <",phaseStart,">:<",phaseEnd,">";
+    cmd=sprintf("%s +%%s -d \"%s\" ",datesys,phaseStart);
+    (cmd | getline phstart);
+    close(cmd);
+    cmd=sprintf("%s +%%s -d \"%s\" ",datesys,phaseEnd);
+    (cmd | getline phend);
+    close(cmd);
+#    print "Phase: ",type," cycle: ",cycle,": <",phstart,">:<",phend,">";
+    deltaStartSafety=-6;
+    deltaEndSafety=6;
+  } 
+  else if ( (type == "CALIBOFF") || (type == "GAIN") || (type == "GAINNF")) {
+    phaseStart=$6; phaseEnd=$7;
+    cmd=sprintf("%s +%%s -d \"%s\" ",datesys,phaseStart);
+    (cmd | getline phstart);
+    close(cmd);
+    cmd=sprintf("%s +%%s -d \"%s\" ",datesys,phaseEnd);
+    (cmd | getline phend);
+    close(cmd);
+    # print "Phase: ",type," cycle: ",cycle,": <",phstart,">:<",phend,">";
+    deltaStartSafety=-6;
+    deltaEndSafety=6;
+  } 
+  else { 
+    print "FATAL: ",type," NOT YET SUPPORTED"; exit 1;
+  }
+
+  for (i=1; i<=nfile; i++) {
+    diffstart = a_sigStart[i] - phstart;
+    diffend   = a_sigEnd[i] - phend;
+#     print "file ",i," start ",a_sigStart[i],": diff <" diffstart ">:<" diffend ">";
+    if ( diffstart >= deltaStartSafety && diffend <= deltaEndSafety )
+       print "cycle ",cycle," file ",i-1," accepted ",a_sigFile[i];
+  }  
+     
+
+}' $inScaFile > ${OUT1}
+
+OUT2=./tmpselect2.$$
+$AWK '
+BEGIN { max=0; min=999999; }; 
+
+($1=="cycle") { table[$2] = table[$2]","$4; if($2>max){max=$2}; if($2<min){min=$2} }; 
+
+END { for (j=min;j<=max;j++) {print j,table[j];} }
+' ${OUT1} > ${OUT2}
+
+$AWK '
+BEGIN { FS=","}
+{
+ print "#"$1,$2","$NF",1";
+}
+' ${OUT2}
+
+$RM $OUT1
+$RM $OUT2
+
+exit 0
Index: /BAORadio/AmasNancay/v5/set_iojobpath.sh
===================================================================
--- /BAORadio/AmasNancay/v5/set_iojobpath.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/set_iojobpath.sh	(revision 596)
@@ -0,0 +1,19 @@
+set_iojobpath()
+{
+  if [ ${ENVIRONMENT} == "INTERACTIVE" -o ${ENVIRONMENT} == "ACCESS" ]; then
+      iojobpath=${IOJOBPATH}
+      $MKDIR -p $iojobpath
+
+  elif [ ${ENVIRONMENT} == "BATCH" ]; then
+    iojobpath=${TMPBATCH}
+
+  elif [ ${ENVIRONMENT} == "SEQUENTIAL_BATCH" -o ${ENVIRONMENT} == "PARALLEL_BATCH" -o  ${ENVIRONMENT} == "INTERACTIVE_BATCH" ]; then
+    iojobpath=${TMPDIR}
+
+  else
+    $ECHO "FATAL: environment is ${ENVIRONMENT} not allowed"
+    exit 1
+  fi
+  $ECHO ${iojobpath}
+
+}
Index: /BAORadio/AmasNancay/v5/statusCycles.sh
===================================================================
--- /BAORadio/AmasNancay/v5/statusCycles.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/statusCycles.sh	(revision 596)
@@ -0,0 +1,99 @@
+#!/bin/sh
+#liste des "sources" enregistrees sous Amas
+AWK=/bin/awk
+SED=/bin/sed
+GREP=/bin/grep
+WC=/usr/bin/wc
+RM=/bin/rm
+CAT=/bin/cat
+TOUCH=/bin/touch
+DATE=/bin/date
+ECHO=/bin/echo
+LS=/bin/ls
+MKDIR=/bin/mkdir
+TR=/usr/bin/tr
+FIND=/usr/bin/find
+PRINTF=/usr/bin/printf
+XARGS=/usr/bin/xargs
+SORT=/bin/sort
+QSUB=qsub
+
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+trim() { echo $1; }
+
+
+# Irods environment settings
+. /usr/local/shared/bin/irods_env.sh -noverbose
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+$LS -l ${tmppublicpath} > /dev/null
+
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath) 
+cd ${iojobpath}
+
+
+OUT1=./baoils.$$
+ils /baoradio/data/AmasNancay/ > ${OUT1}
+OUT2=./baoawk1.$$
+$AWK '($1=="C-") {print $2}' ${OUT1} > ${OUT2}
+$RM $OUT1
+#Sequence 
+tableau=( `$CAT $OUT2 | $AWK '{print $1}'` )
+IFS='
+'
+tableau=( $( $PRINTF "%s\n" "${tableau[@]}" | $AWK 'x[$0]++ == 0' ) )
+IFS=$DefaultIFS
+
+$RM $OUT2
+
+for i in ${tableau[@]}
+do
+  OUT2=./baodir.$$
+  $ECHO "source $i"
+  listedate=( `ils $i | $AWK '($1=="C-"){print $2}'`)
+  IFS='
+'
+  listedate=( $( $PRINTF "%s\n" "${listedate[@]}" | $AWK 'x[$0]++ == 0' ) )
+  IFS=$DefaultIFS
+
+  for j in ${listedate[@]}
+  do
+    ils -l $j 2>&1 | $GREP -i "sca" > ${OUT2}
+#test if the SCA file has been already processed
+    scatrans=`$GREP -i "sca.*\.sum\.trans" ${OUT2} | $AWK '{print $NF}'`
+#test if the file is empty due to previous processing dysfunction
+    emptyfile=`$GREP -i "sca.*\.sum\.trans" ${OUT2} | $AWK '{print $4}'`
+#  echo "scrutinize directory <$i>: [$nblines] [$scatrans]" 
+    if [ "<${scatrans}>" != "<>" ]; then
+	scafile=`$GREP -i "sca.*\.sum\.trans" ${OUT2} | $AWK '{print $NF}'`
+	if [ "<${scafile}>" = "<>" ]; then
+	    $ECHO "WARNING (${scriptName}): Cannot download a SCA file for $j"
+	else
+#get sca file
+	    iget -r -f -K ${j}/${scafile}
+	    ncycle=`$CAT ${scafile} | $WC -l`
+	    $RM ${scafile}
+	    $ECHO ">>> $j ---> ${ncycle} cycles"
+	fi
+    else
+	$ECHO ">>> $j ---> NO SCA summary"
+    fi
+  done 
+  $RM ${OUT2}
+done
+
+
+
Index: /BAORadio/AmasNancay/v5/statuscalib.sh
===================================================================
--- /BAORadio/AmasNancay/v5/statuscalib.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/statuscalib.sh	(revision 596)
@@ -0,0 +1,131 @@
+#!/bin/sh
+#Status de l'etat de la production des fichiers INPUT de calibrations
+GREP=/bin/grep
+AWK=/bin/awk
+ECHO=/bin/echo
+MKDIR=/bin/mkdir
+CAT=/bin/cat
+PRINTF=/usr/bin/printf
+RM=/bin/rm
+SORT=/bin/sort
+XARGS=/usr/bin/xargs
+WC=/usr/bin/wc
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+# Irods environment settings
+. /usr/local/shared/bin/irods_env.sh -noverbose
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+
+OUT1=./baoils.$$
+ils /baoradio/data/AmasNancay/ > ${OUT1}
+OUT2=./baoawk1.$$
+$AWK '($1=="C-") {print $2}' ${OUT1} > ${OUT2}
+$RM $OUT1
+#Sequence 
+listeSources=( `$CAT $OUT2 | $AWK '{print $1}'` )
+IFS='
+'
+listeSources=( $( $PRINTF "%s\n" "${listeSources[@]}" | $AWK 'x[$0]++ == 0' ) )
+IFS=$DefaultIFS
+$RM $OUT2
+
+for i in ${listeSources[@]}
+do
+#nb: $i contains the full path
+  $ECHO "source ${i}"
+  sourceName=`basename ${i}`
+  listeDates=( `ils $i | $AWK '($1=="C-"){print $2}'`)
+  IFS='
+'
+  listeDates=( $( $PRINTF "%s\n" "${listeDates[@]}" | $AWK 'x[$0]++ == 0' ) )
+  IFS=$DefaultIFS
+
+  for j in ${listeDates[@]}
+  do
+#nb: $j contains the full path
+#  $ECHO "run ${j}"
+#
+#Off directory
+#
+    dateField=`basename ${j}`
+    sourceDate="${sourceName}-${dateField}"
+#look if final calibration files exist
+    calibOk=`ils ${j} | $GREP -i "calib_" | $WC -l`
+
+    offDirExist=`ils ${j} | $GREP -i "Off" | $WC -l`
+    if [ ${offDirExist} != 0 ]; then
+	listeCyclesOff=( `ils ${j}/Off | $GREP -i "calibcycle" | $AWK '($1=="C-"){print $2}' | $XARGS -i basename {} | $SORT -k1.11n` )
+	IFS='
+  '
+	listeCyclesOff=( $( $PRINTF "%s\n" "${listeCyclesOff[@]}" | $AWK 'x[$0]++ == 0' ) )
+	IFS=$DefaultIFS
+	
+	if [ ${#listeCyclesOff[*]} != 0 ]; then    
+           for c in ${listeCyclesOff[@]}
+	   do
+#nb: $c has the format of calibcycle<number>
+	     nFiles=`ils ${j}/Off/${c} | $GREP -i "medfiltmtx" | $WC -l`
+	     if [ ${nFiles} != 0 ]; then
+		 $ECHO "${sourceDate}/Off/${c}: ${nFiles} spectra (${calibOk} calib)"
+	     else
+		 $ECHO "${sourceDate}/Off/${c}: Calibration failed"
+	     fi
+#end of loop on cycles 
+	   done
+	else
+	    $ECHO "${sourceDate} : No Calibration done for Off Directory"
+	fi
+#end of Off exist
+    else
+	$ECHO "${sourceDate} : No Off Directory"
+    fi
+#
+#On directory
+#
+    dateField=`basename ${j}`
+    sourceDate="${sourceName}-${dateField}"
+#look if final calibration files exist
+    calibOk=`ils ${j} | $GREP -i "calib_" | $WC -l`
+    onDirExist=`ils ${j} | $GREP -i "On" | $WC -l`
+    if [ ${onDirExist} != 0 ]; then
+	listeCyclesOn=( `ils ${j}/On | $GREP -i "calibcycle" | $AWK '($1=="C-"){print $2}' | $XARGS -i basename {} | $SORT -k1.11n` )
+	IFS='
+  '
+	listeCyclesOn=( $( $PRINTF "%s\n" "${listeCyclesOn[@]}" | $AWK 'x[$0]++ == 0' ) )
+	IFS=$DefaultIFS
+	
+	if [ ${#listeCyclesOn[*]} != 0 ]; then    
+           for c in ${listeCyclesOn[@]}
+	   do
+#nb: $c has the format of calibcycle<number>
+	     nFiles=`ils ${j}/On/${c} | $GREP -i "medfiltmtx" | $WC -l`
+	     if [ ${nFiles} != 0 ]; then
+		 $ECHO "${sourceDate}/On/${c}: ${nFiles} spectra (${calibOk} calib)"
+	     else
+		 $ECHO "${sourceDate}/On/${c}: Calibration failed"
+	     fi
+#end of loop on cycles 
+	   done
+	else
+	    $ECHO "${sourceDate} : No Calibration done for On Directory"
+	fi
+#end of On exist
+    else
+	$ECHO "${sourceDate} : No On Directory"
+    fi
+#end of loop on dates
+  done 
+#end of loop on sources
+done
Index: /BAORadio/AmasNancay/v5/statusdaq.sh
===================================================================
--- /BAORadio/AmasNancay/v5/statusdaq.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/statusdaq.sh	(revision 596)
@@ -0,0 +1,79 @@
+#!/bin/sh
+#liste des "sources" enregistrees sous Amas
+GREP=/bin/grep
+AWK=/bin/awk
+ECHO=/bin/echo
+MKDIR=/bin/mkdir
+CAT=/bin/cat
+PRINTF=/usr/bin/printf
+LS=/bin/ls
+RM=/bin/rm
+SORT=/bin/sort
+XARGS=/usr/bin/xargs
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+
+# Irods environment settings
+. /usr/local/shared/bin/irods_env.sh -noverbose
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+$LS -l ${tmppublicpath} > /dev/null
+
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+
+OUT1=./baoils.$$
+ils /baoradio/data/AmasNancay/ > ${OUT1}
+OUT2=./baoawk1.$$
+$AWK '($1=="C-") {print $2}' ${OUT1} > ${OUT2}
+$RM $OUT1
+
+#Sequence 
+tableau=( `$CAT $OUT2 | $AWK '{print $1}'` )
+IFS='
+'
+tableau=( $( $PRINTF "%s\n" "${tableau[@]}" | $AWK 'x[$0]++ == 0' ) )
+IFS=$DefaultIFS
+
+$RM $OUT2
+
+for i in ${tableau[@]}
+do
+  $ECHO "source $i"
+  listedate=( `ils $i | $AWK '($1=="C-"){print $2}'`)
+  IFS='
+'
+  listedate=( $( $PRINTF "%s\n" "${listedate[@]}" | $AWK 'x[$0]++ == 0' ) )
+  IFS=$DefaultIFS
+
+  ntotfiles=0
+  for j in ${listedate[@]}
+  do
+#Nb: care should be taken to the possible instances of a file returned by ILS
+    listOfsig=( `ils ${j}/Fiber1 | $GREP -i "signal" | $XARGS -i basename {} | $SORT -k1.7n` )
+    IFS='
+  '
+    listOfsig=( $( $PRINTF "%s\n" "${listOfsig[@]}" | $AWK 'x[$0]++ == 0' ) )
+    IFS=$DefaultIFS
+    nfiles=${#listOfsig[@]}
+    $ECHO ">>> $j ---> $nfiles"
+    let "ntotfiles=ntotfiles+nfiles"
+  done 
+  $ECHO "total files = $ntotfiles"
+
+done
+
+exit 0
Index: /BAORadio/AmasNancay/v5/statusgain.sh
===================================================================
--- /BAORadio/AmasNancay/v5/statusgain.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/statusgain.sh	(revision 596)
@@ -0,0 +1,63 @@
+#!/bin/sh
+#liste des "sources" enregistrees sous Amas
+GREP=/bin/grep
+AWK=/bin/awk
+ECHO=/bin/echo
+MKDIR=/bin/mkdir
+CAT=/bin/cat
+PRINTF=/usr/bin/printf
+RM=/bin/rm
+SORT=/bin/sort
+XARGS=/usr/bin/xargs
+WC=/usr/bin/wc
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+# Irods environment settings
+. /usr/local/shared/bin/irods_env.sh -noverbose
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+
+OUT1=./baoils.$$
+ils /baoradio/data/AmasNancay/ > ${OUT1}
+OUT2=./baoawk1.$$
+$AWK '($1=="C-") {print $2}' ${OUT1} > ${OUT2}
+$RM $OUT1
+#Sequence 
+tableau=( `$CAT $OUT2 | $AWK '{print $1}'` )
+IFS='
+'
+tableau=( $( $PRINTF "%s\n" "${tableau[@]}" | $AWK 'x[$0]++ == 0' ) )
+IFS=$DefaultIFS
+
+$RM $OUT2
+
+for i in ${tableau[@]}
+do
+  $ECHO "source $i"
+  listedate=( `ils $i | $AWK '($1=="C-"){print $2}'`)
+  IFS='
+'
+  listedate=( $( $PRINTF "%s\n" "${listedate[@]}" | $AWK 'x[$0]++ == 0' ) )
+  IFS=$DefaultIFS
+
+  for j in ${listedate[@]}
+  do
+    gainOk=`ils ${j} | $GREP -i "gain_" | $WC -l`
+    if [ ${gainOk} -gt 0 ]; then
+	$ECHO ">>> $j ---> GAIN Done (${gainOk})"
+    else
+	$ECHO ">>> $j ---> GAIN To be computed"
+    fi
+  done 
+done
Index: /BAORadio/AmasNancay/v5/statusheader.sh
===================================================================
--- /BAORadio/AmasNancay/v5/statusheader.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/statusheader.sh	(revision 596)
@@ -0,0 +1,87 @@
+#!/bin/sh
+#liste des "sources" enregistrees sous Amas
+GREP=/bin/grep
+AWK=/bin/awk
+ECHO=/bin/echo
+MKDIR=/bin/mkdir
+CAT=/bin/cat
+PRINTF=/usr/bin/printf
+RM=/bin/rm
+SORT=/bin/sort
+XARGS=/usr/bin/xargs
+WC=/usr/bin/wc
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+# Irods environment settings
+. /usr/local/shared/bin/irods_env.sh -noverbose
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+
+OUT1=./baoils.$$
+ils /baoradio/data/AmasNancay/ > ${OUT1}
+OUT2=./baoawk1.$$
+$AWK '($1=="C-") {print $2}' ${OUT1} > ${OUT2}
+$RM $OUT1
+#Sequence 
+tableau=( `$CAT $OUT2 | $AWK '{print $1}'` )
+IFS='
+'
+tableau=( $( $PRINTF "%s\n" "${tableau[@]}" | $AWK 'x[$0]++ == 0' ) )
+IFS=$DefaultIFS
+
+$RM $OUT2
+
+for i in ${tableau[@]}
+do
+  $ECHO "source $i"
+  listedate=( `ils $i | $AWK '($1=="C-"){print $2}'`)
+  IFS='
+'
+  listedate=( $( $PRINTF "%s\n" "${listedate[@]}" | $AWK 'x[$0]++ == 0' ) )
+
+  ntotfiles=0
+  for j in ${listedate[@]}
+  do
+#Fiber 1
+    listOfsig1=( `ils ${j}/Fiber1 | $GREP -i "signal" | $XARGS -i basename {} | $SORT -k1.7n` )
+    IFS='
+  '
+    listOfsig1=( $( $PRINTF "%s\n" "${listOfsig1[@]}" | $AWK 'x[$0]++ == 0' ) )
+    nblinesSIG1=${#listOfsig1[@]}
+    listOfhdr1=( `ils ${j}/Fiber1 | $GREP -i "header" | $XARGS -i basename {} | $SORT -k1.7n` )
+    IFS='
+    '
+    listOfhdr1=( $( $PRINTF "%s\n" "${listOfhdr1[@]}" | $AWK 'x[$0]++ == 0' ) )
+    nblinesHDR1=${#listOfhdr1[@]}
+
+#Fiber 2
+    listOfsig2=( `ils ${j}/Fiber2 | $GREP -i "signal" | $XARGS -i basename {} | $SORT -k1.7n` )
+    IFS='
+  '
+    listOfsig2=( $( $PRINTF "%s\n" "${listOfsig2[@]}" | $AWK 'x[$0]++ == 0' ) )
+    nblinesSIG2=${#listOfsig2[@]}
+    listOfhdr2=( `ils ${j}/Fiber2 | $GREP -i "header" | $XARGS -i basename {} | $SORT -k1.7n` )
+    IFS='
+    '
+    listOfhdr2=( $( $PRINTF "%s\n" "${listOfhdr2[@]}" | $AWK 'x[$0]++ == 0' ) )
+    nblinesHDR2=${#listOfhdr2[@]}
+
+
+
+    $ECHO ">>> $j --->  Fib1: $nblinesHDR1 / $nblinesSIG1 Fib2: $nblinesHDR2 / $nblinesSIG2"
+    let "ntotfiles=ntotfiles+$nblinesSIG1"
+  done 
+  $ECHO "total signal Fiber1 files = $ntotfiles"
+
+done
Index: /BAORadio/AmasNancay/v5/statusonoff.sh
===================================================================
--- /BAORadio/AmasNancay/v5/statusonoff.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/statusonoff.sh	(revision 596)
@@ -0,0 +1,130 @@
+#!/bin/sh
+#Status de l'etat de la production des fichiers INPUT de calibrations
+GREP=/bin/grep
+AWK=/bin/awk
+ECHO=/bin/echo
+MKDIR=/bin/mkdir
+CAT=/bin/cat
+PRINTF=/usr/bin/printf
+RM=/bin/rm
+SORT=/bin/sort
+XARGS=/usr/bin/xargs
+WC=/usr/bin/wc
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+# Irods environment settings
+. /usr/local/shared/bin/irods_env.sh -noverbose
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+
+OUT1=./baoils.$$
+ils /baoradio/data/AmasNancay/ > ${OUT1}
+OUT2=./baoawk1.$$
+$AWK '($1=="C-") {print $2}' ${OUT1} > ${OUT2}
+$RM $OUT1
+#Sequence 
+listeSources=( `$CAT $OUT2 | $AWK '{print $1}'` )
+IFS='
+'
+listeSources=( $( $PRINTF "%s\n" "${listeSources[@]}" | $AWK 'x[$0]++ == 0' ) )
+IFS=$DefaultIFS
+$RM $OUT2
+
+for i in ${listeSources[@]}
+do
+#nb: $i contains the full path
+  $ECHO "source ${i}"
+  sourceName=`basename ${i}`
+  listeDates=( `ils $i | $AWK '($1=="C-"){print $2}'`)
+  IFS='
+'
+  listeDates=( $( $PRINTF "%s\n" "${listeDates[@]}" | $AWK 'x[$0]++ == 0' ) )
+  IFS=$DefaultIFS
+
+  for j in ${listeDates[@]}
+  do
+#nb: $j contains the full path
+#  $ECHO "run ${j}"
+#
+#Off directory
+#
+    dateField=`basename ${j}`
+    sourceDate="${sourceName}-${dateField}"
+#look if final data processing files exist
+    onOffOk=`ils ${j} | $GREP -i "data.*\.ppf\|diff.*\.ppf" | $WC -l`
+    offDirExist=`ils ${j} | $GREP -i "Off" | $WC -l`
+    if [ ${offDirExist} != 0 ]; then
+	listeCyclesOff=( `ils ${j}/Off | $GREP -i "datacycle" | $AWK '($1=="C-"){print $2}' | $XARGS -i basename {} | $SORT -k1.11n` )
+	IFS='
+  '
+	listeCyclesOff=( $( $PRINTF "%s\n" "${listeCyclesOff[@]}" | $AWK 'x[$0]++ == 0' ) )
+	IFS=$DefaultIFS
+	
+	if [ ${#listeCyclesOff[*]} != 0 ]; then    
+           for c in ${listeCyclesOff[@]}
+	   do
+#nb: $c has the format of datacycle<number>
+	     nFiles=`ils ${j}/Off/${c} | $GREP -i "medfiltmtx" | $WC -l`
+	     if [ ${nFiles} != 0 ]; then
+		 $ECHO "${sourceDate}/Off/${c}: ${nFiles} spectra (${onOffOk} ana)"
+	     else
+		 $ECHO "${sourceDate}/Off/${c}: ON-OFF failed"
+	     fi
+#end of loop on cycles 
+	   done
+	else
+	    $ECHO "${sourceDate} : No ON-OFF done for Off Diectory"
+	fi
+#end of Off exist
+    else
+	$ECHO "${sourceDate} : No Off Diectory"
+    fi
+#
+#On directory
+#
+    dateField=`basename ${j}`
+    sourceDate="${sourceName}-${dateField}"
+#look if final calibration files exist
+    onOnOk=`ils ${j} | $GREP -i "data.*\.ppf\|diff.*\.ppf" | $WC -l`
+    onDirExist=`ils ${j} | $GREP -i "On" | $WC -l`
+    if [ ${onDirExist} != 0 ]; then
+	listeCyclesOn=( `ils ${j}/On | $GREP -i "datacycle" | $AWK '($1=="C-"){print $2}' | $XARGS -i basename {} | $SORT -k1.11n` )
+	IFS='
+  '
+	listeCyclesOn=( $( $PRINTF "%s\n" "${listeCyclesOn[@]}" | $AWK 'x[$0]++ == 0' ) )
+	IFS=$DefaultIFS
+	
+	if [ ${#listeCyclesOn[*]} != 0 ]; then    
+           for c in ${listeCyclesOn[@]}
+	   do
+#nb: $c has the format of datacycle<number>
+	     nFiles=`ils ${j}/On/${c} | $GREP -i "medfiltmtx" | $WC -l`
+	     if [ ${nFiles} != 0 ]; then
+		 $ECHO "${sourceDate}/On/${c}: ${nFiles} spectra (${onOnOk} ana)"
+	     else
+		 $ECHO "${sourceDate}/On/${c}: ON-OFF failed"
+	     fi
+#end of loop on cycles 
+	   done
+	else
+	    $ECHO "${sourceDate} : No ON-OFF done for On Diectory"
+	fi
+#end of On exist
+    else
+	$ECHO "${sourceDate} : No On Diectory"
+    fi
+#end of loop on dates
+  done 
+#end of loop on sources
+done
Index: /BAORadio/AmasNancay/v5/submit2bqs-anacalibmaker.sh
===================================================================
--- /BAORadio/AmasNancay/v5/submit2bqs-anacalibmaker.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/submit2bqs-anacalibmaker.sh	(revision 596)
@@ -0,0 +1,45 @@
+#!/bin/sh -xv
+
+scriptName="`basename $0`"
+echo "Processing script ${scriptName} at `date`"
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+dateSelected=
+freqBAOCalib=
+bwBAOCalib=
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=""
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -src)  sourceRadio="$2"; shift;;
+      -date) dateSelected="-date $2"; dateJob="$2";     shift;;
+      -freq) freqBAOCalib="-freq $2"; shift;;
+      -bwd)  bwBAOCalib="-bwd $2"; shift;;
+      -sim) 
+      simulationMode="-sim On"
+      $ECHO "INFO ${scriptName} running in SIMUL mode";;
+	-h)
+	echo >&2 \
+	    "usage: $0 -src souce -date YYYYMMDD [-freq freq in MHz (default ${freqBAOCalib})] [-bwd bandwidth in MHz (default ${bwBAOCalib})]"
+	exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+
+jobBatchName="anacalibs-${sourceRadio}${dateJob}"
+
+jobLogName="${jobBatchName}.log.$$"
+
+qsub -l u_sps_baoradio,u_irods,u_irods_baoradio,T=120000,M=1000MB,scratch=1000MB,platform=LINUX -eo -o $jobLogName -N $jobBatchName -mb -me -mu ${LOGNAME}@lal.in2p3.fr <<EOF
+/afs/in2p3.fr/home/c/campagne/private/work/AmasNancay/anacalibmaker.sh  -src ${sourceRadio} ${dateSelected} ${freqBAOCalib} ${bwBAOCalib} ${simulationMode}
+EOF
Index: /BAORadio/AmasNancay/v5/submit2bqs-anagainmaker.sh
===================================================================
--- /BAORadio/AmasNancay/v5/submit2bqs-anagainmaker.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/submit2bqs-anagainmaker.sh	(revision 596)
@@ -0,0 +1,26 @@
+#!/bin/sh -xv
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=""
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -src)  sourceRadio=$2; shift;;
+      -sim) simulationMode="-sim";;
+	-h)
+	    echo >&2 \
+	    "usage: $0 -src souce [-sim]"
+	    exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+jobBatchName="gains-$sourceRadio"
+jobLogName="${jobBatchName}.log.$$"
+
+qsub -l u_sps_baoradio,u_irods,u_irods_baoradio,T=120000,M=1000MB,scratch=500MB,platform=LINUX -eo -o $jobLogName -N $jobBatchName -mb -me -mu ${LOGNAME}@lal.in2p3.fr <<EOF
+/afs/in2p3.fr/home/c/campagne/private/work/AmasNancay/gainmaker.sh  -src ${sourceRadio} ${simulationMode}
+EOF
Index: /BAORadio/AmasNancay/v5/submit2bqs-anarawonoffmaker.sh
===================================================================
--- /BAORadio/AmasNancay/v5/submit2bqs-anarawonoffmaker.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/submit2bqs-anarawonoffmaker.sh	(revision 596)
@@ -0,0 +1,42 @@
+#!/bin/sh -xv
+
+scriptName="`basename $0`"
+echo "Processing script ${scriptName} at `date`"
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+dateSelected=
+dateJob=
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=""
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -src)  sourceRadio="$2"; shift;;
+      -date) dateSelected="-date $2"; dateJob="$2";     shift;;
+      -sim) 
+      simulationMode="-sim On"
+      $ECHO "INFO ${scriptName} running in SIMUL mode";;
+      -h)
+	echo >&2 \
+	    "usage: $0 -src souce -date YYYYMMDD [-freq freq in MHz (default ${freqBAOCalib})] [-sim to trig simulation mode]"
+	exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+
+jobBatchName="anarawonoff-${sourceRadio}${dateJob}"
+
+jobLogName="${jobBatchName}.log.$$"
+
+qsub -l u_sps_baoradio,u_irods,u_irods_baoradio,T=120000,M=1000MB,scratch=1000MB,platform=LINUX -eo -o $jobLogName -N $jobBatchName -mb -me -mu ${LOGNAME}@lal.in2p3.fr <<EOF
+/afs/in2p3.fr/home/c/campagne/private/work/AmasNancay/anarawonoffmaker.sh  -src ${sourceRadio} ${dateSelected} ${simulationMode}
+EOF
Index: /BAORadio/AmasNancay/v5/submit2bqs-calibmaker.sh
===================================================================
--- /BAORadio/AmasNancay/v5/submit2bqs-calibmaker.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/submit2bqs-calibmaker.sh	(revision 596)
@@ -0,0 +1,43 @@
+#!/bin/sh -xv
+
+scriptName="`basename $0`"
+echo "Processing script ${scriptName} at `date`"
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio
+freqBAOCalib=
+bwBAOCalib=
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=""
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -src)  sourceRadio="$2"; shift;;
+      -freq) freqBAOCalib="-freq $2"; shift;;
+      -bwd)  bwBAOCalib="-bwd $2"; shift;;
+      -sim) 
+      simulationMode="-sim On"
+      $ECHO "INFO ${scriptName} running in SIMUL mode";;
+	-h)
+	echo >&2 \
+	    "usage: $0 -src souce [-freq freq in MHz (default ${freqBAOCalib})] [-bwd bandwidth in MHz (default ${bwBAOCalib})]"
+	exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+
+jobBatchName="calibs-${sourceRadio}"
+
+jobLogName="${jobBatchName}.log.$$"
+
+qsub -l u_sps_baoradio,u_irods,u_irods_baoradio,T=120000,M=1000MB,scratch=1000MB,platform=LINUX -eo -o $jobLogName -N $jobBatchName -mb -me -mu ${LOGNAME}@lal.in2p3.fr <<EOF
+/afs/in2p3.fr/home/c/campagne/private/work/AmasNancay/calibmaker.sh  -src ${sourceRadio} ${freqBAOCalib} ${bwBAOCalib} ${simulationMode}
+EOF
Index: /BAORadio/AmasNancay/v5/submit2bqs-gainmaker.sh
===================================================================
--- /BAORadio/AmasNancay/v5/submit2bqs-gainmaker.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/submit2bqs-gainmaker.sh	(revision 596)
@@ -0,0 +1,33 @@
+#!/bin/sh -xv
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+dateSelected=
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=""
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -src)  sourceRadio=$2; shift;;
+      -date) dateSelected="-date $2"; dateJob="$2";     shift;;
+      -sim) simulationMode="-sim";;
+	-h)
+	    echo >&2 \
+	    "usage: $0 -src souce -date YYYYMMDD [-sim]"
+	    exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+jobBatchName="anagains-${sourceRadio}${dateJob}"
+jobLogName="${jobBatchName}.log.$$"
+
+qsub -l u_sps_baoradio,u_irods,u_irods_baoradio,T=120000,M=1000MB,scratch=500MB,platform=LINUX -eo -o $jobLogName -N $jobBatchName -mb -me -mu ${LOGNAME}@lal.in2p3.fr <<EOF
+/afs/in2p3.fr/home/c/campagne/private/work/AmasNancay/anagainmaker.sh  -src ${sourceRadio} ${dateSelected} ${simulationMode}
+EOF
Index: /BAORadio/AmasNancay/v5/submit2bqs-hdrfitsextractor.sh
===================================================================
--- /BAORadio/AmasNancay/v5/submit2bqs-hdrfitsextractor.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/submit2bqs-hdrfitsextractor.sh	(revision 596)
@@ -0,0 +1,23 @@
+#!/bin/sh
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -src)  sourceRadio=$2; shift;;
+	-h)
+	    echo >&2 \
+	    "usage: $0 -src souce"
+	    exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+jobBatchName="headerMaker-$sourceRadio"
+jobLogName="${jobBatchName}.log.$$"
+
+qsub -l u_sps_baoradio,u_irods,u_irods_baoradio,T=100000,M=256MB,scratch=700MB,platform=LINUX -eo -o $jobLogName -N $jobBatchName -mb -me -mu ${LOGNAME}@lal.in2p3.fr <<EOF
+/afs/in2p3.fr/home/c/campagne/private/work/AmasNancay/hdrfitsextractor.sh  $sourceRadio
+EOF
Index: /BAORadio/AmasNancay/v5/submit2bqs-onoffmaker.sh
===================================================================
--- /BAORadio/AmasNancay/v5/submit2bqs-onoffmaker.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/submit2bqs-onoffmaker.sh	(revision 596)
@@ -0,0 +1,44 @@
+#!/bin/sh -xv
+
+scriptName="`basename $0`"
+echo "Processing script ${scriptName} at `date`"
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+dateSelected=
+dateJob=
+freqBAOCalib=
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=""
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -src)  sourceRadio="$2"; shift;;
+      -date) dateSelected="-date $2"; dateJob="$2";     shift;;
+      -freq) freqBAOCalib="-freq $2"; shift;;
+      -sim) 
+      simulationMode="-sim On"
+      $ECHO "INFO ${scriptName} running in SIMUL mode";;
+	-h)
+	echo >&2 \
+	    "usage: $0 -src souce -date YYYYMMDD [-freq freq in MHz (default ${freqBAOCalib})] [-sim to trig simulation mode]"
+	exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+
+jobBatchName="onoff-${sourceRadio}${dateJob}"
+
+jobLogName="${jobBatchName}.log.$$"
+
+qsub -l u_sps_baoradio,u_irods,u_irods_baoradio,T=120000,M=1000MB,scratch=1000MB,platform=LINUX -eo -o $jobLogName -N $jobBatchName -mb -me -mu ${LOGNAME}@lal.in2p3.fr <<EOF
+/afs/in2p3.fr/home/c/campagne/private/work/AmasNancay/onoffmaker.sh  -src ${sourceRadio} ${dateSelected} ${freqBAOCalib} ${simulationMode}
+EOF
Index: /BAORadio/AmasNancay/v5/submit2bqs-procspecmfib.sh
===================================================================
--- /BAORadio/AmasNancay/v5/submit2bqs-procspecmfib.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/submit2bqs-procspecmfib.sh	(revision 596)
@@ -0,0 +1,126 @@
+#!/bin/sh -xv
+AWK=/bin/awk
+SED=/bin/sed
+GREP=/bin/grep
+WC=/usr/bin/wc
+RM=/bin/rm
+CAT=/bin/cat
+TOUCH=/bin/touch
+DATE=/bin/date
+ECHO=/bin/echo
+LS=/bin/ls
+MKDIR=/bin/mkdir
+TR=/usr/bin/tr
+FIND=/usr/bin/find
+PRINTF=/usr/bin/printf
+XARGS=/usr/bin/xargs
+SORT=/bin/sort
+QSUB=qsub
+
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+
+scriptName="`basename $0`"
+echo "Processing script ${scriptName} at `date`"
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+#action: gain|mspec (gain: gain-like doucble median filtering
+#                   mspec: mean+sigma wo filetring)
+action="-act gain"
+sourceRadio=
+dateSelected=
+typeofproc=
+#first and last cycle to process
+#
+firstCycle=
+lastCycle=
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=""
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -act)  action="-act $2"; act=$2; shift;;
+      -src)  sourceRadio="$2"; shift;;
+      -date) dateSelected="-date $2"; dateJob="$2";     shift;;
+      -type) typeofproc="-type $2"; type=$2; shift;;
+      -fcycle) firstCycle="-fcycle $2"; fcycle="$2"; shift;;
+      -lcycle) lastCycle="-lcycle $2"; lcycle="$2"; shift;;
+       -sim) 
+      simulationMode="-sim On"
+      $ECHO "INFO ${scriptName} running in SIMUL mode";;
+	-h)
+	echo >&2 \
+	    "usage: $0 -src souce -date YYYYMMDD -type type [-fcycle firstCycle] [-lcycle lastCycle] [-sim to trig simulation mode]"
+	exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+if [ "<${dateSelected}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the date option (-date)"
+    exit 1
+fi
+
+if [ "<${typeofproc}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the type option (-type)"
+    exit 1
+fi
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+#Path of the utility scripts
+scriptpath=${SCRIPTPATH}
+#get the daq current irod status
+#JEC 1/10/11 Use generic baodaqstatus name 
+#### tag=`${DATE} +%F`
+OUT1=${publicpath}/baodaqstatus-current.txt
+
+if [ ! -e ${OUT1}  -o ! -r ${OUT1} ]; then
+    $ECHO "FATAL (${scriptName}): ${OUT1} has a problem"
+    exit 1
+#JEC 29/9/11 avoid finished stuff
+#    $RM -f ${tmppublicpath}/statusdaq.finished
+#    ${scriptpath}/statusdaq.sh > ${OUT1}
+#    while [ ! -f "${tmppublicpath}/statusdaq.finished" ]; do
+#	sleep 30
+#    done
+#    $RM ${tmppublicpath}/statusdaq.finished
+#protect against remove/rewriting    
+#    $CHMOD -v 444 ${OUT1} 
+fi
+
+#assume 20 files/cycles cf. 30sec/cycle et 3sec par signal et fact 2 margin 
+if [ "<${firstCycle}>" != "<>" -a "<${lastCycle}>" != "<>" ]; then
+    jobBatchName="procspecmfib-${sourceRadio}${dateJob}${type}-${fcycle}-${lcycle}"
+    nFiles=`expr ${lcycle} - ${fcycle} + 1`
+    nFiles=`expr ${nFiles} \* 20`
+else
+    jobBatchName="procspecmfib-${sourceRadio}${dateJob}${type}-All"
+    #assume 30 cycles maxi!
+    nFiles=`expr 20 \* 30`
+
+fi
+
+jobLogName="${jobBatchName}.log.$$"
+
+#Nbre de paquets utilises pour 1 spectre
+tspwin="5120"
+#calcul du scratch sachant que l'on nettoie apres chaque cycle
+nSpectra=`expr 20 \* 25600 /  ${tspwin}`
+scratchSize=`expr  20 \* 500 + ${nSpectra} \* 200 / 1000 + 5`
+
+#le cpu total tient compte de l'emsemble des ficheirs a taiter
+cpu=`expr ${nFiles} \* 60 \* 50`
+
+qsub -l u_sps_baoradio,u_irods,u_irods_baoradio,T=${cpu},M=1000MB,scratch=${scratchSize}MB,platform=LINUX -eo -o $jobLogName -N $jobBatchName -mb -me -mu ${LOGNAME}@lal.in2p3.fr <<EOF
+/afs/in2p3.fr/home/c/campagne/private/work/AmasNancay/proc_specmfib.sh ${action} -src ${sourceRadio} ${dateSelected} ${typeofproc} ${firstCycle} ${lastCycle} ${simulationMode}
+EOF
Index: /BAORadio/AmasNancay/v5/submit2bqs-scaextractor.sh
===================================================================
--- /BAORadio/AmasNancay/v5/submit2bqs-scaextractor.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/submit2bqs-scaextractor.sh	(revision 596)
@@ -0,0 +1,63 @@
+#!/bin/sh -xvf
+DATE=/bin/date
+GREP=/bin/grep
+AWK=/bin/awk
+ECHO=/bin/echo
+WC=/usr/bin/wc
+CAT=/bin/cat
+PRINTF=/usr/bin/printf
+FIND=/usr/bin/find
+MKDIR=/bin/mkdir
+XARGS=/usr/bin/xargs
+SORT=/bin/sort
+RM=/bin/rm
+TR=/usr/bin/tr
+CP=/bin/cp
+LS=/bin/ls
+CHMOD=/bin/chmod
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+force=
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -src)  sourceRadio=$2; shift;;
+      -force) force="Yes";;
+	-h)
+	    echo >&2 \
+	    "usage: $0 -src souce"
+	    exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+$LS -l ${tmppublicpath} > /dev/null
+
+#Path of the utility scripts
+scriptpath=${SCRIPTPATH}
+
+#JEC 1/10/11 Use generic baodaqstatus name 
+#the daq current irod status
+#tag=`${DATE} +%F`
+#OUT1=${publicpath}/baodaqstatus-${tag}.txt
+OUT1=${publicpath}/baodaqstatus-current.txt
+
+if [ ! -e ${OUT1}  -o ! -r ${OUT1} ]; then
+    $ECHO "FATAL (${scriptName}): ${OUT1} has a problem"
+    exit 1
+fi
+
+jobBatchName="scaMaker-$sourceRadio"
+jobLogName="${jobBatchName}.log.$$"
+
+qsub -l u_sps_baoradio,u_irods,u_irods_baoradio,T=100000,M=256MB,scratch=700MB,platform=LINUX -eo -o $jobLogName -N $jobBatchName -mb -me -mu ${LOGNAME}@lal.in2p3.fr <<EOF
+/afs/in2p3.fr/home/c/campagne/private/work/AmasNancay/scaextractor.sh  ${sourceRadio} ${force}
+EOF
Index: /BAORadio/AmasNancay/v5/submit2ge-anacalibmaker.sh
===================================================================
--- /BAORadio/AmasNancay/v5/submit2ge-anacalibmaker.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/submit2ge-anacalibmaker.sh	(revision 596)
@@ -0,0 +1,46 @@
+#!/bin/sh -xv
+
+scriptName="`basename $0`"
+echo "Processing script ${scriptName} at `date`"
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+dateSelected=
+freqBAOCalib=
+bwBAOCalib=
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=""
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -src)  sourceRadio="$2"; shift;;
+      -date) dateSelected="-date $2"; dateJob="$2";     shift;;
+      -freq) freqBAOCalib="-freq $2"; shift;;
+      -bwd)  bwBAOCalib="-bwd $2"; shift;;
+      -sim) 
+      simulationMode="-sim On"
+      $ECHO "INFO ${scriptName} running in SIMUL mode";;
+	-h)
+	echo >&2 \
+	    "usage: $0 -src source -date YYYYMMDD [-freq freq in MHz (default ${freqBAOCalib})] [-bwd bandwidth in MHz (default ${bwBAOCalib})]"
+	exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+
+jobBatchName="anacalibs-${sourceRadio}${dateJob}"
+
+jobLogName="${jobBatchName}.log.$$"
+
+qsub -P P_baoradio -l sps=1,irods=1,ct=1200,vmem=1000M,fsize=1000M -o $jobLogName -j yes -N $jobBatchName -m be -M ${LOGNAME}@lal.in2p3.fr -V <<EOF
+
+${SCRIPTPATH}/anacalibmaker.sh  -src ${sourceRadio} ${dateSelected} ${freqBAOCalib} ${bwBAOCalib} ${simulationMode}
+EOF
Index: /BAORadio/AmasNancay/v5/submit2ge-anagainmaker.sh
===================================================================
--- /BAORadio/AmasNancay/v5/submit2ge-anagainmaker.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/submit2ge-anagainmaker.sh	(revision 596)
@@ -0,0 +1,35 @@
+#!/bin/sh -xv
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+dateSelected=
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=""
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -src)  sourceRadio=$2; shift;;
+      -date) dateSelected="-date $2"; dateJob="$2"; shift;;
+      -sim)  simulationMode="-sim";;
+	-h)
+	    echo >&2 \
+	    "usage: $0 -src source -date YYYYMMDD [-sim]"
+	    exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+jobBatchName="gains-${sourceRadio}${dateJob}"
+jobLogName="${jobBatchName}.log.$$"
+
+qsub -P P_baoradio -l sps=1,irods=1,ct=2400,vmem=1000M,fsize=500M -o $jobLogName -j yes -N $jobBatchName -m be -M ${LOGNAME}@lal.in2p3.fr -V <<EOF
+
+${SCRIPTPATH}/anagainmaker.sh -src ${sourceRadio} ${dateSelected} ${simulationMode}
+EOF
Index: /BAORadio/AmasNancay/v5/submit2ge-anarawonoffmaker.sh
===================================================================
--- /BAORadio/AmasNancay/v5/submit2ge-anarawonoffmaker.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/submit2ge-anarawonoffmaker.sh	(revision 596)
@@ -0,0 +1,43 @@
+#!/bin/sh -xv
+
+scriptName="`basename $0`"
+echo "Processing script ${scriptName} at `date`"
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+dateSelected=
+dateJob=
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=""
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -src)  sourceRadio="$2"; shift;;
+      -date) dateSelected="-date $2"; dateJob="$2";     shift;;
+      -sim) 
+      simulationMode="-sim On"
+      $ECHO "INFO ${scriptName} running in SIMUL mode";;
+      -h)
+	echo >&2 \
+	    "usage: $0 -src source -date YYYYMMDD [-freq freq in MHz (default ${freqBAOCalib})] [-sim to trig simulation mode]"
+	exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+
+jobBatchName="anarawonoff-${sourceRadio}${dateJob}"
+
+jobLogName="${jobBatchName}.log.$$"
+
+qsub -P P_baoradio -l sps=1,irods=1,ct=2400,vmem=1000M,fsize=1000M -o $jobLogName -j yes -N $jobBatchName -m be -M ${LOGNAME}@lal.in2p3.fr -V <<EOF
+
+${SCRIPTPATH}/anarawonoffmaker.sh  -src ${sourceRadio} ${dateSelected} ${simulationMode}
+EOF
Index: /BAORadio/AmasNancay/v5/submit2ge-calibmaker.sh
===================================================================
--- /BAORadio/AmasNancay/v5/submit2ge-calibmaker.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/submit2ge-calibmaker.sh	(revision 596)
@@ -0,0 +1,44 @@
+#!/bin/sh -xv
+
+scriptName="`basename $0`"
+echo "Processing script ${scriptName} at `date`"
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio
+freqBAOCalib=
+bwBAOCalib=
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=""
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -src)  sourceRadio="$2"; shift;;
+      -freq) freqBAOCalib="-freq $2"; shift;;
+      -bwd)  bwBAOCalib="-bwd $2"; shift;;
+      -sim) 
+      simulationMode="-sim On"
+      $ECHO "INFO ${scriptName} running in SIMUL mode";;
+	-h)
+	echo >&2 \
+	    "usage: $0 -src souce [-freq freq in MHz (default ${freqBAOCalib})] [-bwd bandwidth in MHz (default ${bwBAOCalib})]"
+	exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+
+jobBatchName="calibs-${sourceRadio}"
+
+jobLogName="${jobBatchName}.log.$$"
+
+qsub -P P_baoradio -l sps=1,irods=1,ct=2400,vmem=1000M,fsize=1000M -o $jobLogName -j yes -N $jobBatchName -m be -M ${LOGNAME}@lal.in2p3.fr -V <<EOF
+
+${SCRIPTPATH}/calibmaker.sh  -src ${sourceRadio} ${freqBAOCalib} ${bwBAOCalib} ${simulationMode}
+EOF
Index: /BAORadio/AmasNancay/v5/submit2ge-gainmaker.sh
===================================================================
--- /BAORadio/AmasNancay/v5/submit2ge-gainmaker.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/submit2ge-gainmaker.sh	(revision 596)
@@ -0,0 +1,34 @@
+#!/bin/sh -xv
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+dateSelected=
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=""
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -src)  sourceRadio=$2; shift;;
+      -date) dateSelected="-date $2"; dateJob="$2";     shift;;
+      -sim) simulationMode="-sim";;
+	-h)
+	    echo >&2 \
+	    "usage: $0 -src souce -date YYYYMMDD [-sim]"
+	    exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+jobBatchName="anagains-${sourceRadio}${dateJob}"
+jobLogName="${jobBatchName}.log.$$"
+
+qsub -P P_baoradio -l sps=1,irods=1,ct=2400,vmem=1000M,fsize=500M -o $jobLogName -j yes -N $jobBatchName -m be -M ${LOGNAME}@lal.in2p3.fr -V <<EOF
+
+${SCRIPTPATH}/anagainmaker.sh  -src ${sourceRadio} ${dateSelected} ${simulationMode}
+EOF
Index: /BAORadio/AmasNancay/v5/submit2ge-hdrfitsextractor.sh
===================================================================
--- /BAORadio/AmasNancay/v5/submit2ge-hdrfitsextractor.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/submit2ge-hdrfitsextractor.sh	(revision 596)
@@ -0,0 +1,24 @@
+#!/bin/sh
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -src)  sourceRadio=$2; shift;;
+	-h)
+	    echo >&2 \
+	    "usage: $0 -src souce"
+	    exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+jobBatchName="headerMaker-$sourceRadio"
+jobLogName="${jobBatchName}.log.$$"
+
+qsub -P P_baoradio -l sps=1,irods=1,ct=2000,vmem=256M,fsize=700M -o $jobLogName -j yes -N $jobBatchName -m be -M ${LOGNAME}@lal.in2p3.fr -V <<EOF
+
+${SCRIPTPATH}/hdrfitsextractor.sh  $sourceRadio
+EOF
Index: /BAORadio/AmasNancay/v5/submit2ge-onoffmaker.sh
===================================================================
--- /BAORadio/AmasNancay/v5/submit2ge-onoffmaker.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/submit2ge-onoffmaker.sh	(revision 596)
@@ -0,0 +1,45 @@
+#!/bin/sh -xv
+
+scriptName="`basename $0`"
+echo "Processing script ${scriptName} at `date`"
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+dateSelected=
+dateJob=
+freqBAOCalib=
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=""
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -src)  sourceRadio="$2"; shift;;
+      -date) dateSelected="-date $2"; dateJob="$2";     shift;;
+      -freq) freqBAOCalib="-freq $2"; shift;;
+      -sim) 
+      simulationMode="-sim On"
+      $ECHO "INFO ${scriptName} running in SIMUL mode";;
+	-h)
+	echo >&2 \
+	    "usage: $0 -src souce -date YYYYMMDD [-freq freq in MHz (default ${freqBAOCalib})] [-sim to trig simulation mode]"
+	exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+
+jobBatchName="onoff-${sourceRadio}${dateJob}"
+
+jobLogName="${jobBatchName}.log.$$"
+
+qsub -P P_baoradio -l sps=1,irods=1,ct=2400,vmem=1000M,fsize=1000M -o $jobLogName -j yes -N $jobBatchName -m be -M ${LOGNAME}@lal.in2p3.fr -V <<EOF
+
+${SCRIPTPATH}/onoffmaker.sh  -src ${sourceRadio} ${dateSelected} ${freqBAOCalib} ${simulationMode}
+EOF
Index: /BAORadio/AmasNancay/v5/submit2ge-procspecmfib.sh
===================================================================
--- /BAORadio/AmasNancay/v5/submit2ge-procspecmfib.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/submit2ge-procspecmfib.sh	(revision 596)
@@ -0,0 +1,128 @@
+#!/bin/sh -xv
+AWK=/bin/awk
+SED=/bin/sed
+GREP=/bin/grep
+WC=/usr/bin/wc
+RM=/bin/rm
+CAT=/bin/cat
+TOUCH=/bin/touch
+DATE=/bin/date
+ECHO=/bin/echo
+LS=/bin/ls
+MKDIR=/bin/mkdir
+TR=/usr/bin/tr
+FIND=/usr/bin/find
+PRINTF=/usr/bin/printf
+XARGS=/usr/bin/xargs
+SORT=/bin/sort
+QSUB=qsub
+
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+
+scriptName="`basename $0`"
+echo "Processing script ${scriptName} at `date`"
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+#action: gain|mspec (gain: gain-like doucble median filtering
+#                   mspec: mean+sigma wo filetring)
+action="-act gain"
+sourceRadio=
+dateSelected=
+typeofproc=
+#first and last cycle to process
+#
+firstCycle=
+lastCycle=
+#use -sim option to simulate processing (debug the script as if...)
+simulationMode=""
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -act)  action="-act $2"; act=$2; shift;;
+      -src)  sourceRadio="$2"; shift;;
+      -date) dateSelected="-date $2"; dateJob="$2";     shift;;
+      -type) typeofproc="-type $2"; type=$2; shift;;
+      -fcycle) firstCycle="-fcycle $2"; fcycle="$2"; shift;;
+      -lcycle) lastCycle="-lcycle $2"; lcycle="$2"; shift;;
+       -sim) 
+      simulationMode="-sim On"
+      $ECHO "INFO ${scriptName} running in SIMUL mode";;
+	-h)
+	echo >&2 \
+	    "usage: $0 -src source -date YYYYMMDD -type type [-fcycle firstCycle] [-lcycle lastCycle] [-sim to trig simulation mode]"
+	exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+if [ "<${sourceRadio}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the source option (-src)"
+    exit 1
+fi
+
+if [ "<${dateSelected}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the date option (-date)"
+    exit 1
+fi
+
+if [ "<${typeofproc}>" = "<>" ]; then
+    $ECHO "FATAL: You have forgotten to select the type option (-type)"
+    exit 1
+fi
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+#Path of the utility scripts
+scriptpath=${SCRIPTPATH}
+#get the daq current irod status
+#JEC 1/10/11 Use generic baodaqstatus name 
+#### tag=`${DATE} +%F`
+OUT1=${publicpath}/baodaqstatus-current.txt
+
+if [ ! -e ${OUT1}  -o ! -r ${OUT1} ]; then
+    $ECHO "FATAL (${scriptName}): ${OUT1} has a problem"
+    exit 1
+#JEC 29/9/11 avoid finished stuff
+#    $RM -f ${tmppublicpath}/statusdaq.finished
+#    ${scriptpath}/statusdaq.sh > ${OUT1}
+#    while [ ! -f "${tmppublicpath}/statusdaq.finished" ]; do
+#	sleep 30
+#    done
+#    $RM ${tmppublicpath}/statusdaq.finished
+#protect against remove/rewriting    
+#    $CHMOD -v 444 ${OUT1} 
+fi
+
+#assume 20 files/cycles cf. 30sec/cycle et 3sec par signal et fact 2 margin 
+if [ "<${firstCycle}>" != "<>" -a "<${lastCycle}>" != "<>" ]; then
+    jobBatchName="procspecmfib-${sourceRadio}${dateJob}${type}-${fcycle}-${lcycle}"
+    nFiles=`expr ${lcycle} - ${fcycle} + 1`
+    nFiles=`expr ${nFiles} \* 20`
+else
+    jobBatchName="procspecmfib-${sourceRadio}${dateJob}${type}-All"
+    #assume 30 cycles maxi!
+    nFiles=`expr 20 \* 30`
+
+fi
+
+jobLogName="${jobBatchName}.log.$$"
+
+#Nbre de paquets utilises pour 1 spectre
+tspwin="5120"
+#calcul du scratch sachant que l'on nettoie apres chaque cycle
+nSpectra=`expr 20 \* 25600 /  ${tspwin}`
+scratchSize=`expr  20 \* 500 + ${nSpectra} \* 200 / 1000 + 5`
+
+#le cpu total tient compte de l'emsemble des ficheirs a traiter
+#cpu=`expr ${nFiles} \* 60 \* 50`  # BQS estimation
+cpu=`expr ${nFiles} \* 60`
+
+qsub -P P_baoradio -l sps=1,irods=1,ct=${cpu},vmem=1000M,fsize=${scratchSize}M -o $jobLogName -j yes -N $jobBatchName -m be -M ${LOGNAME}@lal.in2p3.fr -V <<EOF
+
+${SCRIPTPATH}/proc_specmfib.sh ${action} -src ${sourceRadio} ${dateSelected} ${typeofproc} ${firstCycle} ${lastCycle} ${simulationMode}
+EOF
Index: /BAORadio/AmasNancay/v5/submit2ge-scaextractor.sh
===================================================================
--- /BAORadio/AmasNancay/v5/submit2ge-scaextractor.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/submit2ge-scaextractor.sh	(revision 596)
@@ -0,0 +1,64 @@
+#!/bin/sh -xvf
+DATE=/bin/date
+GREP=/bin/grep
+AWK=/bin/awk
+ECHO=/bin/echo
+WC=/usr/bin/wc
+CAT=/bin/cat
+PRINTF=/usr/bin/printf
+FIND=/usr/bin/find
+MKDIR=/bin/mkdir
+XARGS=/usr/bin/xargs
+SORT=/bin/sort
+RM=/bin/rm
+TR=/usr/bin/tr
+CP=/bin/cp
+LS=/bin/ls
+CHMOD=/bin/chmod
+
+#Process cmd line args: the -src option is mandatory (source name as Abell85)
+sourceRadio=
+force=
+while [ $# -gt 0 ]
+do
+  case "$1" in
+      -src)  sourceRadio=$2; shift;;
+      -force) force="Yes";;
+	-h)
+	    echo >&2 \
+	    "usage: $0 -src souce"
+	    exit 1;;
+	*)  break;;	# terminate while loop
+    esac
+    shift
+done
+
+#Path to public backupable path
+publicpath="/afs/in2p3.fr/home/c/campagne/public"
+
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+$LS -l ${tmppublicpath} > /dev/null
+
+#Path of the utility scripts
+scriptpath=${SCRIPTPATH}
+
+#JEC 1/10/11 Use generic baodaqstatus name 
+#the daq current irod status
+#tag=`${DATE} +%F`
+#OUT1=${publicpath}/baodaqstatus-${tag}.txt
+OUT1=${publicpath}/baodaqstatus-current.txt
+
+if [ ! -e ${OUT1}  -o ! -r ${OUT1} ]; then
+    $ECHO "FATAL (${scriptName}): ${OUT1} has a problem"
+    exit 1
+fi
+
+jobBatchName="scaMaker-$sourceRadio"
+jobLogName="${jobBatchName}.log.$$"
+
+qsub -P P_baoradio -l sps=1,irods=1,ct=2000,vmem=256M,fsize=700M -o $jobLogName -j yes -N $jobBatchName -m be -M ${LOGNAME}@lal.in2p3.fr -V <<EOF
+
+${SCRIPTPATH}/scaextractor.sh  ${sourceRadio} ${force}
+EOF
Index: /BAORadio/AmasNancay/v5/transdate.sh
===================================================================
--- /BAORadio/AmasNancay/v5/transdate.sh	(revision 596)
+++ /BAORadio/AmasNancay/v5/transdate.sh	(revision 596)
@@ -0,0 +1,68 @@
+#!/bin/sh
+# transforme les dates en nombre de seconde depuis minuit
+# pour reecrire les start/stop des differentes phases du fichier sca
+
+AWK=/bin/awk
+SED=/bin/sed
+GREP=/bin/grep
+WC=/usr/bin/wc
+RM=/bin/rm
+CAT=/bin/cat
+TOUCH=/bin/touch
+DATE=/bin/date
+ECHO=/bin/echo
+LS=/bin/ls
+MKDIR=/bin/mkdir
+DefaultIFS=$' \t\n'
+IFS=$DefaultIFS
+
+
+scriptName="`basename $0`"
+$ECHO "Processing script ${scriptName} at `date`"
+
+#temporary files to synchronize scripts
+tmppublicpath=${TMPPUBLICPATH}
+$LS -l ${tmppublicpath} > /dev/null
+
+#Path where the job will do temporary IO
+. ${SCRIPTPATH}/set_iojobpath.sh
+iojobpath=$(set_iojobpath)
+cd ${iojobpath}
+
+if [ ! $# = 1 ]; then
+  $ECHO "FATAL (${scriptName}) usage: ./transdate.sh <scaXYZ.sum>"
+  exit 0
+fi
+
+#inputs x-chexk sca file
+inScaFile=$1
+if [ ! -e $inScaFile ]; then
+  $ECHO "FATAL (${scriptName}): $inScaFile not found"
+  exit 1
+fi
+
+$AWK -v datesys=$DATE '
+BEGIN {
+  FS=",";
+}
+
+{
+  cycle=$1;
+  for (i=2; i<=NF; i++) {
+    cmd=sprintf("%s +%%F -d \"%s\" ",datesys,$i);
+    (cmd | getline day);
+    close(cmd);
+    cmd=sprintf("%s +%%s -d \"%s\" ",datesys,day);
+    (cmd | getline s0);
+    close(cmd);
+    cmd=sprintf("%s +%%s -d \"%s\" ",datesys,$i);
+    (cmd | getline s1);
+    close(cmd);
+    $i = s1 - s0;    
+  }
+  print $0;
+}
+
+' $inScaFile >> $inScaFile.trans
+
+exit 0
