#!/bin/bash
# plot statistics from logfile
# Copyright (C) HITACHI,LTD. 2005
# WRITTEN BY HITACHI SYSTEMS DEVELOPMENT LABORATORY,
# Created by M.Hiramatsu <hiramatu@sdl.hitachi.co.jp>
# Updated by H.Kawai <h-kawai@sdl.hitachi.co.jp>

STATFILE=
OUTFILE=

ALL_KEYS=1
DONT_RUN_VIEWER=0
INCR=1
LOGS=
NXT=0
USE_ALIAS=0
WO_MAX=0

trap 'cleanup $?' SIGINT SIGHUP SIGQUIT SIGTERM EXIT

function cleanup()
{
    if [ -f "$PDATA" ]; then
	rm "$PDATA"
    fi
    if [ -f "$SDATA" ]; then
	rm "$SDATA"
    fi
    exit $1
}

function usage()
{
    echo "Usage: lkst_plot_stat [OPTION] <stat_file>"
    echo "OPTION"
    echo "  --log              use log scale for right y axis"
    echo "  --noxtics          don't display xtics and labels"
    echo "  -a                 use alias insted of infokey"
    echo "  -k infokey[,...]]  plot a graph about data indicated by infokeys"
    echo "  -n                 don't run pdf viewer after plotting a graph"
    echo "  -o outfile         output to outfile as pdf format"
    echo "                     (default: <stat_file>.pdf)"
}

function encode_key()
{
    echo "$1" | tr '+-/*.()' '_____\0\0'
}

function mkplotdata()
{
    local i=1
    local j=`expr 1 + $INCR`
    local enc_key
    local ID ALN CNT AVG MAX MIN OTHERS
    read -s NAME
    read -s IK ALN CNT AVG MAX MIN OTHERS
    NAME=`echo $NAME | tr -d " /"` 
    XTICS=
    while read -s IK ALN CNT AVG MAX MIN OTHERS; do
	if [ $USE_ALIAS -ne 0 ]; then
	    IK="$ALN"
	fi

	if [ $ALL_KEYS -eq 0 ]; then
	    enc_key=`encode_key "$IK"`
	    [ "${KEYS[asc_$enc_key]}" != "$IK" ] && continue
	fi
	    
	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 ($IK) Rshow grestore"%" " >> $2
	fi
	i=`expr $i + 1`
    done
    # [ $NXT -ne 0 ] && echo "s/$NAME/$NAME-noxtics/g"
    XENTS=$i

    return `expr $i - 1`
}

function print_plot_max()
{
    if [ $WO_MAX -eq 0 ]; then
	echo -n "\"$PDATA\" using 1:4 axes x1y2 title \"max\" with lines, \\"
    else
	echo -n "\\"
    fi
}

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

OPTS=`getopt -l log,noxtics,inc:,without-max -- ak:no: "$@"`
if [ $? -ne 0 ]; then
    usage
    exit 1
fi

NR_KEYS=0
eval set -- $OPTS
while [ $# -ne 0 ]; do
    case $1 in 
	--log)
	    LOGS="set logscale y2"
	    shift
	    ;;
	--noxtics)
	    NXT=1
	    shift
	    ;;
	--inc)
	    INCR=`echo $2 | tr -d [:alpha:]=`
	    shift 2
	    ;;
	--without-max)
	    WO_MAX=1
	    shift
	    ;;
	-a)
	    USE_ALIAS=1
	    shift
	    ;;
	-k)
	    ALL_KEYS=0
	    for k in `echo "$2" | tr ',' ' '`; do
		let NR_KEYS++
		enc_k=`encode_key "$k"`
		eval asc_$enc_k=$NR_KEYS
		KEYS[asc_$enc_k]="$k"
	    done
	    shift 2
	    ;;
	-n)
	    DONT_RUN_VIEWER=1
	    shift
	    ;;
	-o)
	    OUTFILE=$2
	    shift 2
	    ;;
	--)
	    shift
	    break
	    ;;
	*)
	    exit 1
	    ;;
    esac
done

if [ $# -ne 1 ]; then
    usage
    exit 1
fi

STATFILE="$1"
if [ ! -f $STATFILE ] ;then
    echo "$STATFILE is not found"
    exit 1
fi

[ $INCR -le 0 ] && INCR=1
echo "INCR=$INCR"

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

if [ -z "$OUTFILE" ]; then
    OUTFILE=$STATFILE.pdf
fi

mkplotdata $PDATA $SDATA < $STATFILE
if [ $? -eq 0 ]; then
    echo "error: This log doesn't include any specified keys"
    exit 1
fi

if [ -n "$XTICS" ]; then
    SET_XTICS="set xtics ($XTICS)"
else
    SET_XTICS="unset xtics"
fi

gnuplot << EOF | sed -f $SDATA > $STATFILE.ps
set title "$TITLE"
set xlabel "$NAME" 0,-4
set xrange [0:$XENTS]
set ylabel "counts"
set ytics nomirror
set y2label "sec"
$SET_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, \
`print_plot_max`
     "$PDATA" using 1:5 axes x1y2 title "min" with lines
EOF
rc=$?
if [ $rc -ne 0 ]; then
    exit $rc
fi 

ps2pdf $STATFILE.ps $OUTFILE
rm $STATFILE.ps

if [ $DONT_RUN_VIEWER -eq 0 ]; then
    $VPDF $OUTFILE
fi

exit 0;
