#! /bin/bash
# Last edited on 2017-05-15 01:25:00 by stolfilocal

set -e

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

# Date range for the MtGOX anomaly:
dmin_part="2016-05-01";   # Min date for detail plot.
dmax_part="2017-05-31";   # Max date for detail plot.

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

show="NO";

trap "exit 1" SIGINT SIGTERM

# Grab the list of price files to smooth:
indexFile="${rundate}-file-index.dir"
ixLines=( \
  ` gawk '/^[ ]*20[01][0-9][-]/ { gsub(/^[ ]+/,"",$0); gsub(/[ ]+$/,"",$0); gsub(/[ ]+/,":",$0); print; }' ${indexFile} ` \
)

for hrad in 00 03 07 14 ; do

  # Make the smoothed price files:
  for ixLine in "${ixLines[@]}" ; do 
    # Split fields from index line:
    ixf=( `echo "${ixLine}" | tr ':' ' '` )
    if [[ ${#ixf[@]} -ne 9 ]]; then echo "** bad index line \"${ixLine}\"" 1>&2; exit 1; fi
    iniDate="${ixf[0]}"
    finDate="${ixf[1]}"
    extag="${ixf[2]}"
    crtag="${ixf[3]}"
    exname="${ixf[4]}"
    rate="${ixf[5]}"

    inFile="${dataDir}/${iniDate}--${finDate}-${extag}-${crtag}-01d.txt"
    
    # Output file prefix for single exchange file:
    outPref="${outDir}/${iniDate}--${finDate}-${extag}-${crtag}-01d-sm${hrad}"

    make_and_plot_smoothed_price.sh \
      "${inFile}" \
      "${extag}" "${crtag}" "${exname}" \
      ${rate} ${hrad} \
      "${outPref}" \
      "${dmin_full}" "${dmax_full}" \
      "${show}"

  done

  # Plot all prices together:
  make_jpeg="YES"
  show_jpeg="NO"
  for prange in \
    "${dmin_full}--${dmax_full}:0.04--2000" \
    "${dmin_part}--${dmax_part}:25.0--2000" \
  ; do
    drange="${prange%%:*}"
    vrange="${prange##*:}"
    dmin="${drange%%--*}"
    dmax="${drange##*--}"
    vmin="${vrange%%--*}"
    vmax="${vrange##*--}"
    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 plots:
    plotPref="${outDir}/${rundate}-01d-sm${hrad}-prices-${dmin}--${dmax}"; # Plot file prefix.
    pngFile="${plotPref}.png"
    jpgFile="${plotPref}.jpg"

    rm -f ${pngFile} ${jpgFile}
    plot_prices.sh \
        "Daily prices ${dmin} to ${dmax}${wintit}" \
        '180' 6  \
        "${dmin}" "${dmax}" \
        ${vmin} ${vmax} \
        "YES" \
        ` cat ${indexFile} \
           | gawk -v dir=${outDir} -v hrad=${hrad} \
               ' /^20/{ printf "%s/%s--%s-%s-%s-01d-sm%s.txt 8 %s %s %s\n", dir,$1,$2,$3,$4,hrad,$5,$6,$9; }'
        ` \
      > ${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
