#! /bin/bash -f
# Last edited on 2015-07-19 15:29:56 by stolfilocal

title="$1"; shift    # Plot title.
fdate="$1"; shift    # Second date in file names.
pinidate="$1"; shift # First date to plot.
pfindate="$1"; shift # Last date to plot.

show="SHOW"

infile="txt-der/2009-01-03--${fdate}-mywallet-new-users.txt"

tmp="/tmp/$$"
pngfull="${tmp}-full.png"
pngout="out/2009-01-03--${fdate}-mywallet-new-users.png"
jpgout="out/2009-01-03--${fdate}-mywallet-new-users-x600.jpg"
rm -f ${pngfull} ${pngout} 

export GDFONTPATH=.

gnuplot <<EOF
set term png size 2400,1800 font "courbd,18"
set output "${pngfull}"
set title "${title}" 

# Time format for {timecolumn}
timeformat = "%Y-%m-%d %H:%M:%S"

# Minor tics in weeks, major tics in {tweeks} weeks:
weeksecs = 7 * 24 * 60 * 60
nweeks = 12 # Tic mark spacing (weeks).

xtimefmt = "%Y-%m-%d" # Format for X-axis labels.
pinisecs = strptime(xtimefmt, "${pinidate}")
pfinsecs = strptime(xtimefmt, "${pfindate}")
set xrange [(pinisecs):(pfinsecs)]
k = 0
xtime = pinisecs
unset xtics 
unset mxtics 
set xtics ( 0 )
while (xtime <= pfinsecs) {
    minor = ((k % nweeks) != 0)
    set xtics add ( strftime(xtimefmt, xtime) xtime minor )
    k = k + 1
    xtime = xtime + weeksecs
}
set grid xtics lt 1 lw 3 lc rgb '#ffddaa', lt 1 lw 1.5 lc rgb '#ffddaa'

set yrange [-10:12000]
set ytics 1000
set mytics 5
set grid ytics lt 1 lw 3 lc rgb '#ffddaa', lt 1 lw 1.5 lc rgb '#ffddaa'

set key left

# Converts date and time columns to time in seconds:
tcol(k) = strptime(timeformat,(strcol(k).' '.strcol(k+1)))

#dxlabel = 5*24*60*60
dxlabel = 0
dylabel = -0.30

plot "${infile}" using (tcol(1)):3 title "new users" with linespoints pt 7

EOF

if [[ -s ${pngfull} ]]; then 
  convert ${pngfull} -resize '50%' ${pngout}
  if [[ "/${show}" == "/SHOW" ]]; then
    display ${pngout}
  fi
  convert ${pngfull} -resize '600x' ${jpgout}
fi

rm -f ${tmp}-* ${tmp}.*
