#!/bin/bash

set -ue

source tools/config.sh

TMPFILE="/dev/shm/plot-timing.tmp"
IMAGE="timing.png"

if [ $# == 1 ]
then
	sequence=$1
else
	sequence="escadrille"
fi

# echo "plot timing $sequence" >> WS/log

grep $sequence WS/mp4.timing | tail -3600 | awk 		\
				-v nbframes=$NBFRAMES		\
'								\
BEGIN	{							\
	# print "nb frames = ", nbframes;			\
	for (foo=0; foo<nbframes; foo++) {			\
		mini[foo]  = 666;				\
		maxi[foo]  = -42;				\
		count[foo] = 0;					\
		}						\
	}							\

# for every line						\
	{							\
	accu[$2] += $3;						\
	count[$2]++;						\
	if (mini[$2] > $3)	mini[$2] = $3;			\
	if (maxi[$2] < $3)	maxi[$2] = $3;
	last[$2] = $3					\
	}							\
								\
END	{							\
	for (foo=0; foo<nbframes; foo++) {			\
		if (count[foo] > 0) {				\
			mean = accu[foo] / count[foo];		\
			printf "%4d %4f %4d %4d %4d\n",
				foo, mean,
				mini[foo], maxi[foo],
				last[foo];
			}					\
		}						\
	}							\
' > $TMPFILE

# head $TMPFILE   ; exit

gnuplot	<< __EOC__
	set term png size $Img_Width,$Img_Height
	set output "timing.png"
	set grid
	set xrange [:360]
	set yrange [0:]
	set title "Séquence '${sequence}'"
	set xlabel "numéro de la trame"
	set ylabel "temps en secondes"
	plot "/dev/shm/plot-timing.tmp" u 1:4 w l 		\
				lc "#ff0000" t "maximum",	\
	     "/dev/shm/plot-timing.tmp" u 1:3 w l		\
				lc "#0000ff" t "minimum",	\
	     "/dev/shm/plot-timing.tmp" u 1:2 w l		\
				lc "#00aa00" t "moyenne",	\
	     "/dev/shm/plot-timing.tmp" u 1:5 w l		\
				lc "#000000" t "last"
__EOC__

convert -negate -level -33% $IMAGE WS/negatif.png