#!/bin/bash

. ./functions

STATDIR=$PWD/stat
mkdir -p $STATDIR

ccs="`cd results; ls | sed 's,.*_\(.*\)-.*,\1,' | sort -u`"

for t in bt rt size ; do
  benchs="`cd results; ls *-$t | cut -d _ -f 1 | sort -u`"

  # generate data files
  (
  echo -n ""
  for b in $benchs ; do
	[[ $b = linux*  ]] && continue
	echo -n "$b"
	ref=""
	for cc in $ccs ; do
		v="`tail -n 1 results/${b}_${cc}-$t`"
		if [ "$v" ] ; then
		  v="0$v" # 0 prefix as ploticus can not cope without it
		  [ "$ref" ] || ref=$v
		else
		  v=0
		fi
		perc="`echo "scale=5; ( $v * 100 ) / $ref" | bc`"
		echo -ne "\t$perc"
	done
	echo ""
  done
  ) > $STATDIR/stat-$t.csv # | sort -n -k +6

  # generate ploticus files
  (
  case $t in
	rt)
		title="Runtime"
		;;
	bt)
		title="Buildtime"
		;;
	size)
		title="Binary size"
		;;
  esac

  i=1
  n=0
  datafields=""
  for cc in $ccs ; do
	: $(( i++ ))
	: $(( n++ ))
	var_append datafields "," "$i"
  done

  cat <<-EOT
#proc getdata
file: stat-$t.csv
delimit: tab

#proc areadef
title: $title
rectangle: 1 1 8.5 4
xscaletype: categories
xcategories: datafield=1
catcompmethod: exact
#xautorange: datafield=1 nearest=10 lowfix=0
#yrange: 80 120
yautorange: datafield=$datafields nearest=10

#proc xaxis
#label: Package
stubs: inc
stubvert: yes
stubcull: yes
stubs: usecategories
grid: color=gray(0.8) width=0.8

#proc yaxis
label: $title in %
stubs: inc 10
grid: color=gray(0.8) width=0.8

EOT

  i=0
  for cc in $ccs ; do
        : $(( i++ ))

	# match the color
	color="`egrep -m1 "^$cc[^-]" stat.color | cut -f 2`"
	if [ ! "$color" ] ; then
		# ok - no exact match be more relaxed
		tcc=`echo $cc | sed 's/[^-]*$//'`
		if [[ $cc =~ .*-.* ]]; then
			tcc=${i%-*}-
			color="`egrep -m1 "^$tcc[^-]" stat.color | cut -f 2`"
		fi
		[ "$color" ] || color="gray(0.3)"
	fi
	#echo "$cc: color: $color" 1>&2

	cat <<-EOT
#proc bars
//xfield: $((i+1))
cluster: $i / $n
lenfield: $((i+1))
color: $color
barwidth: 0.06
legendlabel: $cc

EOT
  done

  cat <<-EOT
#proc legend
seglen 0.1
location: min+0.25 max-0.25
EOT
  ) > $STATDIR/stat-$t.ploticus
done

if [ $(type -p ploticus) ]; then
	PLBIN=ploticus
elif pl -version 2>&1 | grep -q ploticus; then
	PLBIN=pl
else
	echo ERROR: ploticus not found
	exit 1
fi
pushd $STATDIR > /dev/null
for t in bt rt size; do
	echo "Rendering -$t graph ..."
	$PLBIN -png -o stat-$t.png stat-$t.ploticus
done
popd > /dev/null
