#!/bin/bash
#
# This (ugly) script calculate the average of power consumption.
# return: simple HTML table code.
#
# logfiles have to be named:
#
# <log file> <- consumption_report_54321     (test system log - devicedown.sh)
# and		consumption_report_54321.log (measurement log - QtDMM or equal)

if [ -z "$1" ]; then
	echo -e "usage: $0 <log file>";
	exit -1;
fi

DATAFILE="$1.log";
LOGFILE="$1";

# Internal File Separator (man bash) set only with \n
IFS="
";

# sum total and calculate average of the first 40 seconds 
# in the first 40 seconds all devices are in D0
SUM=0;
for value in `tail -n 40 $DATAFILE | awk '{print $3}'`; do
	SUM=`echo "$SUM + $value" | bc`;
done;

IDLE=$(echo "scale=5; $SUM / 40" | bc);

# generate HTML output
echo '<table style="font-size: small;" border="1">';
echo "<tr><td>Device:</td><td>consumption [A]</td><td>profit [A]</td></tr>";
echo "<tr><td>idle (all devices in DO)</td><td>$IDLE</td><td>.0</td></tr>";

# read the log - line by line
for m in `cat $LOGFILE`; do
	

	if [ "$( echo $m | grep "changed to D3")" ]; then
		# set time
		TIME_DOWN=$( echo $m | awk '{print $1}');
		COUNT=0;
		SUM=0;

		# name of device
		echo -n "<tr><td>$( echo $m  | cut -c 11- | rev | cut -c 16- | rev)</td>"; 

		# ugly code :(
		# read the whole measurement log file - line by line
		for n in `cat $DATAFILE`; do
			#  set current time and value
			TIME=$( echo $n | awk '{print $2}');
			VALUE=$( echo $n | awk '{print $3}');

			# we start average calculation after 10seconds
			# and use the following 40seconds settings.
			if [ "$TIME" = "$TIME_DOWN" ]; then
				COUNT=1;
			fi;
			
			# counting...
			if [ "$COUNT" -gt 0 ]; then
				COUNT=$( expr $COUNT + 1 );
			fi;

			# begin calculation after 10sec and end after 40sec
			if [ "$COUNT" -gt "10" -a "$COUNT" -lt "50" ]; then
				SUM=`echo "$SUM + $VALUE" | bc`;
			fi;

			if [ "$COUNT" -gt "50" ]; then
				break;
			fi;
			
				 
		done;

		# calculation of average and profit
		# and print HTML output
		echo -n "<td>$(echo "scale=5; $SUM / 40" | bc)</td>";
		echo "<td>$(echo "scale=5; $IDLE - ($SUM / 40)" | bc)</td></tr>";
		TIME_DOWN="";
	fi;
	
done;
echo "</table>";


exit 1;
