#! /bin/bash
# Last edited on 2015-02-27 14:39:57 by stolfilocal

# Plots the conversion factors of one or more exchanges from a currency factor file.
# 
# Arguments: {TITLE} {TTICDAYS} {TMTICS} {DMIN} {DMAX} {FMIN} {FMAX} \
#    {LABEL[0]} {SCALE[0] {COLOR[0]} \
#    {LABEL[1]} {SCALE[1] {COLOR[1]} \
#    ... \
#    {LABEL[N-1]} {SCALE[N-1] {COLOR[N-1]} 
# 
# Where 
#   
#   {TITLE} is the plot's title;
#   {TTICDAYS} is the major tic spacing on the X-axis, in days;
#   {TMTICS} is the number of sub-intervals per major time tic interval, defined by minor tics and grid; 
#   {DMIN,DMAX} is the range of dates to plot;
#   {FMIN,FMAX} is the range of currency factors for the vertical scale of the plot; 
#   {LABEL[i]} is the exchange label to show on the plot's key; 
#   {SCALE[i]} is a scale factor to be divided into the relative price; 
#   {COLOR[i]} is the color to use when plotting this exchange.
#  
# The input file (read from {stdin}) must contain one line per day in the 
# format "{DATE} {TIME} | {PRF[i]} | {CCF[i,k]}" where
#   {PRF[i]} is the smoothed reference price assumed for that {DATE},
# the fields "| {CCF[i]}" are repeated for each exchange {k} specified,
# except first one ({K=0}) which is assumed to be the reference price.
# See {compute_currency_factors.gawk} for details.
# 

title="$1"; shift  # Plot title.
tticdays="$1"; shift  # Number of days per tic interval (may be fractional).
tmtics="$1"; shift    # Number of minor tic intervals per major tic interval.
dmin="$1"; shift      # Min date to plot.
dmax="$1"; shift      # Max date to plot.
fmin="$1"; shift      # Min currency factor for plot range.
fmax="$1"; shift      # Max currency factor for plot range.
label=()
scale=()
color=()
i=0;
while [[ $# -gt 1 ]]; do
  label[$i]="$1"; shift # Plot label.
  scale[$i]="$1"; shift # Scale factor.
  color[$i]="$1"; shift # Line color.
  i=$(( $i + 1 ))
done
ncols=$i

show="SHOW"

tmp="/tmp/$$"

dataFile="${tmp}.dat"
gplFile="${tmp}.gpl"
fullplotFile="${tmp}-full.png"
plotFile="${tmp}.png"

# Save the input data:
cat \
  | gawk \
      -v dmin="${dmin}" \
      -v dmax="${dmax}" \
      '/^20[01][0-9]-/ { dt = $1; if ((dt >= dmin) && (dt <= dmax)) { print; } }' \
  > ${dataFile}

# Create the plot command
printf "plot" > ${gplFile}
sep=""

i=0;
while [[ $i -lt $ncols ]]; do
  titlei="${label[$i]}"
  scalei="${scale[$i]}"
  colori="${color[$i]}"
  kprf=4;
  if [[ ${i} -eq 0 ]]; then
    what="1.00"
  else
    kccf=$(( 2 * ${i} + 4 ));
    what="ccf(${kccf},${scalei})"
  fi
  printf "%s "'\\'"\n" "${sep}" >> ${gplFile}
  printf "  \"${dataFile}\" using (tim(1)):(${what}) title \"${titlei}\"" >> ${gplFile}
  printf " with lines lt 1 lw 2.0 lc rgb '#${colori}'" >> ${gplFile}
  sep=","
  i=$(( $i + 1 ))
done
printf "\n" >> ${gplFile}

export GDFONTPATH=.:..

gnuplot <<EOF
set term png size 3000,1500 font "courbd,24"
set output "${fullplotFile}"

# Input time format:
set timefmt "%Y-%m-%d %H:%M:%S"

tticdays = ${tticdays}       # Number of days per time tic interval
tticsecs = 60*60*24*tticdays # Number of seconds per time tic interval
tmtics =  ${tmtics}          # Number of minor time tic intervals per major time tic interval

set xdata time
set xtics tticsecs
set format x "%Y-%m-%d"
set mxtics tmtics

set title "${title}"

# Time (horiz axis):
tim(kcol) = (timecolumn(kcol))

# Currency conversion factor:
ccf(kccf,scale) = (column(kccf) == 0 ? 0/0 : column(kccf)/scale)

fmin = ${fmin}
fmax = ${fmax}

set yrange [fmin:fmax]
set logscale y

if (fmax/fmin > 100) {
set ytics ( \
  0.010,0.020,0.030,0.050,0.070, \
  0.10, 0.20, 0.30, 0.50, 0.70,  \
  1,    2,    3,    5,    7,     \
  10,   20,   30,   50,   70,    \
  100,  200,  300,  500,  700,   \
  1000, 2000, 3000, 5000, 7000   \
)
} else {
if (fmax/fmin > 10) {
set ytics ( \
  0.010,0.012,0.015,0.020,0.025,0.030,0.040,0.050,0.060,0.070,0.080,0.090, \
  0.10, 0.12, 0.15, 0.20, 0.25, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80, 0.90,  \
  1,    1.2,  1.5,  2,    2.5,  3,    4,    5,    6,    7,    8,    9,     \
  10,   12,   15,   20,   25,   30,   40,   50,   60,   70,   80,   90,    \
  100,  120,  150,  200,  250,  300,  400,  500,  600,  700,  800,  900,   \
  1000, 1200, 1500, 2000, 2500, 3000, 4000, 5000, 6000, 7000, 8000, 9000   \
)
} else {
set ytics ( \
  0.010,0.011,0.012,0.015,0.020,0.025,0.030,0.035,0.040,0.045,0.050,0.055,0.060,0.065,0.070,0.075,0.080,0.085,0.090,0.095, \
  0.10, 0.11, 0.12, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95,  \
  1,    1.1,  1.2,  1.5,  2,    2.5,  3,    3.5,  4,    4.5,  5,    5.5,  6,    6.5,  7,    7.5,  8,    8.5,  9,    9.5,   \
  10,   11,   12,   15,   20,   25,   30,   35,   40,   45,   50,   55,   60,   65,   70,   75,   80,   85,   90,   95,    \
  100,  110,  120,  150,  200,  250,  300,  350,  400,  450,  500,  550,  600,  650,  700,  750,  800,  850,  900,  950,   \
  1000, 1100, 1200, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 5500, 6000, 6500, 7000, 7500, 8000, 8500, 9000, 9500   \
)
}
}
set grid xtics  lt 1 lw 3 lc rgb '#ffddaa', lt 1 lw 2 lc rgb '#ffddaa'
set grid mxtics
set grid ytics  lt 1 lw 3 lc rgb '#ffddaa', lt 1 lw 2 lc rgb '#ffddaa'

set xzeroaxis lt 1 lw 3 lc rgb '#ffddaa'
set key left top

load "${gplFile}"
quit
EOF

if [[ -s ${fullplotFile} ]]; then 
  convert ${fullplotFile} -resize '50%' ${plotFile}
  if [[ "/${show}" == "/SHOW" ]]; then display ${plotFile}; fi
  cat ${plotFile}
fi

rm -fv ${tmp}{-*,}.*
    
        
