#! /bin/bash
# Last edited on 2018-04-11 12:32:54 by jstolfi

# Reads a trace file of a simulation.
# Plots the potentials of selected neurons as a function of time.
# The neurons in the trace file are indexed from 0 on.

fname="$1"; shift  # Traces file name
i0="$1"; shift     # Index of first neuron to plot.
i1="$1"; shift     # Index of last neuron to plot.

tmp="/tmp/$$"

# END COMMAND LINE PARSING
# ----------------------------------------------------------------------

# Prefix for temporary file names
tmp="/tmp/$$"

# Create the gnuplot command file:
tmpplt="${tmp}.gnuplot"
cat > ${tmpplt} <<EOF
set terminal png truecolor size 1200,800 font "arial,18"
set output "${tmp}.png"
set xrange [-1:]
set yrange [-60:+10]
set xzeroaxis 
set yzeroaxis
set key Left Bottom
set ytics 20
set mytics 4
set grid mytics lt 3
set grid ytics lt 0
set title "traces"
EOF

color=( "ff0000" "996600" "338800" "008800" "007755" "0033ff" "5500ff" "aa0066" "aa2200" "557700" "117700" "007722" "005588" "2222ff" "880088" )
sep=""
iplot=${i0};
icolor=0;
printf "plot \\\\\n" >> ${tmpplt}
while [[ ${iplot} -le ${i1} ]]; do
  col=$(( 5 * ${iplot} + 6 ))
  printf "%s\"${fname}\" using 1:%d title \"V_{%02d}\" with lines lt 1 lw 1.0 lc rgb '#%s' \\\\\n" \
      "${sep}" "${col}" "${iplot}" "${color[${icolor}]}" \
    >> ${tmpplt}
  sep=','
  icolor=$(( ${icolor} + 1 ))
  if [[ ${icolor} -ge ${#color[@]} ]]; then icolor=0; fi
  iplot=$(( ${iplot} + 1 ))
done

printf "\n" >> ${tmpplt}
printf "quit\n" >> ${tmpplt}

export GDFONTPATH="."

gnuplot < ${tmpplt}

if [[ -s ${tmp}.png ]]; then
  pfile="${fname%.*}.png"
  convert ${tmp}.png -resize '50%' ${pfile}
  display ${pfile}
fi
