#! /bin/bash
# Last edited on 2014-01-16 22:50:05 by stolfilocal

# Arguments:
#
#   {SHOW} {PREFIX}
#
# where
#
#   {SHOW} "SHOW" to display, "NOSHOW" not to.
#   {PRFIX} is the in/out file name prefix.
#
# Reads {PREFIX}.txt, which is supposed to contain a list of triplets, one per line,
# {I} {Z[I]} {Y[I]}
# where {Zi]} is the actual value at time {i} and 
# {Y[i]} is the predicted value.  Writes {PREFIX}.png showing
# {Z[I]}, {Y[I]}, and the prediction error {Y[i] - Z[i]}. 

show=$1; shift
prefix="$1"; shift

infile="${prefix}.txt"

if [[ ! ( -e ${infile}) ]]; then
  echo "** no file \"${infile}\"" 1>&2 ; exit 1
fi

tmp="/tmp/$$"

pngfile="${prefix}.png"

export GDFONTPATH=.

gnuplot <<EOF
set term png size 2800,2000 font "courbd,24"
set grid xtics lt 1 lw 3 lc rgb '#ffddaa', lt 1 lw 1.5 lc rgb '#ffddaa'
set output "${tmp}.png"
yden = 2000.0/1800.0
e10(k) = exp(log(10.0)*column(k))
set multiplot layout 1,1 title "${prefix}"
# ----------------------------------------------------------------------
# Pairs
set origin 0.0,(0.500/yden)
set size 1.0,(0.475/yden)
plot "${infile}" using 1:(e10(2)*1000.0) title "Z[i]" with linespoints lt 1 lw 1.5 pt 7 ps 2.0 lc rgb '#0077ff', \
     ""          using 1:(e10(3)*1000.0) title "Y[i]" with linespoints lt 1 lw 1.0 pt 7 ps 1.0 lc rgb '#441100'
# ----------------------------------------------------------------------
# Difference
set origin 0.0,(0.000/yden)
set size 1.0,(0.475/yden)
plot "${infile}" using 1:(column(3)-column(2)) title "Y[i]-Z[i]" with impulses lt 1             lc rgb '#335533', \
     ""          using 1:(column(3)-column(2)) title "Y[i]-Z[i]" with points   lt 1 pt 7 ps 1.0 lc rgb '#007700'
# ----------------------------------------------------------------------
unset multiplot
quit
EOF

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

if [[ "/${show}" == "/SHOW" ]]; then
  display ${pngfile}
fi

rm -fv ${tmp}{-*,}.*
