#! /bin/bash
# Last edited on 2014-03-18 20:25:30 by stolfilocal

# Plots the slumber volume ratios {Vhi/Vhj} for each day
# 
# Arguments: {TITLE} {FNAME}
# 
# Where 
#   
#   {TITLE} is the plot's title;
#   {FNAME} is a data file with one line per slumber time in format
#      "{DATE} {TIME} | {NDAY} | {QL} | {HUBI.VH0} | {HUBI.VH1} | {HUBI.VH2} | {HUBI.VD}"

title="$1"; shift  # Plot title.
fname="$1"; shift  # Input file name. 

show="SHOW"

tmp="/tmp/$$"

timg="${tmp}-full.png"

color=( '#0022ff' '#ff0000' '#008800' '#8800dd' '#dd4400' '#0066ff' )

export GDFONTPATH=.:..

gnuplot <<EOF
# ----------------------------------------------------------------------
# Common definitions:

zerotonan(z) = (z == 0 ? 0/0 : z)

set timefmt "%Y-%m-%d %H:%M:%S" # For {timecolumn}.
set lmargin 10
set rmargin 4
set bmargin 2.5
set tmargin 2.5

set xtics mirror
set xdata time
set grid xtics lt 1 lw 3 lc rgb '#ffddaa', lt 1 lw 1.5 lc rgb '#ffddaa'
set grid mxtics
set format x "%b/%d"

set term png size 2400,600 font "courbd,18"
set output "${timg}"
set title "${title} - slumber hourly volume ratios 02:00--04:59 CST"

set logscale y
set yrange [0.00999:101.0]
set grid ytics lt 1 lw 3 lc rgb '#ffddaa', lt 1 lw 1.5 lc rgb '#ffddaa'
set grid mytics

set key top right

plot \
  (1.00) notitle with lines lt 1 lw 2.0 lc rgb '#4466ff', \
  "< grep -e '^20' ${fname}" using (timecolumn(1)):(zerotonan(column(16))/zerotonan(column(18))) title "Vh(02:30)/Vh(03:30)" \
    with linespoints pt 7 ps 2.0 lt 1 lw 1.0 lc rgb '#aa0088', \
  ""                         using (timecolumn(1)+10000):(zerotonan(column(20))/zerotonan(column(18))) title "Vh(04:30)/Vh(03:30)" \
    with linespoints pt 7 ps 2.0 lt 1 lw 1.0 lc rgb '#aa6600'
quit
EOF

if [[ -s ${timg} ]]; then
  oimg="${tmp}-red.png"
  convert ${timg} -resize '50%' ${oimg}

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

cat ${oimg}

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