#! /bin/bash
# Last edited on 2021-09-02 08:32:19 by stolfi

# Filter all runs with filter "B" (rejects below 1-2 Hz and above 20-30 Hz)

subj="$1"; shift; # Max runs to process per subjcet.
logdate="$1"; shift; # Date and time for log files.

fptag="C"
restep=5
rebase=1

filter=( "G" 0.166667 0.333333  24.0 48.0 )

echo "# running ${0##*/}" 1>&2
echo "# logdate ${logdate}" 1>&2
    
channels=( `cat channel_names.txt | gawk '/^[ ]*[0-9]/{ print $3; }'` )
ne=${#channels[@]}
printf "assuming %d channels in raw files = %s\n" "${ne}" "${channels[*]}" 1>&2

rawdir="raw-runs"
fltdir="flt-runs-${fptag}"
nsedir="nse-runs-${fptag}"

mkdir -p ${fltdir}
mkdir -p ${nsedir}

( cd ~/programs/c/NEUROMAT/nmeeg_filter && make uninstall build install )
( cd ~/programs/c/NEUROMAT/nmeeg_plot_channels && make uninstall build install )
  
# Resampling options:
if [[ ${rebase} != 0 ]]; then resop=("-rebase") ; else resop=( ); fi

function runfilter(){
  fname="$1"; shift;  # Name of extracted run file, sans ".txt", e.g. "s010/r00123".
  noise="$1"; shift;  # 1 to compute noise component, 0 to compute the filtered file

  # set -o xtrace
   
  echo "=== ${fname} ==========================================================" 1>&2
  echo "filtering ${rawdir}/${fname}.txt --> ${fltdir}/${fname}.txt + ${nsedir}/${fname}.txt" 1>&2
  
  fltvmax=180  # Max voltage for filtered plot scaling.
  nsevmax=1010 # Max voltage for noise plot scaling.
  
  # Get names of electrodes to esclude:
  exop=( ` cat ${fltdir}/${fname%%/*}/bad-channels.txt | gawk '/^C/{ printf "-exclude %s\n", $1; }'` )
  echo "fname = ${fname} exop = ${exop[@]}" 1>&2

  if [[ ${noise} -eq 0 ]]; then
    echo "filtering ${rawdir}/${fname}.txt --> ${fltdir}/${fname}.txt" >> ${gfile}
    cat ${rawdir}/${fname}.txt \
      | nmeeg_filter \
          ${exop[@]} \
          -trend 3 0 \
          -filter "${filter[@]}" \
          -invert 0 \
          ${resop[@]} \
          -resample ${restep} \
      > ${fltdir}/${fname}.txt
    plot_run.sh NOSHOW ${fltdir}/${fname} 0 -1 180 500
  else
    echo "separating noise ${rawdir}/${fname}.txt --> ${nsedir}/${fname}.txt" >> ${gfile}
    # Removed noise and trend:
    cat ${rawdir}/${fname}.txt \
      | nmeeg_filter \
          ${exop[@]} \
          -trend 3 1 \
          -filter "${filter[@]}" \
          -invert 1 \
          ${resop[@]} \
      > ${nsedir}/${fname}.txt
    plot_run.sh NOSHOW ${nsedir}/${fname} 0 -1  1010 500
  fi

}

function subjfilter(){
  subj="$1"; shift;  # Subject's ID, e.g. "s010".
  
  echo "" 1>&2
  echo "######################################################################" 1>&2
  echo "processing subject ${subj}" 1>&2

  gfile="${fltdir}/${subj}/filter_runs_${logdate}.log"
  echo "messages will be written to ${gfile}" 1>&2
  echo "" 1>&2

  mkdir -p ${fltdir}/${subj}
  mkdir -p ${nsedir}/${subj}

  # Remove all filtered files since filter parameters may have changed:
  rm -f ${nsedir}/${subj}/r?????.{txt,png,stat}
  rm -f ${fltdir}/${subj}/r?????.{txt,png,stat}
  
  rm -f ${gfile}

  # Compute filtered version of all runs:
  echo "filtering all runs of subject ${subj}" 1>&2
  for fraw in `( cd ${rawdir} && ls ${subj}/r?????.txt )` ; do 
    fname="${fraw%%.txt}"
    runfilter ${fname} 0 >> ${gfile} 2>&1
  done

  notable_runs=( `cat notable_runs.txt | grep -e "${subj}/"` ) 
  
  # Compute the noise component of a random susbet of all runs:
  echo "computing noise component of some runs of subject ${subj}" 1>&2
  maxruns=30
  ( cd ${rawdir} && ls ${subj}/r?????.txt ) \
    | gawk '//{ printf "%+10.7f %s\n", sin(17*FNR+23), $1 }' \
    | sort -k1,1g \
    | cut -d ' ' -f 2 \
    | head -n ${maxruns} \
    | sort \
    > .tmp-runs
  cat .tmp-runs notable_runs.txt \
    | sort | uniq \
    > .sel-runs
  for fraw in `cat .sel-runs`; do
    fname="${fraw%%.txt}"
    runfilter ${fname} 1 >> ${gfile} 2>&1
  done

  # Plotting the power spectra of selected filtered and noise runs:
  echo "computing and plotting power spectra of selected runs" 1>&2
  plot_some_runs_and_spectra.sh SHOW ${fltdir} 0 -1 51 101 500 "${notable_runs[@]}" >> ${gfile} 2>&1
  plot_some_runs_and_spectra.sh SHOW ${nsedir} 0 -1 250 151 500 "${notable_runs[@]}" >> ${gfile} 2>&1


  echo 'done.' 1>&2
  echo "......................................................................" 1>&2
  echo "From ${gfile} " 1>&2
  egrep -e '[!*][!*]|^[=][=][=]' ${gfile} 1>&2
  echo "......................................................................" 1>&2
  echo "######################################################################" 1>&2
}

subjfilter ${subj}
