	xdef	_XCEXIT			* exit(code) is standard way to leave C.

	xref	_LinkerDB		* linker defined base value
	xref	__BSSBAS		* linker defined base of BSS
	xref	__BSSLEN		* linker defined length of BSS

	xref	__main			* Name of C program to start with.
	xref	_AbsExecBase		* ExecBase librayr pointer
	xref	_FindTask		* FindTask() routine
	xref	_DOSBase		* DOSBase library pointer


*	library references

	csect	text,0,0,1,2	* any xref's after this are 16-bit reloc

	xref	_LVOFindTask
	xref	_LVOForbid
	xref	_LVOOpenLibrary
	xref	_LVOCloseLibrary

start:
	move.l	a7,d0			* save old stack ptr
	movem.l	d1-d6/a0-a6,-(a7)	* save registers on stack
	move.l	d0,a5			* save old stack frame
	move.l	a7,__StackPtr		* Save stack ptr

	move.l	_AbsExecBase,a6		* set up for Exec Call (FindTask)
	move.l	a6,_SysBase		* save ExecBase in _SysBase
	suba.l	a1,a1			* load a zero
	jsr	 _LVOFindTask(a6)	* FindTask(0)
	move.l	d0,a4			* use A4 as pointer to Task

openDOS:
	lea	DOSName,A1              * point to DOSName
	moveq.l	#0,D0			* load a zero
	jsr	_LVOOpenLibrary(a6)	* Open the DOS library
	move.l	D0,_DOSBase		* store its pointer in _DOSBase
	bne	Call_Main		* if OpenLibrary failed then error
	moveq.l	#100,d0			*   with code 100
	bra	exit2			* skip running the main program

Call_Main:
	lea	__BSSBAS,a6		* get base of BSS
	move.l	#__BSSLEN,d0		* get length of BSS in longwords
	beq.s	main			* if no bss
	subq.l	#1,d0			* number of iterations
	moveq	#0,d1			* value to store (zero)
clr_bss move.l	d1,(a6)+		* store and increment pointer
	dbf	d0,clr_bss		* decrement count and repeat

main	lea	_LinkerDB,a6		* load base register
	jsr	__main		        * call C entrypoint
	moveq.l	#0,d0			* set successful status
	bra.s	exit2

_XCEXIT:
	move.l	4(SP),d0		* extract return code
exit2:
        move.l	d0,-(a7)		* save it temporarily

	move.l	_SysBase,a6		* prepare for Exec call (CloseLibrary)
	move.l	_DOSBase,a1		* closing DOS library
	jsr	_LVOCloseLibrary(a6)	* call CloseLibrary()

        MOVE.L	(A7)+,D0		* get back return code
	movea.l  __StackPtr,SP		* restore stack ptr
	movem.l	(a7)+,d1-d6/a0-a6	* restore registers
	rts



	csect	__MERGED,1

        xdef    _SysBase
        xdef    __oserr
        xdef    __OSERR
        xdef    __ONBREAK
        xdef    __FPERR,__SIGFPE,__ECS
	xdef	__ProgramName,__StackPtr

__oserr		dc.l	0
__OSERR		dc.l	0
__ONBREAK	dc.l	0
__FPERR         dc.l    0
__SIGFPE        dc.l    0
__ECS           dc.l    0
_SysBase	dc.l	0
__StackPtr	dc.l	0
__ProgramName	dc.l	0
DOSName 	dc.b	'dos.library',0

	END

