#! /bin/bash

# Arguments: {DMIN} {DMAX} {VMIN} {VMAX}
#
# where {DMIN.DMAX} is the range of dates to plot,
# and {VMIN,VMAX} is the range of prices for the plot.

dmin="$1"; shift;
dmax="$1"; shift;
vmin="$1"; shift;
vmax="$1"; shift;

name="deg2-full"
dfile="fit-${name}-data.txt"
cfile="fit-${name}-coeffs.txt"
ffile="fit-${name}-fitted.txt"
pfile="fit-${name}-fitted.png"

cat data.txt \
  | gawk \
     ' BEGIN { k = 0; } 
       // {
         dt = $1; pm = $2;
         wt = (pm > 0.0 ? 1.000 : 0.000) 
         t = k/1000;
         printf "%s %+14.6f %6.3f %3.1f %6.3f %12.6f\n", dt, log(pm + 1.0e-30), wt, 1, t, t*t
         k++
       }
     ' \
  > ${dfile}
  
cat ${dfile} \
  | linear_fit \
      -terms 3 \
      -weighted T \
      -writeFormula ${cfile} \
  | gawk \
      ' // {
          dt = $1; lpm = $2; lpf = $3;
          pm = (lpm < -10 ? 0.0 : exp(lpm)); 
          pf = exp(lpf);
          printf "%s %12.5f %12.5f\n", dt, pm, pf;
        }
      ' \
  > ${ffile}
  
plot_poly_fit.sh \
    "Quadratic extrapolation" \
    ${dmin} ${dmax} ${vmin} ${vmax} ${ffile} \
  > ${pfile}
