#! /bin/bash
# Last edited on 2009-12-13 09:08:18 by stolfi

pha="$1"; shift
logscale="$1"; shift
datafile="$1"; shift

echo "${0##*/} pha = ${pha} logscale = ${logscale} datafile = ${datafile}" 1>&2

seppref="/tmp/$$-sep"
epsfile="/tmp/$$.eps"

if [[ ${pha} -eq 0 ]]; then
  xrange="set xrange [2000.8:2010.8]"
  dzmax="80000"
elif [[ ${pha} -eq 1 ]]; then
  xrange="set xrange [2000.8:2004.8]"
  dzmax="35000"
elif [[ ${pha} -eq 2 ]]; then
  xrange="set xrange [2006.3:2010.7]"
  dzmax="80000"
else
  echo "invalid pha = [${pha}]" 1>&2 ; exit 1
fi

if [[ ${logscale} -gt 0 ]]; then 
  dzmin="(dzmax/100.0)"
  yscale="set logscale y"
else
  dzmin="(-0.05*dzmax)"
  yscale=" "
fi

# In this plot we assume {du} is either 1 (ok), 0 (suspicious) or 9 (ignore):
for du in 0 1; do
  cat ${datafile} \
    | gawk -v du=${du} \
        ' /^ *([\#]|$)/{ next; } 
          ($10 == du){ print; next; } 
          // { print ""; } 
        ' \
    > ${seppref}-dz-${du}.txt
done

gnuplot <<EOF
set term postscript eps color solid "TimesRoman" 24
set output "${epsfile}"
set size 1.5,1.0

dzmax=${dzmax}
dzmin=${dzmin}
sper=28
yeardz(i)=((column(i)-(0.5*sper))/365.25 + 2001)

set key reverse left Left samplen 1.0
set samples 200

set grid xtics
set xtics 1.0 format "        %4.0f"
set mxtics 12
${xrange}

${yscale}
set ytics format "%8.0f"
set yrange[dzmin:dzmax]
set grid ytics

plot \
  "${seppref}-dz-1.txt" using (yeardz(1)):9 title "observed" with points pt 7 ps 1.0 lc rgb '#ee4422', \
  "${seppref}-dz-0.txt" using (yeardz(1)):9 notitle with points pt 6 ps 1.0 lc rgb '#bb5566', \
  "${datafile}" using (yeardz(1)):11 smooth csplines title "model" with lines lt 1 lw 3.0 lc rgb '#cc2200'

quit
EOF

cat ${epsfile}
gv ${epsfile}
rm -f ${epsfile} ${seppref}-*.txt
