#! /bin/bash
# Last edited on 2019-10-28 00:01:14 by jstolfi

# Usage: 
#   cleanup_bitcoincharts_data.sh {EX} {CR} [ {RAWFILE} ]
# where {EX} is the 4-letter exchange code, {CR} is the 3-letter currency code,
# and {RAWFILE} is a file of  raw trade data obtained from http://bitcoincharts.com/charts/.
# If {RAWFILE} is omitted, reads from standard input.
# Writes to stdout the contents of {RAWFILE} reformatted as a nice table

function acheck(){
  name="$1"; shift;
  arg="$1"; shift;
  if [[ "/${arg}" == "/" ]]; then 
    echo "** must provide {${name}}" 1>&2 ; exit 1
  fi
}

ex="$1"; shift; acheck ex "$ex"
cr="$1"; shift; acheck cr "$cr"
if [[ $# -gt 0 ]]; then rawfile="$1"; shift; else rawfile=""; fi

( \
  printf '# Last edited on DATE TIME by USER\n' ; \
  printf '# Exchange '"${ex}"' ('"${cr}"' per BTC)\n'  ; \
  printf 'Timestamp ! Open ! High ! Low ! Close ! V.BTC ! V.'"${cr}"' ! WTPrice\n'  ; \
  cat ${rawfile} \
   | egrep -e '^[ ]*20[0-9][0-9]-[0-9][0-9]-[0-9][0-9][ ][ ]*[0-9][0-9]:' \
   | tr '\011' '|' \
   | sed \
       -e 's:1[.]7e[+]308:0:g' \
       -e 's:Infinity:0:g' \
) | txtable-reformat 
