#!/bin/bash

TOP=jt89
DUMPSIGNALS=-trace
TEST_FILE=
VER_EXTRA=
EXTRA=
GYM_ARG=

while [ $# -gt 0 ]; do
	if [ "$1" = "-slow" ]; then
		echo "Clock divider enabled"
		FAST=
		EXTRA="$EXTRA -slow"
		shift
		continue
	fi	
	if [ "$1" = "-f" ]; then
		shift
		if [ ! -e "$1" ]; then
			echo "Cannot open file " $1 " for GYM parsing"
			exit 1
		fi
		GYM_ARG="-f"
		TEST_FILE="$1"
		if [[ "$WAV_FILE" == "" ]]; then
			WAV_FILE=$(basename "${TEST_FILE}.wav")
		fi
		shift
		continue
	fi
	if [ "$1" = "-time" ]; then
		shift
		EXTRA="$EXTRA -time $1"
		shift
		continue
	fi
	if [ "$1" = "-sms" ]; then
		echo "Use SMS variation."
		shift
		VER_EXTRA="-Ginterpol16=1 ../../hdl/mixer/jt12_interpol.v ../../hdl/mixer/jt12_comb.v"
		continue
	fi

	echo Unrecognized option
    exit 1
done

if [[ "$TEST_FILE" = "" ]]; then
	echo "Specify the VGM/GYM/JTT file to parse using the argument -gym file_name"
	exit 1
fi

if [ "$EXTRA" != "" ]; then echo EXTRA="$EXTRA"; fi

if [[ $(expr match "$TEST_FILE" ".*\.vgz") != 0 ]]; then
	echo Uncompressing vgz file...
	gunzip -S vgz "$TEST_FILE" --to-stdout > input.vgm
	UNZIP_GYM=input.vgm
else
	UNZIP_GYM=$TEST_FILE
fi

if ! verilator --cc ../../hdl/${TOP}.v $VER_EXTRA -I../../hdl --top-module $TOP --trace --exe test.cpp; then
	exit $?
fi

if ! make -j -C obj_dir -f V${TOP}.mk V${TOP}; then
	exit $?
fi

mkdir -p log

date
echo Simulation start...
echo obj_dir/V${TOP} $DUMPSIGNALS $EXTRA $GYM_ARG "$UNZIP_GYM"
if ! obj_dir/V${TOP} $DUMPSIGNALS $EXTRA $GYM_ARG "$UNZIP_GYM" ; then
	exit $?
fi

if [[ $DUMPSIGNALS == "-trace" && -e test.vcd ]]; then
	echo Converting VCD to FST
	if vcd2fst -p -v test.vcd -f test.fst; then
		rm test.vcd
		echo Done
	fi
fi
# verilator_coverage --annotate log/cov.log