#! /bin/bash
# Last edited on 2021-09-02 17:54:31 by stolfi

show="$1"; shift    # "SHOW" or "NOSHOW".
topDir="$1"; shift; # Parent dir of all subjects and runs.
subj="$1"; shift;   # Subject ID, e.g. "s019".
run="$1"; shift     # Run id, e.g. "r00221".
vmaxC="$1"; shift   # Max potential for plot of components (uV).
vmaxR="$1"; shift   # Max potential for plot of residual (uV).
compNames=( "$@" )       # Names of components to extract.

pcaTag="A1"

subjRunName="${subj}/${run}"      # Full run name, including subject ID.

subjDir="${topDir}/${subj}"   # Subject's folder.
pcaDir="${subjDir}/${pcaTag}" # Directory where the PCA-related files are.

inFile="${topDir}/${subj}/${run}.txt"           # Input EEG file name.

sumFile="${pcaDir}/${run}_SUM.txt"      # Output file name with total extracted components.
ampFile="${pcaDir}/${run}_AMP.txt"      # Output file name of component amplitudes.
resFile="${pcaDir}/${run}_RES.txt"      # Output file name residual EEG .

patOps=()
wrOps=()
eegNames=()
for cName in ${compNames[@]} ; do
  patOps+=( -pattern ${cName} ${subjDir}/${pcaTag}/${cName}_eig.txt )
  wrOps+=( -writeComp ${cName} ${subjDir}/${pcaTag}/${run}_${cName}.txt = ${cName} )
  eegNames+=( ${subj}/${pcaTag}/${run}_${cName} )
done
eegNames+=( ${subj}/${pcaTag}/${run}_AMP ${subj}/${pcaTag}/${run}_SUM )

rm -fv ${subjDir}/${run}*.png ${pcaDir}/${run}*.png

echo "running {nmeeg_comp_analysis}..." 1>&2
nmeeg_comp_analysis \
  ${patOps[@]} \
  -normalize \
  ${wrOps[@]} \
  -writeComp SUM ${sumFile} = ${compNames[@]} \
  -writeCoeffs ${ampFile} \
  -delete ${compNames} \
  < ${inFile} \
  > ${resFile}
  
fmax=50
vsize=500

if [[ ! ( -s ${resFile} ) ]]; then
  echo "** nmeeg_comp_analysis failed" 1>&2; exit 1
fi
  
logdate="`yyyy-mm-dd-hhmmss`"
plot_some_runs_and_spectra.sh NOSHOW ${topDir} 0 -1 ${fmax} ${vmaxC} ${vsize}  ${subjRunName}  ${eegNames[@]}

logdate="`yyyy-mm-dd-hhmmss`"
plot_some_runs_and_spectra.sh NOSHOW ${topDir} 0 -1 ${fmax} ${vmaxR} ${vsize}  ${subj}/${pcaTag}/${run}_RES

if [[ "/${show}" == "/SHOW" ]]; then
  display ${subjDir}/${run}*.png ${pcaDir}/${run}*.png
fi
