#!/bin/sh

LOGFILE="./ca-ga.log"

# you want to see skips of dna, say "skips," not skips, or it will double up the samples because
# the log also says "neural skips of dna", which refers to jmps of the dna IP by the neural net,
# not to stuns which is what skips or in this case "skips," refers to, skipped turns, anyway my bad

if [ "" == "$1" ]; then echo 'Usage: ./plot-ca-ga-log.sh [bites|gives|pokes|skips|nops|kills|breeds|splits|"high score"|"lost fights"|"won fights"|"max ip"|...] [vs [bites|gives|pokes|...]]'; echo; echo 'NOTE: Uses ca-ga.log if one exists. Run ca-ga as "./ca-ga | tee ca-ga.log" to produce it. Depending on your tee you might not see output in your terminal or the file until a few updates have passed. This is normal'; exit; fi

#PERLCOND='if $x>5; $x=6 if $x>5; $x++;' # any extra perl code for processing etc (this removes half the datapoints for example)

if [ "vs" == "$2" ]
	then echo "Plotting $1 vs $3 (ratio) from ca-ga.log"

#	grep -vi 'segfault' /root/c/ca-ga-ann/ca-ga.log >/mnt/rd/11 # temp (Debug output in binary)

	if echo $1 | grep -i 'max ip' || echo $1 | grep -i 'high score' || echo $1 | grep -i 'highest was'|| echo $1 | grep -i 'lowest is' || echo $1 | grep -i 'average'; then
		grep -ai "$1" $LOGFILE | perl -ne "/$1 ([0-9.-]+)/i; print \$1.\"\n\" $PERLCOND" > plottemp.data.2
	else
		grep -ai "$1" $LOGFILE | perl -ne "/([0-9.-]+) $1/i; print \$1.\"\n\" $PERLCOND" > plottemp.data.2
	fi
	
	if echo $3 | grep -i 'max ip' || echo $3 | grep -i 'high score' || echo $3 | grep -i 'highest was'|| echo $3 | grep -i 'lowest is' || echo $3 | grep -i 'average'; then
		grep -ai "$3" $LOGFILE | perl -ne "/$3 ([0-9.-]+)/i; print \$1.\"\n\" $PERLCOND" > plottemp.data.1
	else
		grep -ai "$3" $LOGFILE | perl -ne "/([0-9.-]+) $3/i; print \$1.\"\n\" $PERLCOND" > plottemp.data.1
	fi
	
	cat plottemp.data.1 | perl -e 'open(F,"plottemp.data.2"); while(<F>){ $x = $_; $y = <STDIN>; chomp $x; chomp $y; print "".($x/$y)."\n" if $x ne "" and $y ne "" and $y>0}' > plottemp.data

	rm plottemp.data.1
	rm plottemp.data.2
	
	YLABEL="$1 per $3"
else
	echo "Plotting reported $1 in $LOGFILE"
	
#	grep -vi 'segfault' /root/c/ca-ga-ann/ca-ga.log >/mnt/rd/11 # temp (Debug output in binary)

	if echo $1 | grep -i 'max ip' || echo $1 | grep -i 'high score' || echo $1 | grep -i 'highest was'|| echo $1 | grep -i 'lowest is' || echo $1 | grep -i 'average'; then
		grep -ai "$1" $LOGFILE | perl -e " while(<>){/$1 ([0-9.-]+)/i; print \$1.\"\n\" $PERLCOND}" > plottemp.data
	else
		grep -ai "$1" $LOGFILE | perl -e " while(<>){/([0-9.-]+) $1/i; print \$1.\"\n\" $PERLCOND}" > plottemp.data
	fi
	YLABEL="Incidents"
fi

echo `wc -l plottemp.data|cut -d " " -f 1 | xargs` records

cat > plottemp2 << EOF
set output "plottemp.png"
set title "$LOGFILE $1 $2 $3 graph"
set xlabel "Update (s)"
set ylabel "$YLABEL"
set grid
set term png
plot "plottemp.data" title ""
EOF

gnuplot < plottemp2
rm plottemp2
echo "Viewing $PWD/tempplot.png with xv"
xv -geom 1280 plottemp.png &
