
		;   C.A
		;
		;   (c)Copyright 1990, Matthew Dillon, All Rights Reserved
		;
		;   Amiga startup code
		;
		;   Code is residentable if
		;	(a) A copy of HUNK_DATA exists  or
		;	(b) There is no HUNK_DATA
		;
		;   refer to the -r option for dcc.

		section text,code

		xref	__main		    ; we call _main()
		xref	_FreeMem
		xref	__BSS_BAS
		xref	__BSS_LEN
		xref	__DATA_COPY_BAS
		xref	__DATA_COPY_LEN
		xref	_LVOSetSignal

		xdef	__exit		    ; we are _exit()
		xdef	start
		xdef	_SysBase

start:
		movem.l D2-D7/A2-A6,-(sp)

		move.l	4,A6		    ; EXEC base
		move.l	A6,_SysBase

		;   Arbitrate access... only one instance at a time!

		addq.w	#1,ResRefCnt
		beq	arbok
					    ; uh oh XXX fix me to LoadSeg!
		bra	exarberr

arbok
		move.l	sp,A2
		move.l	A0,-(sp)            ; save arg for _main() call
		move.l	D0,-(sp)            ; save arglen for _main() call

		;   Clear BSS space and code data-copy into data space.

		moveq.l #0,D0
		lea	__BSS_BAS,A0
		move.l	#__BSS_LEN,D1
		bra	bssent
bsslop		move.l	D0,(A0)+
bssent		dbf	D1,bsslop
		sub.l	#$10000,D1
		bcc	bsslop

		;   Copy __DATA_COPY_BAS, __DATA_COPY_LEN

		lea	__DATA_COPY_BAS,A1
		move.l	#__DATA_COPY_LEN,D1
		bra	datent
datlop		move.l	(A1)+,(A0)+
datent		dbf	D1,datlop
		sub.l	#$10000,D1
		bcc	datlop

		move.l	A2,__ExitSP	    ; sp to restore

		moveq.l #0,D0		    ; new signals
		move.l	#$1000,D1	    ; signal mask
		jsr	_LVOSetSignal(A6)   ; clear ^C

		jsr	__AutoInit0	    ; A6 has SYSBase
		jsr	__AutoInit1	    ; A6 has SYSBase
		jsr	__main(PC)

		;   fall through to low level exit... this avoids referencing
		;   exit() if the user overides _main().

		pea	0
		pea	0

		;   _EXIT()
		;
		;   since entry uses malloc we must free any incidental memory
		;   at __exit instead of _exit.

__exit:
		move.l	_SysBase,A6
		jsr	__AutoExit1	    ; A6 has SysBase
		jsr	__AutoExit0	    ; A6 has SysBase
		move.l	___MemList,D0	    ; free memory
		beq	ex20
ex10		move.l	D0,A2
		move.l	(A2),A3             ; next...
		move.l	4(A2),-(sp)         ; bytes
		move.l	A2,-(sp)            ; ptr
		jsr	_FreeMem
		addq.l	#8,sp
		move.l	A3,D0		    ; next...
		bne	ex10
ex20		move.l	D0,___MemList

		move.l	4(sp),D0            ; get exit code
		move.l	__ExitSP,sp	    ; restore sp

		;   FINIS, poof.

exarberr	subq.w	#1,ResRefCnt
		movem.l (sp)+,D2-D7/A2-A6
		rts

_SysBase	dc.l	0		    ; in CODE section on purpose
ResRefCnt	dc.w	-1		    ; in CODE section on purpose

		;   Base of autoinit section

		section autoinit0,code
__AutoInit0:
		section autoinit1,code
__AutoInit1:
		section autoexit0,code
__AutoExit0:
		section autoexit1,code
__AutoExit1:
		section bss,bss

		xdef	___MemList

__ExitSP	ds.l	1
___MemList	ds.l	1

		END

