#! /bin/bash 
# Last edited on 2013-05-29 22:42:15 by stolfilocal

# Usage: 
#   
#   plot_electrode_correlations.sh {FILE_NAME} {FIRST_REPEAT} {LAST_REPEAT}
#   
# where
#   
#   {FILE_NAME} is the file name prefix.
#   {FIRST_REPEAT} is the index of the first repeat of the experiment (from 1).
#   {LAST_REPEAT} is the index of the last repeat of the experiment.
#
# Reads {FILE_NAME}.txt, which is the output of {extract_electrode_pair.gawk}
# Writes {FILE_NAME}.png a plot file

fname=$1; shift
inir=$1; shift
finr=$1; shift

if [[ ${inir} -lt 1 ]]; then
  echo "bad first index" 1>&2 ; exit 1
fi

if [[ ${finr} -lt ${inir} ]]; then
  echo "bad range" 1>&2 ; exit 1
fi

tmp=/tmp/$$

# Prepare the data file:
cat ${fname}.txt | grep -v '=' > ${tmp}.dat

# Prepare the plot commad file:

color=( ee0000 aa5500 447700 008800 007755 0055ff 3333ff 5500ff )
nc=${#color[@]}

kr=${inir}
kc=0
sep=""
printf "plot" > ${tmp}.gpl
while [[ ${kr} -le ${finr} ]]; do
  printf "%s \\\\\n" ${sep} >> ${tmp}.gpl
  printf "  '%s.txt' using 1:%d title '%02d' with linespoints pt 7 lc rgb '#%s'" \
    "${fname}" "$(( 1 + kr ))" "${kr}" "${color[${kc}]}" >> ${tmp}.gpl
  kr=$(( kr + 1 ))
  kc=$(( kc + 1 ))
  if [[ ${kc} -ge ${nc} ]]; then kc=0; fi
  sep=','
done
printf "\n" >> ${tmp}.gpl

cat ${tmp}.gpl 1>&2

export GDFONTPATH=.

gnuplot <<EOF
set term png size 1600,1200 font "arial,20"
set output "${tmp}.png"
set yrange [-1.05:+1.05]
load "${tmp}.gpl"
quit
EOF

convert ${tmp}.png -resize '50%' ${fname}.png
display ${fname}.png

rm -fv ${tmp}.*
