#! /bin/bash
# Last edited on 2015-04-07 20:50:35 by stolfilocal

ddate="$1"; shift

datafile="${ddate}-table.txt"
plotfile="${ddate}-smbit-plot.png"

show="SHOW"

tmp="/tmp/$$"
tmpdata="${tmp}.dat"
tmpfile="${tmp}-full.png"

export GDFONTPATH=.:..

cat ${datafile} \
  | gawk -v FS='|' \
      ' /^(Seed|[0-9][0-9][-][A-Z])/ {
          gsub(/Seed/, "24-Sep-13", $0);
          printf "%s ", $1;
          for (i=2; i<=NF; i++) { 
            X=rmb($(i)); 
            if ( X=="" ) { X = "nan"; } 
            printf " %s", X; 
          } 
          printf "\n"; next;
        } 
        // { next; } 
        function rmb(x){ gsub(/^[ ]+/,"",x); gsub(/[ ]*$/,"",x); return x; }
      ' \
   > ${tmpdata}

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

set key top left

# Input time format:
set timefmt "%d-%b-%y"

set title "Second Market Bitcoin Investment Trust (SMBIT)"

ttics = 24 # Time between major tics (weeks)
set xdata time
set format x "%Y-%m-%d"
set xtics ttics*7*24*3600
set mxtics ttics
set grid xtics lt 1 lw 3 lc rgb '#ffddaa', lt 1 lw 1.5 lc rgb '#ffddaa'
set grid mxtics

set yrange [-5:155]
set grid ytics lt 1 lw 3 lc rgb '#ffddaa', lt 1 lw 1.5 lc rgb '#ffddaa'
set mytics 2
set grid mytics


plot \
  "${tmpdata}"  using (timecolumn(1)):2                 title "Nominal Share Value (\$)"        with linespoints pt 7 ps 0.75 lt 1 lc rgb '#ff0000', \
  ""            using (timecolumn(1)):3                 title "Net Total Assets (M\$)"          with linespoints pt 7 ps 0.75 lt 1 lc rgb '#008800', \
  ""            using (timecolumn(1)):(column(4)/1000)  title "Est. Bitcoin Holdings (kBTC)"    with linespoints pt 7 ps 0.75 lt 1 lc rgb '#0055ff', \
  ""            using (timecolumn(1)):(column(7)/1000)  title "Actual Bitcoin Holdings (kBTC)"  with      points pt 6 ps 1.50 lt 1 lc rgb '#ff00ff', \
  ""            using (timecolumn(1)):8                 title "Est. Accum. Investment (M\$)"    with linespoints pt 7 ps 0.75 lt 1 lc rgb '#ff00ff'

quit
EOF

convert ${tmpfile} -resize '50%' ${plotfile}

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

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