#! /bin/bash
# Last edited on 2017-11-24 14:43:32 by jstolfi

logdate="$1"; shift # Date for log name prefix
rundir="$1"; shift  # Directory where runs are.
vmax="$1"; shift    # Max voltage (uV) for vertical scaling of time plots.

# Plots all raw runs extracted from the 128-electrode datasets.
# Also computes and plots their power spectra.

# 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 the plots will be
# "${FNAME}.png" and "${FNAME}_pwr.png".

# Writes a log file for each subject in "${rundir}/s${SSS}/plot_runs_and_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

mkdir -p ${rundir}

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

tmp="/tmp/$$"

function plotruns(){

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

  ic_ini=0     # First channel index (from 0) for time plots.
  ic_fin=130   # Last channel index for time plots.

  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.
  
  gfile="${rundir}/s${subject}/plot_runs_and_spectra_${logdate}.log"

  /bin/rm -f ${gfile}
  for rfile in ${rundir}/s${subject}/r?????.txt ; do
    echo "=== ${rfile} ===" >> ${gfile}
    fname="${rfile%%.txt}"
    
    plot="${fname}.png"
    pwrfile="${fname}_pwr.txt"
    pwrplot="${fname}_pwr.png"
    rm -f ${plot} ${pwrfile} ${pwrplot}

    plot_run.sh          NOSHOW ${fname} ${ic_ini} ${ic_fin} ${vmax} >> ${gfile} 2>&1
    ls -l ${plot}
    if [[ ! (-s ${plot} ) ]]; then break; fi

    plot_run_spectrum.sh NOSHOW ${fname} ${ie_ini} ${ie_fin} ${pwr_fmax} ${pwr_vsize} >> ${gfile} 2>&1
    ls -l ${pwrfile} ${pwrplot}
    if [[ ! (-s ${pwrfile} ) ]]; then break; fi
    if [[ ! (-s ${pwrplot} ) ]]; then break; fi
  done
  egrep -e '([!*][!*])|^[=][=][=]' ${gfile}
}

plotruns 010
# plotruns 011
# plotruns 012
# plotruns 013
# plotruns 014
# plotruns 015
# plotruns 016
# plotruns 017
# plotruns 018
# plotruns 019
# plotruns 020
plotruns 021
