#!/data/data/com.termux/files/usr/bin/bash
source pidejl/includes.sh
rompath=storage/external-1/Intellivision
game=$rompath/$1
ListGames(){
	cd $rompath
	ls *.bin *.int *.itv *.rom | sed 's/\(.*\)\..*/\1/'
	cd
}
clear
if [ -z "$1" ] ; then
	ListGames
	echo -e "${LightRed}Choose from the above list and enter the name of the game in quotes.${NoColor}"
elif [[ ! -e $game.bin && ! -e $game.rom && ! -e $game.cc3 && ! -e $game.int && ! -e $game.itv ]] ; then
	ListGames
	echo -e "${LightRed}$1 not found.  Sorry.${NoColor}"
else
	echo -e "${White}$1 for Intellivision${NoColor}"
	# Check for box image
	if [ -e "$game.png" ] ; then
		#feh --bg-max "$game.png"
		feh --no-fehbg --force-aliasing -x -F -Z "$game.png" &
	fi
	DrawThatGrid
	maxchoice=12
	read var
	if [[ -z $var || $var -lt 1 || $var -gt $maxchoice ]] ; then
		echo -e "${LightRed}Not one of the options.  Goodbye.${NoColor}"
	else
		# IntelliVoice?
		[[ $((var & 1 )) -eq 0 ]] && argvoice=-v1 || argvoice=-v0
		# ECS or INTV88 (4x GRAM)?
		case $((($var - 1) / 2 % 3 )) in
			1) argsecs="-s1 -G0"
				;;
			2) argsecs="-s0 -G2"
				;;
			*) argsecs="-s0 -G0"
		esac
		# PAL or NTSC?
		if [[ $var -ge 7 ]] ; then
			argpal=-P
		fi
		# Vectron has its own keyboard hackfile and debug script, which enables a cheat to disable the Nasties.
		[[ $1 == "Vectron" ]] && arghackfile=pidejl/veckeys.cfg || arghackfile=pidejl/hackfile.cfg
		[[ $1 == "Vectron" ]] && argscript=pidejl/veccheat.txt || argscript=pidejl/dbscript.txt
		# Find the ROM image
		if [ -e "$game.bin" ] ; then
			romfile="$game.bin"
		elif [ -e "$game.rom" ] ; then
			romfile="$game.rom"
		elif [ -e "$game.cc3" ] ; then
			romfile="$game.cc3"
		elif [ -e "$game.int" ] ; then
			romfile="$game.int"
		elif [ -e "$game.itv" ] ; then
			romfile="$game.itv"
		else
			romfile="$game.luigi"
		fi
		# Check for instruction manual
		if [ -e "$game.pdf" ] ; then
			xpdf -geometry -0+0 "$game.pdf" &
			sleep 1
		fi
		# Check for overlay image
		if [ -e "$game.jpg" ] ; then
			feh --no-fehbg -g +0+0 "$game.jpg" &
		fi
		# Play time!
		#pidejl/overlay.py | jzintv --gui-mode --gfx-palette=pidejl/intycolors.cfg --kbdhackfile=$arghackfile --script=$argscript -d -z3 -b6 -a11025 $argvoice $argsecs $argpal $2 $3 $4 $5 $6 $7 $8 $9 "$romfile"
		jzintv --gfx-palette=pidejl/intycolors.cfg --kbdhackfile=$arghackfile --script=$argscript -d -z3 -b6 -a11025 $argvoice $argsecs $argpal $2 $3 $4 $5 $6 $7 $8 $9 "$romfile"
		echo jzintv returned exit status $?
		# Get rid of the overlay image
		if [ -e "$game.jpg" ] ; then
			pkill feh
		fi
		# Get rid of the instruction manual
		if [ -e "$game.pdf" ] ; then
			pkill xpdf
		fi
	fi
	# Get rid of the box image
	if [ -e "$game.png" ] ; then
		#feh --bg-max -z *.jpg
		pkill feh
	fi
fi
#EOF
