#!/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
TMP="/tmp"

OUT1=${TMP}/selectFits.$$

if [ ! $# = 3 ]; then
  $ECHO "usage: ./select.sh <scaXYZ.sum> <signalXYZDirectory> <type of phase:ON|OFF|CALIBON|CALIBOFF>"
   exit 0
fi

#inputs x-chexk sca file
inScaFile=$1
if [ ! -e $inScaFile ]; then
  $ECHO "$inScaFile not found: FATAL"
  exit 1
fi

#scan the Fiber1 directory only
inFiberDir=$2/Fiber1

inTypeOfPhase=$3
case "$inTypeOfPhase" in
    ON) 
    $ECHO "filter signal files for ON phases";;
    OFF) 
    $ECHO "filter signal files for OFF phases";;
    CALIBON) 
    $ECHO "filter signal files for CALIBRATION ON phases";;
    CALIBOFF) 
    $ECHO "filter signal files for CALIBRATION OFF phases";;
    *) 
    $ECHO "use ON|OFF|CALIBON|CALIBOFF phase tags."
    exit 1
    ;;
esac


#################
#fill the arrays association signal file with start/end date&time 
# arrays
declare -a sigStart
declare -a sigEnd
declare -a sigFile

for fullfile in $(find $inFiberDir -name "signal*" | 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 "$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=${TMP}/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" ) {
    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" ) {
    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" ) {
    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 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=${TMP}/tmpselect2.$$
$AWK '
BEGIN { max=0 }; 

($1=="cycle") { table[$2] = table[$2]","$4; if($2>max){max=$2} }; 

END { for (j=1;j<=max;j++) {print j,table[j];} }
' ${OUT1} >> ${OUT2}

$AWK '
BEGIN { FS=","}
{
 print "#"$1,$2","$NF",1";
}
' ${OUT2}





#for elem in ${!sigStart[*]} ; do
#        echo "index <${elem}>: file "${sigFile[${elem}]}" : start <"${sigStart[${elem}]}"> end <"${sigEnd[${elem}]}">" ;
#done


