#! /bin/bash
# Last edited on 2019-10-28 04:30:09 by jstolfi

set -e

rundate="$1"; shift;       # Nominal date of analysis
dmin_full="$1"; shift;     # Min date for plot.
dmax_full="$1"; shift;     # Max date for plot.

# Date range for the transition region:
dmin_part="2012-04-01";   # Min date for detail plot.
dmax_part="2013-03-31";   # Max date for detail plot.

show="YES"
show_jpg="NO"

dataDir="../00-DATA/series/fix"
outDir="out"

indexFile="${rundate}-file-index.dir"
refPref="${outDir}/${rundate}-refprice-01d"

if [[ ! ( -s ${indexFile} ) ]]; then
  echo "**file ${indexFile} not found" 1>&2; exit 1
fi

refFile="${refPref}.txt"
export TZ="UTC"; \
compute_ref_price.gawk \
    -f useful_functions.gawk \
    -f index_file_functions.gawk \
    -v indexFile="${indexFile}" \
    -v inDir="${dataDir}" \
  | txtable-reformat \
  > ${refFile}
ls -l ${refFile}

#Plot the two prices and the ref price, in two scales:
make_jpeg="YES"
show_jpeg="NO"
for prange in \
  "${dmin_full}--${dmax_full}:0.039--24000" \
  "${dmin_part}--${dmax_part}:2.8--320" \
; do
  drange="${prange%%:*}"
  vrange="${prange##*:}"
  dmin="${drange%%--*}"
  dmax="${drange##*--}"
  vmin="${vrange%%--*}"
  vmax="${vrange##*--}"

  # Plot file names:
  plotPref="${refPref}-${dmin}--${dmax}"
  pngFile="${plotPref}.png"
  jpgFile="${plotPref}.jpg"

  rm -f ${pngFile} ${jpgFile}
  plot_prices.sh \
      "Reference price - ${dmin} to ${dmax}" \
      '180' 6  \
      "${dmin}" "${dmax}" \
      ${vmin} ${vmax} \
      ${show} \
      `cat ${indexFile} | gawk -v dir=${dataDir} '/^20/{ printf "%s/%s--%s-%s-%s-01d.txt 16 %s %s %s\n", dir,$1,$2,$3,$4,$5,$6,$9; }' ` \
      "${refFile}" 16 "Reference" 1.000 778899 \
    > ${pngFile}
  if [[ ( -s ${pngFile} ) && ( "/${make_jpeg}" == "/YES" ) ]]; then
    convert ${pngFile} -quality 85 -resize '600x' ${jpgFile}
    ls -l ${pngFile} ${jpgFile}
    if [[ "/${show_jpg}" == "/YES" ]]; then display ${jpgFile}; fi
  fi

done
