#! /bin/sh
#
# (C) 2002-2003 Intel Corporation
# Iaky Prez-Gonzlez <inaky.perez-gonzalez@intel.com>
#
# Distributed under the FSF's GNU Public License v2 or later.
#
# Plot the output of priority inheritance tests.

# Modifs by Sebastien Decugis:
# -> plots linespoints instead of dots
# -> legend is outside the graph.
# -> Change axis names and graph title

FILE=$1
TMP=$(mktemp -d)

function clean_up
{
    rm -rf $TMP
}

function error
{
    cat 1>&2
    clean_up
    exit 1
}

trap clean_up EXIT

if ! cols=$(grep "#[ ]*COLUMNS" $FILE)
then
    error <<EOF
E: $FILE: Cannot locate the COLUMNS descriptor
EOF
fi
cols=$(echo $cols | sed 's/#//')
columns=$(echo $cols | awk '{print $2;}')
count=1
while [ $count -le $columns ]
do
  column[$count]=$(echo $cols | awk -vcount=$count '{print $(2 + count);}')
  if [ -z "${column[$count]}" ]
      then
      column[$count]=$count;
  fi
  count=$(($count + 1))
done

# Set up the plot area
count=2
with="with linespoints"
cat > $TMP/gnuplot.script <<EOF
set term png
set output "pthread_cond_timedwait.png"
set xlabel "${column[1]}"
set ylabel "Latency (s)"
set key below
set title "pthread_cond_timedwait scalability"
EOF

# Plot the events
height=15
grep "#[ ]*EVENT" $FILE | sed 's/#//' > $TMP/events
events=$(cat $TMP/events | wc -l)
if [ $events -gt 0 ]
then
    step=$(((100 - $height) / $events))
    if [ $step -lt 5 ]
        then
        step=5;
    fi
    cat $TMP/events | while read event x text
      do
      if ! [ $event = "EVENT" ]
          then
          cat 1>&2 <<EOF
E: Unknown event type "$event", ignoring
EOF
          continue;
      fi
      height_text=$(($height + 2))
      echo "set arrow from $x, graph 0 to $x, graph 0.$height" >> $TMP/gnuplot.script
      echo "set label \"$text\" at $x, graph 0.$height_text center" >> $TMP/gnuplot.script
      height=$(($height + $step))
    done
fi

# Plot the data
plot_cmd="plot '$FILE' using 1:2 title \"${column[$count]}\" $with"
count=3
while [ $count -le $columns ]
do
	plot_cmd=$plot_cmd",'$FILE' using 1:$count title \"${column[$count]}\" $with"
	count=$(($count + 1))
done

echo $plot_cmd >> $TMP/gnuplot.script

#cp $TMP/gnuplot.script .
cat $TMP/gnuplot.script | gnuplot
rm -rf $TMP
