#! /bin/bash
# Last edited on 2015-03-30 02:15:25 by stolfilocal

rundate="$1"; shift; # Nominal date of experiment.
hrad="$1"; shift;    # Radius of price smoothing window.
inFile="$1"; shift;  # Filename with input reference price.

dmin="2010-06-20"    # Min date for plot.
dmax="2015-03-10"    # Max date for plot.

make_jpg="YES"
show_jpg="NO"

trap "exit 1" SIGINT SIGTERM

parmsFile="${rundate}-bubble.parms"

outDir="out"
outPref="${outDir}/${rundate}-01d-sm${hrad}-bubbles"

outFile="${outDir}/${rundate}-01d-sm${hrad}.txt"

echo "${inFile} --> ${outFile}" 1>&2

export TZ="UTC" ; \
split_bubbles.gawk \
    -f useful_functions.gawk \
    -f smoothed_price_file_functions.gawk \
    -f bubble_parms_file_functions.gawk \
    -v parmsFile="${parmsFile}" \
    -v inFile="${inFile}" \
    -v hrad="${hrad}" \
  > ${outFile}

# Create a residual file for further analysis:
residFile=".rest.txt"
cat ${outFile} \
  | gawk '/^20/ { dy = $1; pism = $4; pmod = $6; printf "%s %18.5f\n", dy, pism-pmod; }' \
  > ${residFile}

# Plot the bubbles:
if [[ 10#${hrad} -eq 0 ]]; then
  wintit=""
else
  hwid=$(( 2 * 10#${hrad} + 1 )); # Total width of smoothing window.
  wintit=" (smoothed with ${hwid}-day Hann window)"
fi
plotPref="${outPref}"; # Plot file prefix.
pngFile="${plotPref}.png"
jpgFile="${plotPref}.jpg"
rm -f ${pngFile} ${jpgFile}

../plot_prices.sh \
  "Price bubbles - ${dmin} to ${dmax}${wintit}" \
  180 6 \
  "${dmin}" "${dmax}" \
  "0.04" "1600.0" \
  "YES" \
  "${outFile}" 4 "Price" 1.000 778899 \
  "${outFile}" 6 "Model" 1.000 228822 \
  "${outFile}" 8 "Ratio" 1.000 882222 \
  ` cat ${parmsFile} \
      | sort -b -k3,3 \
      | gawk \
          -v hrad=${hrad} \
          -v ofi=${outFile} \
          ' BEGIN { kf = 10; } \
            /^ *20/ { \
              printf "%s %d %s 1.000 %s\n", ofi, kf, $7, $8; 
              kf += 2;
            } \
          ' \
  ` \
  "${residFile}" 2 "Rest" 1.000 ff9900 \
  > ${pngFile}

if [[ ( -s ${pngFile} ) && ( "/${make_jpg}" == "/YES") ]]; then
  convert ${pngFile} -quality 85 -resize '600x' ${jpgFile}
  ls -l ${pngFile} ${jpgFile}
  if [[ "/${show_jpg}" == "/YES" ]]; then display ${jpgFile}; fi
fi

  
# rm -fv ${tmp}-rem-*.txt
