#! /bin/bash
# Last edited on 2015-02-21 18:14:15 by stolfilocal

# Plots the traffic for one wallet.
# 
# Arguments: {DFILE} {CUM} {VAR} {INIDATE} {FINDATE} {WALLET} {OUTDIR}
# 
# Where 
#   
#   {DFILE}    is the input data file.
#   {USDBINS}  is 0 is bin ranges are in BTC, 1 if they are in USD
#   {CUM}      is 0 for simple histogram, 1 for cumulative hitogram.
#   {VAR}      is 0 for op counts, 1 for BTC totals, 2 for USD totals.
#   {INIDATE}  first date present in file (for title and filenames).
#   {FINDATE}  last date present in file (for title and filenames).
#   {WALLET}   is the ID of the wallet (for titles).
#   {OUTDIR}   directory for output plots.
#  
# The input file (read from {stdin}) must contain one line per day in the 
# format "{IB} {VMIN} {VMID} {VMAX} {NOPS} {TBTC} {TUSD}"  
# See {extract_wallet_histogram.gawk} for details.
#
# The plots are called "{OUTDIR}/{INIDATE}--{FINDATE}-u{USDBINS}-{bin,cum}-hist.{png,jpg}"
# 

dfile="$1"; shift   
usdBins="$1"; shift     
cum="$1"; shift        
var="$1"; shift     
iniDate="$1"; shift # First date in file.
finDate="$1"; shift # Last date in file.
wallet="$1"; shift  # Wallet name, for titles
pdir="$1"; shift 

show="SHOW"

tmp="/tmp/$$"

if [[ ${usdBins} -eq 0 ]]; then
  titbins="BTC bins"
else
  titbins="USD bins"
fi

set_y_scale="set logscale y; set yrange[(-ymin):]";
if [[ ${cum} -eq 1 ]]; then
  titcum="cumulative"; xcum="cum"; 
  echo "** cumulative histograms not implemented" 1>&2; exit 1
else
  titcum="(binned)"; xcum="bin"; 
fi

if [[ ${var} -eq 0 ]]; then
  titvar="Op count"; xvar="num";
  ymin="1";
elif [[ ${var} -eq 1 ]]; then
  titvar="Total BTC"; xvar="btc";
  ymin="0.0001"
elif [[ ${var} -eq 2 ]]; then
  titvar="Total USD"; xvar="usd";
  ymin="0.001"
else
  echo "** invalid {var} = \"${var}\"" 1>&2; exit 1
fi

title="Wallet ${wallet} -- ${iniDate}--${finDate} -- ${titvar} ${titcum} -- ${titbins}"

oprefix="${pdir}/${iniDate}--${finDate}-u${usbBins}-${xvar}-${xcum}-hist"

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

pfile="${oprefix}.png"
jfile="${oprefix}.jpg"

export GDFONTPATH=.:..

gnuplot <<EOF
set term png size 3000,1000 font "courbd,24"
set output "${pfile_full}"

ymin = (${ymin})
${set_y_scale}

set title "${title}"

set grid xtics  lt 1 lw 3 lc rgb '#ffddaa', lt 1 lw 2 lc rgb '#ffddaa'
set grid mxtics
set grid ytics  lt 1 lw 3 lc rgb '#ffddaa', lt 1 lw 2 lc rgb '#ffddaa'

set xzeroaxis lt 1 lw 3 lc rgb '#ffddaa'
set key left top

# Columns of output, shuffle, input
kvar = 5 + ${var}

plot \
  "${dfile}" using 1:(column(kvar)) title "${titvar}" with histeps lt 1 lw 2.0 lc rgb '#000088'
quit
EOF

if [[ -s ${pfile_full} ]]; then 
  convert ${pfile_full} -resize '50%' ${pfile}
  convert ${pfile} -quality 80 -resize '600x' ${jfile}
  if [[ "/${show}" == "/SHOW" ]]; then display ${pfile} ${jfile}; fi
fi

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