*** Startup module for the Tesseract program
*   See tess.c for copyright notice

	include "libraries/dosextens.i"
	include "workbench/startup.i"

	public	_LVOOldOpenLibrary
	public	_LVOFindTask,_LVOWaitPort,_LVOGetMsg
	public	_LVOCurrentDir
	public	_LVOForbid,_LVOReplyMsg

AbsExecBase	equ	4

	entry	.begin
	public	.begin
.begin
	far	data
	lea	__H1_org+32766,a4	; geta4
	near	data

	; Determine if INITALIZED and UNINITIALIZED data segments are together
	lea	__H1_end,a1
	lea	__H2_org,a2
	cmp.l	a1,a2
	; If so, skip the operation as data will already be set to zero
	bne	2$

	; Determine amount of memory to clear
	move.w	#((__H2_end-__H2_org)/4)-1,d1
	; Skip if no UNINITIALIZED data
	bmi	2$

	; "Clear global variables" loop
1$	clr.l	(a1)+
	dbra	d1,1$

2$	; Set up the EXEC library base pointer
	movea.l AbsExecBase,a6
	move.l	a6,_SysBase

	; Get our task address
	suba.l	a1,a1
	jsr	_LVOFindTask(a6)
	move.l	d0,_ThisProc

	; Get and save the WB startup message, if not started from CLI
	move.l	d0,a5
	moveq	#0,d0
	tst.l	pr_CLI(a5)
	bne	3$
	lea	pr_MsgPort(a5),a0
	jsr	_LVOWaitPort(a6)
	lea	pr_MsgPort(a5),a0
	jsr	_LVOGetMsg(a6)
3$	move.l	d0,_WBenchMsg

	; Open DOS library
	;  1.  Any version
	;  2.  Assumes success!!!
	;  3.  Not closed on exit!
	lea	dos_name,a1
	jsr	_LVOOldOpenLibrary(a6)
	move.l	d0,_DOSBase

	; Set current directory on WB startup
	move.l	_WBenchMsg,d0
	beq	4$
	move.l	d0,a0
	move.l	sm_ArgList(a0),a0
	move.l	wa_Lock(a0),d1
	move.l	_DOSBase,a6
	jsr	_LVOCurrentDir(a6)

	public	_main
4$	jmp	_main		; must return via exit()


	public	_exit,__exit
_exit
__exit
	move.l	4(sp),d0        ; fetch exit() return code
exit
* A static initial SP variable is not used in this code.  We are using the
* fact that AmigaDOS places the address of the top of our stack in SP and
* proc->pr_ReturnAddr right before JSR'ing to us.  This code uses
* pr_ReturnAddr when restoring SP.
	move.l	_ThisProc,a5
	move.l	pr_ReturnAddr(a5),sp
	subq.l	#4,sp		; subtract 4 for return address

	; Return the WB startup message, if applicable
	tst.l	_WBenchMsg
	beq.s	1$
	;  We Forbid() so Workbench can't UnLoadSeg() us before we're done
	move.l	d0,-(sp)        ; put return code temporarily on stack
	move.l	_SysBase,a6
	jsr	_LVOForbid(a6)
	move.l	_WBenchMsg,a1
	jsr	_LVOReplyMsg(a6)
	move.l	(sp)+,d0        ; pull return code off stack and return to DOS

1$	rts


dos_name	dc.b	'dos.library'      ,0

	dseg

	; Data segment labels (used above)
	public	__H1_org,__H1_end,__H2_org,__H2_end

	; Global variables set up by this startup code
	global _SysBase,4
	global _DOSBase,4
	global _WBenchMsg,4
	global _ThisProc,4

	end
