; File: Atari2600.i
; =================
; Author: Neil Cafferkey

	ifnd	atari2600_i
atari2600_i	set	1


	include	"lib/atari2600.i"

	include	"MOS6507.i"
	include	"Stella.i"
	include	"Riot.i"

	include	"asm_support.i"

	include	"offsets.i"



; Macro: START_UP
; ===============
;

	macro	START_UP

	; Get pointer to exec.library

	move.l	4,a6

	; Find the program's process structure

	movea.l	#0,a1
	CALLSYS	FindTask
	movea.l	d0,a4

	; Check if the program was started from the Workbench or the CLI

	clr.l	wb_msg
	tst.l	(pr_CLI,a4)
	bne	cli$

wait_again$:

	lea.l	(pr_MsgPort,a4),a0
	CALLSYS	WaitPort
	lea.l	(pr_MsgPort,a4),a0
	CALLSYS	GetMsg
	movea.l	d0,wb_msg
	beq	wait_again$

cli$:

	; Open any version of atari2600.library

	lea	atari2600Name,a1
	moveq	#0,d0
	CALLSYS	OpenLibrary

	; Store library base. Exit if library couldn't be opened.

	move.l	d0,Atari2600Base
	bne	\@opened$
	moveq	#20,d2
	bra	exit

	; Open a new simulated Atari 2600 environment

\@opened$:
	movea.l	Atari2600Base,a6

	move.l	sp,d0
	movea.l	#data,a1
	movea.l	#env_tags,a0
	CALLSYS	A2600_OpenAtari2600

	; Store environment. Exit if environment couldn't be created.

	move.l	d0,environment
	movea.l	d0,ENV
	bne	\@env_created$

	moveq	#20,d2
	bra	exit

\@env_created$:

	; Move ROM image into Atari 2600's address space

	movea.l	Atari2600Base,a6
	lea	rom,a0
	lea	data+$1000,a1
	move.l	#$1000,d0
	CALLSYS	A2600_InstallROM

	; Clear all emulation registers

	moveq	#0,A
	moveq	#0,X
	moveq	#0,Y
	moveq	#0,P
	moveq	#0,D_FLAG
	moveq	#0,S

	movea.l	#0,CLOCK

	endm


; Macro: EXIT
; ===========
;

	macro	EXIT

	; Close Atari 2600 environment

	move.l	environment,d0
	movea.l	d0,a1
	beq	\@env_not_opened$
	movea.l	Atari2600Base,a6
	CALLSYS	A2600_CloseAtari2600

\@env_not_opened$:

	; Close Atari 2600 library

	move.l	Atari2600Base,d0
	movea.l	d0,a1
	beq	\@lib_not_opened$
	movea.l	4,a6
	CALLSYS	CloseLibrary

\@lib_not_opened$:

	; Reply to workbench message if program was started from workbench

	tst.l	wb_msg
	beq	\@skip_msg_reply$

	movea.l	4,a6
	CALLSYS	Forbid

	movea.l	wb_msg,a1
	CALLSYS	ReplyMsg

\@skip_msg_reply$:

	; Set return code and exit

	move.l	d2,d0
	rts

	endm


	bss

wb_msg:			ds.l	1
Atari2600Base:		ds.l	1
environment:		ds.l	1

timed_out		ds.w	1


	data

atari2600Name:
	dc.b	"atari2600.library",0


	bss

	cnop	0,4

data:

	ds.b	$2000


	endc

