#! /bin/bash
# Last edited on 2015-04-17 23:16:39 by stolfilocal

prefix="$1"; shift

show="SHOW"
pricesfile="${prefix}-prices.txt"
pngfile="${prefix}-prices-extrap.png"

tmp="/tmp/$$"

for var in gains prices curve ; do
  vfile="${tmp}-${var}-extrap.txt"
  cat ${pricesfile} \
    | gawk -v var=${var} \
        ' BEGIN { 
            y0 = 2011.3123; p0 = 1.70;
            y1 = 2015.3123; 
            dy = (var == "curve" ? 1.0/32 : 1);
            for (y = y0; y <= y1 + 0.999; y += dy) { 
              x = y - y0 - 1; 
              z = 0.47712 + 1.99651*x - 0.99312*x*x; 
              g = exp(z*log(10)); 
              if (var == "gains") { 
                if (y > y0) { printf "%9.4f %8.2f\n", y - 0.5, 100*g; }
              } else if (var == "curve") { 
                if ((y > y0 + 0.75) && (y < y1 + 0.25)) { printf "%9.4f %8.2f\n", y - 0.5, 100*g; }
              } else {
                p = (y == y0 ? p0 : g*p);
                printf "%9.4f %8.2f\n", y, p;
              }
            }
          }
        ' \
    > ${vfile}
  echo "${vfile}" 1>&2
  cat ${vfile} 1>&2
done

export GDFONTPATH=.

gnuplot <<EOF
set term png size 960,960 font "courbd,18"
set output "${tmp}.png"
set title "BTC price on Apr/24 of each year"

set xtics 1
set mxtics 12

set xrange [2010.8:2015.9]
set logscale y
set yrange [0.009:50000.0]

plot \
  "${pricesfile}"            using 1:2 title "actual price (USD)"    with points pt 7 ps 4 lc rgb '#ff0000', \
  "${tmp}-gains-extrap.txt"  using 1:2 title "percent increase"      with points pt 7 ps 2 lc rgb '#008800', \
  "${tmp}-curve-extrap.txt"  using 1:2 title "fitted log-quadratic"  with lines lt 1 lw 1  lc rgb '#008800', \
  "${tmp}-prices-extrap.txt" using 1:2 title "predicted price (USD)" with linespoints lt 1 lw 2 pt 7 ps 2 lc rgb '#0033ff' 
quit
EOF

convert ${tmp}.png -resize '50%' ${pngfile}

if [[ "/${show}" == "/SHOW" ]]; then
  display ${pngfile}
fi
echo "${pngfile}" 1>&2

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