#! /bin/bash
# Last edited on 2015-04-17 23:24:52 by stolfilocal
    
prefix="$1"; shift
logscale="$1"; shift
c="$1"; shift
b="$1"; shift
a="$1"; shift
echo "p(2012+x) = (${a})*x^2 + (${b})*x + (${c})" 1>&2

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

tmp="/tmp/$$"

for var in prices curve ; do
  vfile="${tmp}-${var}-extrap-${logscale}.txt"
  cat ${pricesfile} \
    | gawk \
          -v var=${var} \
          -v logscale=${logscale} \
          -v a="${a}" -v b="${b}" -v c="${c}" \
        ' BEGIN { 
            y0 = 2012.8466;
            y1 = 2016.8466; 
            dy = (var == "curve" ? 1.0/32 : 1);
            yp0 = (var == "curve" ? y0 - 0.25 : y0);
            yp1 = (var == "curve" ? y1 + 0.25 : y1);
            for (y = yp0; y <= yp1 + 0.00000001; y += dy) { 
              x = y - y0; 
              z = c + b*x + a*x*x; 
              p = (logscale ? exp(z*log(10)) : z); 
              printf "%9.4f %8.2f\n", y, p;
            }
          }
        ' \
    > ${vfile}
  echo "${vfile}" 1>&2
  cat ${vfile} 1>&2
done

if [[ ${logscale} -ne 0 ]]; then
  curvtit="fitted log-quadratic"
else
  curvtit="fitted quadratic"
fi

export GDFONTPATH=.

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

set xtics 1
set mxtics 12
logscale=${logscale}

set xrange [2012.3:2017.3]
if (logscale) {
  set logscale y
  set yrange [0.05:9000.0]
} else {
  set yrange [-0.05:420.1]
  set ytics 50
  set mytics 5
}
set grid xtics  lt 1 lw 3 lc rgb '#ffddaa', lt 1 lw 2 lc rgb '#ffddaa'
set grid ytics  lt 1 lw 3 lc rgb '#ffddaa', lt 1 lw 2 lc rgb '#ffddaa'
set key top left Left reverse

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

if [[ -s ${tmp}.png ]]; then
  convert ${tmp}.png -resize '50%' ${pngfile}
  if [[ "/${show}" == "/SHOW" ]]; then
    display ${pngfile}
  fi
  echo "${pngfile}" 1>&2
fi

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