#! /bin/bash
# Last edited on 2021-09-02 06:23:48 by stolfi

show="$1"; shift      # "SHOW" or "NOSHOW"
rundir="$1"; shift    # Directory where runs are.
ie_ini="$1"; shift    # First electrode index (from 0) for power spectra.
ie_fin="$1"; shift    # Last electrode index for power spectra, or -1 for all.
pwr_fmax="$1"; shift  # Max frequency to plot in Hz.
vmax="$1"; shift      # Max value for potential plot.
vsize="$1"; shift     # Vertical plot size in pixels.

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}.

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

tmp="/tmp/$$"

plotfiles=()

function plotrun(){

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

  runfile="${rundir}/${rname}.txt"
  runplot="${rundir}/${rname}.png"

  rm -f ${runplot} 
  plot_run.sh NOSHOW "${rundir}/${rname}" ${ie_ini} ${ie_fin} ${vmax} ${vsize}
  plotfiles+=( ${runplot} )

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

  # vmax_pwr=`echo "p=${vmax}; 10*p*p" | bc -lq`
  plot_run_spectrum.sh NOSHOW ${rundir}/${rname} ${ie_ini} ${ie_fin} ${pwr_fmax} ${vsize}
  # ls -l ${pwrfile} ${pwrplot}
  if [[ ! (-s ${pwrfile} ) ]]; then exit 1; fi
  if [[ ! (-s ${pwrplot} ) ]]; then exit 1; fi
  plotfiles+=( ${pwrplot} )

}

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

if [[ "/${show}" == "/SHOW" ]]; then 
  eom ${plotfiles[@]}
fi
