
	SECTION	ONE

*	PCQStart.asm (of PCQ Pascal runtime library)
*	Copyright (c) 1989 Patrick Quaid

*	This is the startup and shutdown code for the programs.
*	Note that a few changes have got to take place here before PCQ
*	programs can be run from the WorkBench.

	XREF	_CommandLine	; from the main program
	XREF	_AbsExecBase
	XREF	_LVOOpenLibrary
	XREF	_LVOCloseLibrary

	XREF	_LVOInput
	XREF	_LVOOutput
	XREF	_LVOClose

	XREF	_LVOFreeRemember

	XREF	newkey
	XREF	filekey

	XDEF	_stdin
	XDEF	_stdout
	XDEF	stdinbuffed
	XDEF	stdinbuffer
	XDEF	_p%DOSBase
	XDEF	_p%IntuitionBase
	XDEF	_p%MathBase

;	Define entry point

	xdef	_p%initialize
_p%initialize

;	Save stack pointer for exit() routine

	move.l	sp,StkPtr	; save stack pointer
	add.l	#4,StkPtr	; account for this jsr to get to original

;	copy command line into _CommandLine

	move.l	#_CommandLine,a1
1$	move.b	(a0)+,d1
	move.b	d1,(a1)+
	bne	1$
	
;	Open libraries

	lea	intuitionname,a1
	clr	d0
	move.l	_AbsExecBase,a6
	jsr	_LVOOpenLibrary(a6)
	move.l	d0,_p%IntuitionBase
	beq	_p%wrapitup

	lea	dosname,a1
	clr	d0
	jsr	_LVOOpenLibrary(a6)
	move.l	d0,_p%DOSBase
	beq	_p%wrapitup

	lea	mathname,a1
	clr	d0
	jsr	_LVOOpenLibrary(a6)
	move.l	d0,_p%MathBase
	beq	_p%wrapitup

;	Find standard file handles
;	This part will have to be adjusted for WorkBench.

	move.l	_p%DOSBase,a6
	jsr	_LVOInput(a6)
	move.l	d0,_stdin
	beq	_p%wrapitup
	jsr	_LVOOutput(a6)
	move.l	d0,_stdout
	beq	_p%wrapitup
	rts

;	The shut-down code

	xdef	_p%wrapitup
_p%wrapitup:

	tst.l	filekey		; close all open files
	beq.s	2$
	move.l	_p%DOSBase,a6
	move.l	filekey,a0
1$	move.l	(a0),d1
	move.l	a0,-(sp)
	jsr	_LVOClose(a6)
	move.l	(sp)+,a0
	move.l	14(a0),a0
	move.l	a0,d0
	bne.s	1$

2$	tst.l	newkey		; return all allocated memory
	beq.s	3$
	lea	newkey,a0
	moveq.l	#-1,d0
	move.l	_p%IntuitionBase,a6
	jsr	_LVOFreeRemember(a6)
3$
	move.l	_AbsExecBase,a6
	move.l	_p%IntuitionBase,a1
	move.l	a1,d0				; to set flags
	beq.s	4$
	jsr	_LVOCloseLibrary(a6)
4$
	move.l	_p%DOSBase,a1
	move.l	a1,d0				; set flags
	beq.s	5$
	jsr	_LVOCloseLibrary(a6)
5$
	move.l	_p%MathBase,a1
	move.l	a1,d0
	beq.s	6$
	jsr	_LVOCloseLibrary(a6)
6$
	moveq.l	#0,d0
	rts

	XDEF	_exit
	XDEF	_p%exit
_exit
	move.l	4(sp),d0
_p%exit
	move.l	d0,-(sp)
	jsr	_p%wrapitup
	move.l	(sp)+,d0
	move.l	StkPtr,sp
	rts

	SECTION	TWO,DATA

stdinbuffed	dc.b	0
stdinbuffer	dc.b	0
dosname		dc.b	'dos.library',0
intuitionname	dc.b	'intuition.library',0
mathname	dc.b	'mathffp.library',0

	CNOP	0,2

_p%DOSBase	dc.l	0
_p%IntuitionBase dc.l	0
_p%MathBase	dc.l	0

	SECTION	THREE,BSS

StkPtr		ds.l	1
_stdin		ds.l	1
_stdout		ds.l	1

	END
