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

LOGFILE=$1
IKNAME=$2
LSTYLE=$3

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 [ $# -lt 2 ] ;then 
echo "lkst_plot_log <log_file> <infokey> [linestyle]"
exit 1;
fi

if [ -z "$LSTYLE" ] ; then
LSTYLE="steps lw 3"
fi

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

function mkplotdata()
{
local IK ALN TM DLT
read -s NAME
read -s IK ALN TM DLT
OTM=
#export NAME=`echo $NAME | tr -d " "` 
XTICS=
while true; do
read -s IK ALN TM DLT
[ -z "$OTM" ] && OTM=$TM
[ -z "$TM" ] && break
[ "$IK" = "$1" ] && echo $IK $ALN `echo $TM - $OTM | bc` $DLT
done
}

TITLE=`head -n 1 $LOGFILE | sed s/analyzer/graph/g`
DTITLE=`head -n 2 $LOGFILE | tail -n 1 | xargs | cut -d\  -f 4 `

PDATA=`mktemp /tmp/tmp$$.XXXXXX`
cat $LOGFILE | mkplotdata $IKNAME | sort -n -k 3 > $PDATA

gnuplot << EOF | sed -e "s/^currentpoint gsave translate 90 rotate 0 0 M/\
currentpoint gsave translate 45 rotate 0 0 M/g" \
-e s@"^($DTITLE) Cshow"@\
"currentpoint gsave translate 45 rotate 0 0 M ($DTITLE) Cshow grestore"@g \
>  $IKNAME.ps
set title "$TITLE"
set xlabel "sec"
set ylabel "$DTITLE"
set key box
#set key top outside
set format x "%f"
set xtics axis rotate
set yrange [] nowriteback
set terminal postscript color
plot "$PDATA" using 3:4 title "$IKNAME" with $LSTYLE
EOF

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

exit 0;
