#!/bin/sh
#
#   plot.sh - Parses the runtime simulation json data and plots them to an svg file
#
#   Copyright (c) 2024 Efthymios Kritikos
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
set -euf

print_help(){
	echo "$0 <json data file> <function> <output filename>"
	echo " Possible functions:"
	echo "      cache_time      : graph of cache utilisation in bytes over time in clock cycles"
	echo "      cache_util_freq : graph of the likelihood of the cache for each utilisation"
}

if [ "$#" != 3 ] || ! [ -e "$1" ]
then
	print_help
	exit 1
fi

CSV_FILE=$(mktemp)
IN=$1
OUT=$3

jq  -r '.Cycles[]| [.C,.L1,.VDI,.JMP]|@csv' -- "$IN" > "$CSV_FILE"

BASE_GNUPLOT_OPTIONS="set datafile separator ',';set term svg;set output \"${OUT}\";"

parse_cache_size(){
	CACHE_SIZE=$(jq -r .L1_size -- "$IN")
}

parse_total_cycles(){
	TOTAL_CYCLES=$(jq -r .\"Total\ Cycles\" -- "$IN")
}

case "$2" in
	"cache_time")
		parse_cache_size
		parse_total_cycles
		gnuplot -e "${BASE_GNUPLOT_OPTIONS}\
set term svg name \"Cache_time\";\
set xlabel \"Clock cycles\";\
set ylabel \"Cache utilisation (bytes)\";\
set offsets 0,  0, 3, 1;\
set ytics 0,1,$((CACHE_SIZE-1));\
set xtics 0,$((TOTAL_CYCLES/15)),${TOTAL_CYCLES};\
unset colorbox;\
set ytics add (\"Valid\" -1);\
set grid ytics;\
set yrange [-2:${CACHE_SIZE}];\
set xrange [-10:${TOTAL_CYCLES}+9];\
set palette model RGB defined ( 0 'red', 1 'green', 2 'dark-khaki' );\
plot\
     '${CSV_FILE}' using 1:(-2):(0):("'$'"4*100):(2) with vectors nohead palette notitle,\
     '${CSV_FILE}' using 1:2  with histeps notitle ls 1,\
     '${CSV_FILE}' using 1:(-0.75):(0):(-0.5):3 with vectors nohead palette notitle \
     "

		;;
	"cache_util_freq")
		parse_cache_size
		gnuplot -e "${BASE_GNUPLOT_OPTIONS}\
set term svg name \"cache_util_freq\";\
set xlabel \"Utilisation (bytes)\";\
set ylabel \"Occurrences\";\
set boxwidth 0.5;\
set style fill solid 0.4;\
set xtics 0,1,$((CACHE_SIZE-1));\
set offsets 1, 2, 0, 0;\
 plot '${CSV_FILE}' using 2:(1) smooth frequency with boxes notitle"

		;;
	*)
		print_help;
		exit 1
		;;
esac
