#! /bin/bash
# Last edited on 2015-02-27 23:35:52 by stolfilocal

rundate="$1"; shift; # Nominal date of analysis

dmin_full="2010-06-20" # Start date for full plot.
dmax_full="2015-03-10" # End date for full plot.

dmin_part="2012-11-20" # Start date for detail plot.
dmax_part="2014-03-10" # End date for detail plot.

mergeDir="../merged-price"

indexFile="${mergeDir}/${rundate}-file-index.dir"

for hrad in 14 07 03 00 ; do

  joinFile="${mergeDir}/out/${rundate}-prices-01d-sm${hrad}.txt"

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

  ccfFile="${outPref}.txt"

  echo "creating ${ccfFile} ..." 1>&2

  export TZ="UTC"; \
  compute_currency_factors.gawk \
      -f useful_functions.gawk \
      -f index_file_functions.gawk \
      -v indexFile=${indexFile} \
    < ${joinFile} \
    > ${ccfFile}
  ls -l ${ccfFile}

  echo "plotting ${ccfFile} ..." 1>&2

  make_jpeg="YES"
  show_jpeg="NO"

  for prange in \
    "${dmin_full}--${dmax_full}:180x6" \
    "${dmin_part}--${dmax_part}:60x6" \
  ; do
    drange="${prange%%:*}"
    trange="${prange##*:}"
    dmin="${drange%%--*}"
    dmax="${drange##*--}"
    tticdays="${trange%%x*}"
    tmtics="${trange##*x}"
    vmin="0.800"
    vmax=`echo "1.250 + 0.80/(${hrad}+1)" | bc -lq`
    echo "vmax = ${vmax}" 1>&2
    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

    # File names for joint price plots:
    plotPref="${outPref}-${dmin}--${dmax}"; # Plot file prefix.
    pngFile="${plotPref}.png"
    jpgFile="${plotPref}.jpg"

    plot_currency_factors.sh \
        "Relative prices - ${dmin} to ${dmax}${wintit}" \
        "${tticdays}" "${tmtics}"  \
        ${dmin} ${dmax} \
        ${vmin} ${vmax} \
        ` gawk '/^[ ]*20[01][0-9][-]/ { print $5,$6,$9; }' ${indexFile} ` \
      < ${ccfFile} \
      > ${pngFile}

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

  done

done
