#!/bin/bash
# plot statistics from logfile

LOGFILE=$1
shift 1
OPTS=$*

if [ "$PDF_VIEWER" ] ; then
  VPDF=$PDF_VIEWER
else
  VPDF=`which acroread 2> /dev/null`;
  if [ -z "$VPDF" ]; then
   VPDF=`which xpdf 2> /dev/null`;
  fi
  if [ -z "$VPDF" ]; then
   VPDF=`which gpdf 2> /dev/null`;
  fi
  if [ -z "$VPDF" ]; then
   VPDF=echo
  fi
fi

if [ $# -gt 2 ] ;then 
echo "lkst_plot_stat <stat_file> [format-options]"
exit 1;
fi

if [ ! -f $LOGFILE ] ;then
echo "$LOGFILE is not found"
exit 1;
fi
#options 
LOGS=
NXT=0
INCR=1
if [ "$OPTS" ]; then
for i in $OPTS ; do
case $i in 
	log) 
	LOGS="set logscale y2"
	;;
	noxtics)
	NXT=1
	;;
	inc=*)
	INCR=`echo $i|tr -d [:alpha:]=`
esac
done
fi
[ $INCR -le 0 ] && INCR=1
echo $INCR

function mkplotdata()
{
local i=1
local j=`expr 1 + $INCR`
local ID ALN CNT AVG MAX MIN
read -s NAME
read -s ID ALN CNT AVG MAX MIN
NAME=`echo $NAME | tr -d " /"` 
XTICS=
while true; do
read -s ID ALN CNT AVG MAX MIN
[ -z "$ID" ] && break;
echo $i $CNT $AVG $MAX $MIN >> $1
if [ $NXT -eq 0 ];then
if [ "$XTICS" ] ;then
[ $i -eq $j ] && XTICS="$XTICS, \"@$i@\" $i" && j=`expr $i + $INCR`
else
XTICS="\"@$i@\" $i"
fi
echo s%"^(@$i@) Cshow"%\
"currentpoint gsave translate 45 rotate 0 0 M ($ALN) Rshow grestore"%" " >> $2
fi
i=`expr $i + 1`
done
[ $NXT -ne 0 ] && echo "s/$NAME/$NAME-noxtics/g"
XENTS=$i
}

PDATA=`mktemp /tmp/tmp$$.XXXXXX`
SDATA=`mktemp /tmp/tmp$$.XXXXXX`
TITLE=`head -n 1 $LOGFILE | sed s/analyzer/statistics-graph/g`

mkplotdata $PDATA $SDATA < $LOGFILE

gnuplot << EOF | sed -f $SDATA > $NAME.ps
set title "$TITLE"
set xlabel "$NAME" 0,-4
set xrange [0:$XENTS]
set ylabel "counts"
set y2label "sec"
set xtics ($XTICS)
set y2tics
$LOGS
set key box
#set key outside
set terminal postscript color
plot "$PDATA" using 1:2 title "count" with boxes,\
     "$PDATA" using 1:3 axes x1y2 title "average" with lines, \
     "$PDATA" using 1:4 axes x1y2 title "max" with lines, \
     "$PDATA" using 1:5 axes x1y2 title "min" with lines
EOF

rm $PDATA
rm $SDATA
ps2pdf $NAME.ps
$VPDF $NAME.pdf


exit 0;
