#! /bin/bash
# Last edited on 2021-08-26 20:59:59 by stolfi

printf '# Last edited on %s by %s\n' `yyyy-mm-dd-hhmmss` "${0##*/}" 1>&2
    
channels=( `cat channel_names.txt | gawk '/^[ ]*[0-9]/{ print $3; }'` )
printf "assuming %d channels = %s\n" "${#channels[@]}" "${channels[*]}" 1>&2

mkdir -p raw-runs

( cd ~/programs/c/NEUROMAT/nmeeg_split_e20_gh2012 && make uninstall build install )
( cd ~/programs/c/NEUROMAT/nmeeg_plot_channels && make uninstall build install )

function eegsplit(){
  origname="$1"; shift; # Name of raw source file, sans ".txt".
  subject="$1"; shift;  # Subject's ID number.
  nt_exp="$1"; shift;   # Frames expected in raw source file.
  nr_ini="$1"; shift;   # ID number of first run in source file.
  nr_exp="$1"; shift;   # Expected number of runs in source file.
  
  # set -o xtrace
 
  nt_run=4200  # Frames to include in each run.
  fsmp=600     # Sampling frequency in raw source file.
  
  # Get run types from log file:
  runtypes=( `runtypes_from_log.gawk raw/${origname}_seq.log | sed -e 's:nonBio:N:g' -e 's:Bio:B:g'` )
  if [[ ${#runtypes[@]} -ne ${nr_exp} ]]; then
    echo "** mismatched run counts ${#runtypes[@]} ${nr_exp}" 1>&2 ; exit 1;
  fi
  
  cat raw/${origname}.txt.gz \
    | gunzip \
    | nmeeg_split_e20_gh2012 \
        -subject ${subject} \
        -channels "${channels[@]}" \
        -nElectrodes 20 \
        -framesPerRun ${nt_run} \
        -firstRun ${nr_ini} \
        -fSampling ${fsmp} \
        -trigger "TR" -pulsesPerRun 4 \
        -runTypes ${runtypes[@]} \
        -source ${origname} \
        -marker "SOn" 0 1  -12  600 30.0 \
        -marker "Occ" 1 1 -612 1800 50.0 \
        -marker "RAp" 2 1 -312  900 70.0 \
        -outDir raw-runs
  
}

function plotruns(){

  subject="$1"; shift;  # Subject's ID number.

  ic_ini=0    # First electrode to plot.
  ic_fin=23   # Last electrode to plot.
  vmax=180    # Max voltage for plot scaling.

  for rfile in raw-runs/s${subject}_r???.txt ; do
    fname="${rfile%%.txt}"
    plot_run.sh NOSHOW raw-runs/${fname} ${ic_ini} ${ic_fin} ${vmax} 500
  done
}

rm -f raw-runs/s???_r???.{txt,png}

eegsplit s1_bl1   001 282640  1  50
eegsplit s1_bl2   001 285220 51  50
plotruns 001

eegsplit s2_bl1   002 295148  1  50
eegsplit s2_bl2   002 292860 51  50
plotruns 002

eegsplit s3_bl1   003 281334  1  50
eegsplit s3_bl2   003 287132 51  50
plotruns 003

eegsplit s4_bl1   004 290840  1  50
eegsplit s4_bl2   004 296645 51  50
plotruns 004

eegsplit s5_bl1-2 005 555755  1 100
plotruns 005

eegsplit s6_bl1   006 283420  1  50
eegsplit s6_bl2   006 290412 51  50
plotruns 006

eegsplit s7_bl1   007 286880  1  50
eegsplit s7_bl2   007 287820 51  50
plotruns 007

eegsplit s8_bl1   008 286700  1  50
eegsplit s8_bl2   008 286280 51  50
plotruns 008
