#!/bin/bash

use_gun=1
gun_w=0
gun_h=0
gun_mode="absolute"
gun_device='/dev/input/by-id/usb-0b9a_016a-joystick'

res="0"
run=""
free_play=0
num_of_coins=5

emulator=`basename $0 | awk -F. '{ print $1 }'`

emu_time="/tmp/emulate_time"
time_thresh=2

# dont let it run too fast
if [ -f $emu_time ]; then
	now=`date +%s`
	b4=`cat $emu_time`
	diff=`calc $now-$b4`

	if [ $diff -lt $time_thresh ]; then
#		killall wahcade -9
#		killall python -9
		date +%s > $emu_time
		exit
	fi
fi

######## PARSE OPTIONS #########

# start emulator
case $emulator in
	"mame" )
		free_play=1
		use_gun=0
		run="cd ~/emulators/mame/mame_142; ./mame $*"
		;;
	"snes" )
		run="zsnes -m \"$*\""
		;;
	"nes" )
		#num_of_coins=2
		res="640x480"
		run="aoss fceu -sound 1 -fs 0 -opengl 1 \"$*\""
		;;
	"sms" )
		# put int clipboard
		echo "$*" | xclip -i -selection clipboard
		run="eval \"sleep 1; xdotool key ctrl+o; sleep .2; xdotool key ctrl+v BackSpace Return;\"&"
		run="$run aoss ~/emulators/Sega\\ Master\\ System/osmose/osmose"
#		xmessage "$run"
		;;
	"genesis" )
		run="gens  --enable-sound --fs --quickexit --disable-message --game \"$*\""
		;;
	"pc" )
		run="sh \"$*\"";
		;;
	"c64" )
		run=""
		;;
	"atari" )
		run="/usr/bin/stella -fullscreen 1 \"$*\""
		;;
	"psx" )
		gun_w=400
		gun_h=300
		gun_mode="relative"
		#res="1024x768"

		# hack to get gun working
		run="eval \"sleep 10; xdotool key F5; xdotool key F5;\"&"
		run="$run eval \"sleep 10; xdotool key F5; xdotool key F5;\"&"
		run="$run cd ~/emulators/psx/epsxe1.7; wine ./ePSXe.exe -nogui -loadiso \"$*\""
		;;
	"wii" )
		run="dolphin-emu -b -e \"$*\""
		;;
	"n64" )
		run="mupen64plus --nogui --fullscreen \"$*\""
		;;
esac


xdotool mousemove 1600 1200
killall mame_relay.sh
mame_relay.sh game

######## C.R.E.A.M.  #########
if [ "$free_play" -lt 1 ]; then
	xterm -geometry 0x0-0-0 -e "/usr/local/bin/wait_for_coins.sh $num_of_coins $$"
	mame_relay.sh paid&
	# hide cursor
	xdotool mousemove 1366 768
fi

######## START GAME #########
killall mame_relay.sh -9

xrandr -s "$res"

if [ "$use_gun" -gt 0 ]; then
	#xterm -geometry 0x0-0-0 -e "while [ 1 ]; do /usr/local/bin/joymouse -i /dev/input/js0 -t $gun_mode -w $gun_w -h $gun_h; done"&
	 /usr/local/bin/joymouse -i "$gun_device" -t $gun_mode -w $gun_w -h $gun_h -o /tmp/gun&
fi

echo $run
eval $run

killall joymouse

######## STOP GAME #########
# reset display
xrandr -s 1360x768;

# relays for menu
killall mame_relay.sh -9
killall xterm -9
mame_relay.sh menu&

date +%s > $emu_time

