#! /bin/bash
# Last edited on 2017-05-14 04:05:15 by stolfilocal
# plots number of transaction outputs per day, separated by size range.

hrad="$1"; shift;      # Radius of price smoothing window.
rel="$1"; shift;       # 0 for absolute counts, 1 for relative ones.
dmin="$1"; shift;      # Min date for plot.
dmax="$1"; shift;      # Max date for plot.
inFile="$1"; shift;    # Filename with transaction outputs per day and BTC range.
priceFile="$1"; shift; # Filename with BTC prices per day, or "NONE".

make_jpg="YES"
show_jpg="NO"

loValBTC=( "0.0" "0.0001" "0.001" "0.01" "0.1" "1" "10" "100" "1000" )
loValUSD=( "0.0" "0.01" "0.10" "1" "10" "100" "1000" "10000" "100000" )

if [[ "/${priceFile}" == "/NONE" ]]; then
  # Ranges in BTC
  loVal=( "${loValBTC[@]}" )
  cr="BTC"
else
  # Ranges in USD
  loVal=( "${loValUSD[@]}" )
  cr="USD"
fi
nranges=${#loVal[@]}

show="SHOW"

trap "exit 1" SIGINT SIGTERM

outDir="out"
outPref="${outDir}/txos-01d-sm${hrad}-BTC"
outFile="${outPref}.txt"

tmp="/tmp/$$"

# Smooth out the data file:
echo "smoothing the input data..." 1>&2
cumFile="${tmp}.dat"
smooth_txos_per_day.gawk \
    -f useful_functions.gawk \
    -f smoothed_price_file_functions.gawk \
    -v inFile="${inFile}" \
    -v priceFile="${priceFile}" \
    -v hrad="${hrad}" \
    -v loValsBTC="${loValBTC[*]}" \
    -v loValsUSD="${loValUSD[*]}" \
  > ${outFile}

# Change from per-range to cumulative:
echo "computing cumulative counts..." 1>&2
cat ${outFile} \
  | gawk \
      -v FS='|' \
      -v rel=${rel} \
      -v nranges=${nranges} \
      ' /^[ ]*([\#]|$)/ { next; }
        /[!]/ { next; }
        /^[-+ ]+$/ { next; }
        /^[ ]*20[0-9][0-9][-]/ {
          dy = $1;
          S = 0; split("", cum); nc = 0;
          for (ir = NF; ir >= 2; ir--) { 
            X=rmb($(ir)); 
            if (X == "") { X = "nan"; } 
            S += X;
            cum[nc] = S; nc++;
          }
          if (nc != nranges) 
            { printf "** error: {nc = %s} [%s]\n", nc, $0 > "/dev/stderr"; exit(1); } 
          if (S == 0) { S = 1.0e-30; }
          printf "%s ", dy;
          for (k = 0; k < nc; k++) {
            if (rel) {
              printf " %8.6f", cum[k]/S;
            } else {
              printf " %.2f", cum[k]; 
            }
          } 
          printf "\n"; next;
        } 
        // { printf "** error: format [%s]\n", $0 > "/dev/stderr"; exit(1); } 
        function rmb(x){ gsub(/^[ ]+/,"",x); gsub(/[ ]*$/,"",x); return x; }
      ' \
   > ${cumFile}
   
# Define smoothing part of title
echo "defining the smoothing title..." 1>&2
if [[ ${hrad} -gt 0 ]]; then
  smtit=" - smoothed with $(( ${hrad} * 2 + 1 ))-day Hann window" 
else
  smtit=""
fi

# Select the Y range
if [[ ${rel} -ne 0 ]]; then
  # Percentages:
  yrange="[-0.000001:+1.000001]"
else
  # Absolute counts:
  yrange="[-5:]"
fi

# Create the plot statements file
echo "creating the plot statement file..." 1>&2
gplFile="${tmp}.gpl"
color=( '#0022ff' '#ff0000' '#008800' '#8800dd' '#dd4400' '#0066ff' )
ncolors=${#color[@]}

sep=""
printf "plot" > ${gplFile}
ir=$(( ${nranges} - 1 )); # Cumulative range index.
iv=3; # Column of cumulative data file.
ic=0; # Color counter.
while [[ ${ir} -ge 0 ]]; do
  loVali=${loVal[$ir]}
  if [[ ${ic} -ge ${ncolors} ]]; then ic=0; fi
  colori="${color[$ic]}"
  titlei=">= ${loVali} ${cr}"
  echo "  column ${iv} ranges ${ir}..$(( ${nranges} - 1 )): \"${titlei}\"" 1>&2
  printf "%s \\\\\\n" "${sep}" >> ${gplFile}
  printf "  \"${cumFile}\" using (tim(1)):${iv} title \"${titlei}\"" >> ${gplFile}
  printf " with linespoints pt 7 ps 0.75 lt 1 lw 1.0 lc rgb '${colori}'" >> ${gplFile}
  ir=$(( ${ir} - 1 ))
  iv=$(( ${iv} + 1 ))
  ic=$(( ${ic} + 1 ))
  sep=", "
done
printf "\n" >> ${gplFile}

# Plotting:
echo "plotting..." 1>&2

pngFileFull="${tmp}-full.png"

imgPref="${outPref}-${dmin}--${dmax}"
pngFile="${imgPref}.png"
jpgFile="${imgPref}.jpg"

rm -f ${pngFileFull} ${pngFile} ${jpgFile}

export GDFONTPATH=.:..:../..

gnuplot <<EOF
set term png size 2400,1000 font "courbd,24"
set output "${pngFileFull}"

set key top left reverse invert Left

# Input time format:
set timefmt "%d-%b-%y"

set title "Transaction Outputs per day and ${cr} range${smtit}"

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

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

ttics = 48 # Time between major tics (weeks)
set xdata time
set format x "%Y-%m-%d"
set xtics ttics*7*24*3600
set mxtics ttics/4
set grid xtics lt 1 lw 3 lc rgb '#ffddaa', lt 1 lw 1.5 lc rgb '#ffddaa'
set grid mxtics

set yrange ${yrange}
set grid ytics lt 1 lw 3 lc rgb '#ffddaa', lt 1 lw 1.5 lc rgb '#ffddaa'
set mytics 2
set grid mytics

load "${gplFile}"

quit
EOF

if [[ -s ${pngFileFull} ]]; then
  convert ${pngFileFull} -resize '50%' ${pngFile}
  if [[ "/${show}" == "/SHOW" ]]; then
    display ${pngFile}
  fi
  if [[ "/${make_jpg}" == "/YES" ]]; then
    convert ${pngFile} -resize '600x' ${jpgFile}
    if [[ "/${show_jpg}" == "/YES" ]]; then
      display ${jpgFile}
    fi
  fi
fi

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