#!/bin/bash
# plot histgram from logscale distribution
# Copyright (C) HITACHI,LTD. 2005
# WRITTEN BY HITACHI SYSTEMS DEVELOPMENT LABORATORY,
# Created by M.Hiramatsu <hiramatu@sdl.hitachi.co.jp>


DISTFILE=$1
NAME=$2

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 [ $# -ne 2 ] ;then 
echo "lkst_plot_dist <log_file> <aliasname>"
exit 1;
fi

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

TITLE=`head -n 1 $DISTFILE | sed s/analyzer/distribution-graph/g`

PDATA=`mktemp /tmp/tmp$$.XXXXXX`
echo -n "# " > $PDATA
i=2
while true; do
 STR1=`head -n 2 $DISTFILE | tail -n 1 | xargs | cut -d\  -f $i`
 STR2=`grep " $NAME " $DISTFILE | xargs | cut -d\  -f $i`
 if [ -z "$STR2" ]; then
  if [ "$STR1" ]; then
	echo "error : This log is not including $NAME data"
	exit 0;
  fi
  break;
 fi
 if [ "$STR1" = "less-than-min" -o "$STR1" = "more-than-max" ]; then
  echo -n "# " >> $PDATA
 fi
 echo $STR1 $STR2 >> $PDATA
 i=`expr $i + 1`
done

gnuplot << EOF > $NAME.ps
set title "$TITLE"
set logscale x
set xlabel "sec"
set ylabel "count"
set key box
set terminal postscript color
plot "$PDATA" using 1:2 title "$NAME" with steps
EOF

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

exit 0;
