#! /bin/bash
# Last edited on 2009-12-12 00:19:28 by stolfi

# Plots the WP monthly size, raw and cleaned/interpolated.
# Assumes that raw input is "{TIME} {YEAR} {MONTH} {DAY} {SZ} {SU}"
# and cleaned input is "{TIME} {YEAR} {MONTH} {DAY} {SZ} {SU}  {DZ} {DU}"
# The fields {SU} and {DU} are reliability flags (1 ok, 0 dubious, 9 discard)

pha="$1"; shift
rarfile="$1"; shift
intfile="$1"; shift

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

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

if [[ ${pha} -eq 0 ]]; then
  xrange="set xrange [2000.8:2010.8]"
  yrange="set yrange [0:+3600000]"
  evtics="400000"
elif [[ ${pha} -eq 1 ]]; then
  xrange="set xrange [2000.8:2004.8]"
  yrange="set yrange [0:+530000]"
  evtics="50000"
elif [[ ${pha} -eq 2 ]]; then
  xrange="set xrange [2006.3:2010.7]"
  yrange="set yrange [0:+3600000]"
  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 ${rarfile} \
    | gawk -v su=${su} '/^ *([\#]|$)/{ next; } ($6 == su){ print; next; } // { print ""; }' \
    > ${seppref}-sz-rar-${su}.txt
  cat ${intfile} \
    | gawk -v su=${su} '/^ *([\#]|$)/{ next; } ($6 == su){ print; next; } // { print ""; }' \
    > ${seppref}-sz-int-${su}.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

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

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

${yrange}
set grid ytics

bbot(i,j)=column(j)+0.7*(${evtics})
blen(i,j)=1.0*(${evtics})
btop(i,j)=bbot(i,j)+blen(i,j)
year(i)=(column(i)/365.25 + 2001)
yearsz(i)=(column(i)/365.25 + 2001)

plot \
  "data/counter-breaks.txt" using (year(1)):(btop(5,6)):(0.0):(-blen(5,6)) \
      notitle with vectors lw 3.0 lt rgb '#ee1177', \
  "${seppref}-sz-rar-1.txt" using (yearsz(1)):(column(5)) \
      title "N(t)" with points pt 7 ps 0.75 lt rgb '#0077ee', \
  "${seppref}-sz-rar-0.txt" using (yearsz(1)):(column(5)) \
      notitle with points pt 6 ps 0.75 lt rgb '#5599bb', \
  "${seppref}-sz-int-1.txt" using (yearsz(1)):(column(5)) \
      title "N(t)" with linespoints pt 7 ps 1.0 lt rgb '#4499ee', \
  "${seppref}-sz-int-0.txt" using (yearsz(1)):(column(5)) \
      notitle with points pt 6 ps 1.00 lt rgb '#77aabb'
quit
EOF

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