#! /bin/bash
# Last edited on 2017-08-03 17:58:01 by jstolfi

fname="$1"; shift

tmp="/tmp/$$"

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

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

# Save input data in temp file:
tmpfni="${tmp}.fni"
cat > ${tmpfni}

# Extract plottable data, save in another temp file:
tmpdat="${tmp}.dat"
gawk '/^[ ]*[-+]?[0-9]/ { print; }' ${tmpfni} > ${tmpdat}

# Preparations for vertical range:
if [[ ${yrange} -ne 0 ]]; then
  yrangevars="ymin=(${ymin}); ymax=(${ymax}); dv=0.02*(ymax-ymin)"
  setyrange="set yrange [(ymin-dv):(ymax+dv)]"
else
  yrangevars=""
  setyrange=""
fi
if [[ ${xrange} -ne 0 ]]; then
  xrangevars="xmin=(${xmin}); xmax=(${xmax}); dv=0.02*(xmax-xmin)"
  setxrange="set xrange [(xmin-dv):(xmax+dv)]"
else
  xrangevars=""
  setxrange=""
fi
  
# Create the gnuplot command file:
tmpplt="${tmp}.gnuplot"
cat > ${tmpplt} <<EOF
set terminal postscript eps color 
set output
set size 2,0.75
${xrangevars}
${setxrange}
${yrangevars}
${setyrange}
set xzeroaxis 
set yzeroaxis
set nokey
set ytics 0.5
set mytics 5
set grid mytics lt 0, lt 3
set title "${title}"
EOF

ltype=( 1 2 3 )
itype=0
sep=""
iplot=0;
printf "plot \\\\\n" >> ${tmpplt}
while [[ ${iplot} -lt ${#indices[@]} ]]; do
  ix=${indices[${iplot}]}
  channel=$(( ${ix} + 1 ))
  printf "%s\"${tmpdat}\" using 3:%d title \"bas[%02d]\" with lines lt %d lw 3.0 \\\\\n" \
      "${sep}" "$(( ${channel} + 3))" "${ix}" "${ltype[${itype}]}" \
    >> ${tmpplt}
  sep=','
  itype=$(( ${itype} + 1 ))
  if [[ ${itype} -ge 3 ]]; then itype=0; fi
  iplot=$(( ${iplot} + 1 ))
done

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

gnuplot < ${tmpplt}

# /bin/rm -f ${tmpfni} ${tmpdat} ${tmpnum} ${tmpplt}

export GDFONTPATH="."

gnuplot <<EOF
  set term png truecolor size 1200,800 font "arial,18"
  set output "${tmp}-t.png"
  set xrange [0:${ng}]
  set yrange [0:${np}]
  plot "out/traces.dat" using 2:3 with lines
  quit
EOF

convert ${tmp}-t.png -resize '50%' out/traces.png 
