#! /bin/bash
# Last edited on 2017-10-19 07:55:58 by jstolfi

show="$1"; shift  # "SHOW" or "NOSHOW"
logdate="$1"; shift # Date for log name prefix
rundir="$1"; shift  # Directory where runs are.
runs=( "$@" )  # Runs in format "s${SSS}/r${BBB}${RR}" with no extension.

# Computes and plots spectra for selected runs from the 128-electrode datasets.

# Assumes that the raw extracted data for each run is in file "${rundir}/s${SSS}/r${BBB}${RR}.txt"
# where ${SSS} is the subject's numeric ID, ${BBB} is the block's numeric ID (001-008), and 
# ${RR} is the the run's numeric ID in the block (01--32).  The spectra for each file 
# "${FNAME}.txt" will be written to "${FNAME}_pwr.txt", and its plot will be
# "${FNAME}_pwr.png", in directory ${rundir}.

# Writes a log file in "${rundir}/plot_some-run_spectra_${logdate}.log".

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

( cd ~/programs/c/NEUROMAT/nmeeg_spectrum      && make uninstall build install )
( cd ~/programs/c/NEUROMAT/nmeeg_plot_spectra  && make uninstall build install )

tmp="/tmp/$$"
  
gfile="${rundir}/plot_some_run_spectra_${logdate}.log"
/bin/rm -f ${gfile}

function plotrun(){

  rname="$1"; shift # Run name as "s${SSS}/r${BBB}${RR}"

  ie_ini=0      # First electrode index (from 0) for power spectra.
  ie_fin=128    # Last electrode index for power spectra.
  pwr_fmax=250  # Max frequency to plot in Hz.
  pwr_vsize=500 # Vertical plot size in pixels for power spectra.

  rfile="${rundir}/${rname}.txt"
  echo "=== ${rfile} ===" >> ${gfile}

  pwrfile="${rundir}/${rname}_pwr.txt"
  pwrplot="${rundir}/${rname}_pwr.png"
  rm -f ${pwrfile} ${pwrplot}

  plot_run_spectrum.sh ${show} ${rundir}/${rname} ${ie_ini} ${ie_fin} ${pwr_fmax} ${pwr_vsize} >> ${gfile} 2>&1
  ls -l ${pwrfile} ${pwrplot}
  if [[ ! (-s ${pwrfile} ) ]]; then exit 1; fi
  if [[ ! (-s ${pwrplot} ) ]]; then exit 1; fi

}

for rname in "${runs[@]}" ; do 
  plotrun ${rname}
done

egrep -e '([!*][!*])|^[=][=][=]' ${gfile}
