#! /bin/bash
# Last edited on 2023-10-21 18:24:06 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}/${name}.txt" where ${name} is one of the
# names listed in ${runs[@}}. The spectra for each file "${name}.txt"
# will be written to "${name}_pwr.txt", and its plot will
# be "${name}_pwr.png", in directory ${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/$$"

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
