#! /bin/bash
# Last edited on 2009-12-12 00:21:31 by stolfi

# Plots the WP monthly size and growth rate.
# Assumes that input is "{TIME} {YEAR} {MONTH} {DAY} {SZ} {SU}  {DZ} {DU}"
# where {TIME} is spaced {sper} days apart starting with {sper-1}, {SZ} is size
# interpolated at {TIME}, {DZ} is the increment in {SZ} during the last {sper} days.
# The fields {SU} and {DU} are reliability flags (1 ok, 0 dubious, 9 discard)

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

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

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

if [[ ${pha} -eq 0 ]]; then
  xrange="set xrange [2000.8:2010.8]"
  yrange="set yrange [-1000:+66000]"
  evtics="400000"
elif [[ ${pha} -eq 1 ]]; then
  xrange="set xrange [2000.8:2004.8]"
  yrange="set yrange [-500:+25500]"
  evtics="50000"
elif [[ ${pha} -eq 2 ]]; then
  xrange="set xrange [2005.3:2010.7]"
  yrange="set yrange [-1000:+66000]"
  evtics="400000"
else
  echo "invalid pha = [${pha}]" 1>&2 ; exit 1
fi

# In this plot we assume that {su} is 0 or 1:
for su in 0 1; do
  cat ${datafile} \
    | gawk -v su=${su} '/^ *([\#]|$)/{ next; } ($6 == su){ print; next; } // { print ""; }' \
    > ${seppref}-sz-${su}.txt
done

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

gnuplot <<EOF
set term postscript eps color solid "TimesRoman" 24
set size 1.5,1.0
set output "${epsfile}"
set key left samplen 1.0
set style fill solid 0.50 border

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

${yrange}
set grid ytics

sper=28
bbot(i,j)=column(j)+0.7*(${evtics})
blen(i,j)=1.0*(${evtics})
btop(i,j)=bbot(i,j)+blen(i,j)

yearsz(i)=(column(i)/365.25 + 2001)
yeardz(i)=((column(i)-(0.5*sper))/365.25 + 2001)
set boxwidth sper/365.25
plot \
  "${seppref}-dz-1.txt" using (yeardz(1)):7 \
      title "N'(t)" with linespoints pt 7 ps 1.0 lt rgb '#ee4422', \
  "${seppref}-dz-0.txt" using (yeardz(1)):7 \
      notitle with points pt 6 ps 1.0 lt rgb '#bb5566', \
  "data/counter-breaks.txt" using 1:(btop(5,6)/100):(0.0):(-blen(5,6)/100) \
      notitle with vectors lw 3.0 lt rgb '#ee1177', \
  "${seppref}-sz-1.txt" using (yearsz(1)):(column(5)/100) \
      title "N(t)/100" with linespoints pt 7 ps 1.0 lt rgb '#4499ee', \
  "${seppref}-sz-0.txt" using (yearsz(1)):(column(5)/100) \
      notitle with points pt 6 ps 1.0 lt rgb '#77aabb'
quit
EOF

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