local ioport = manager.machine.ioport
local cas = manager.machine.cassettes[':ctrl3:cassette:cassette']
local playing = false
local caslistener
local warp = false

local wordshift = ioport.ports[':KEYPAD0'].fields['=   WORDS Shift']
local blueshift = ioport.ports[':KEYPAD1'].fields['.   BLUE Shift']
local colon     = ioport.ports[':KEYPAD0'].fields['+   =     #   %   :   PRINT']
local input     = ioport.ports[':KEYPAD2'].fields['2   0     <   "   >   INPUT']
local enterkey  = ioport.ports[':KEYPAD3'].fields['C   GO                +10']
local runkey    = ioport.ports[':KEYPAD1'].fields['↓   HALT              RUN']

caslistener = emu.add_machine_frame_notifier(function()
    if cas.is_playing then
		playing = true
		if not warp then
			warp = true
			manager.machine.video.throttled = false
		end
    else
    	if playing then
        	caslistener:unsubscribe()
        	manager.machine.video.throttled = true
        	emu.wait(1)        	
        	runkey:set_value(1) emu.wait(1/20) runkey:clear_value() emu.wait(2)
        	wordshift:set_value(1) emu.wait(1/20) wordshift:clear_value() emu.wait(1/20)
        	runkey:set_value(1) emu.wait(1/20) runkey:clear_value() emu.wait(1/2)
        	enterkey:set_value(1) emu.wait(1/20) enterkey:clear_value()
        end
    end
end)

blueshift:set_value(1) emu.wait(1/20) blueshift:clear_value() emu.wait(1/20)
colon:set_value(1) emu.wait(1/20) colon:clear_value() emu.wait(1/20)
wordshift:set_value(1) emu.wait(1/20) wordshift:clear_value() emu.wait(1/20)
input:set_value(1) emu.wait(1/20) input:clear_value() emu.wait(1/2)
enterkey:set_value(1) emu.wait(1/20) enterkey:clear_value() emu.wait(1)

cas:play()
