;---------------------------------------------------------------------
;	SPOOLER RSX v1.2 (development version)
;---------------------------------------------------------------------
;
sectrs	equ	16		; No of sectors to buffer in disk read operations.
				; Sectrs=16 is a 2k buffer
;
qentry	equ	16		; Max no of spool queue entries
;
;---------------------------------------------------------------------
;	RSX function nos reserved for communicating with loader.
;
intspl	equ	40		; Install spooler RSX and setup spool directory
getnxt	equ	41		; Return fcb for next file to add to queue
qcopy	equ	42		; Copy filename entry to queue
				; Data format is (nos in brackets are no of bytes):
				; Drive(1),filename(8),extension(3),pos(1),size(3).
getdir	equ	43		; Return spool directory drive and user no
qlist	equ	44		; List spool queue
abortp	equ	45		; Cancel one spooled file
bugoff	equ	46		; Abort spool and uninitialise
;
;---------------------------------------------------------------------
;	RSX Header follows:
;
	db	0,0,0,0,0,0
	jp	monitr		; BDOS calls routed to RSX "listener"
nxtrsx:	jp	0		; Jump vector to next module/BDOS (set by CCP Loader)
prev:	dw	0		; Address of previous module
remove:	db	0ffh		; Remove flag (0=permanent)
	db	0		; Nonbank=FALSE
rsxnam:	db	'SPOOLER '
	db	0,0,0
;
;---------------------------------------------------------------------
;	Monitor BDOS calls for any communication with RSX.
;	This routine is called normally via the RSX header.
;
monitr:	ld	a,c		; A=BDOS function no
	cp	calrsx		; RSX call?
	jp	nz,nxtrsx	; No, so go to next RSX or BDOS
	jp	talk		; Else check if ours & talk to caller
;
;---------------------------------------------------------------------
;	BDOS call intercept routine.
;	Calls to the BDOS entry point are redirected here.
;
rbase:	ld	a,(nospol)
	or	a
	jp	nz,gosys	; Not active - no intercepts
	ld	a,c
	cp	scan1		; Else, is it a directory search?
	jp	nz,nolock
;
	ld	a,0ffh
	ld	(lockfl),a	; If so, lock out disk access until complete
;
nolock:	ld	a,c
	cp	open
	jp	z,unlock	; Remove lockout if its another disk function...
	cp	wrsect
	jp	z,unlock
	cp	rdsect
	jp	z,unlock
	cp	close
	jp	z,unlock
	cp	make
	jp	z,unlock
	cp	delete
	jp	z,unlock
	cp	rnread
	jp	z,unlock
	cp	rnwrit
	jp	z,unlock
	cp	wrzfil
	jp	nz,staylk
;
unlock:	xor	a
	ld	(lockfl),a	; Disk access lock = OFF
;
;	Save user regs & stack before testing for console input calls.
;
staylk:	ld	h,d
	ld	l,e
	ld	(bdosde),hl	; Save user parms
	ld	a,c
	ld	(bdosfn),a	; Save user function no
	ld	hl,0
	add	hl,sp
	ld	(bdostk),hl	; Save user stack
	ld	sp,stack2
;
;	Test for console status requests & handle if so
;
	cp	const		; BDOS function 11?
	jp	z,notcin	; Yes: jump to fill buffer if empty
				; Note: BIOS intercept calls splout after BDOS call made
;
;	Test for Direct Console I/O
;
	cp	dircon		; Direct console I/O?
	jp	nz,ndirio	; No - jump past
;
;	Handle Direct Console I/O requests
;
	ld	a,e
	cp	0fdh		; Wait for input call?
	jp	c,docall	; No, but <0fdh, so must output a character
	jp	z,chstat	; Yes - poll until BDOS const TRUE
;
notcin:	call	chkbuf		; Read buffer if empty (applies to 0feh & 0ffh calls)
	jp	docall		; And do the BDOS call
;
;	Handle Conin & Fill Console Buffer Calls - others jump past 
;
ndirio:	cp	conin		; Conin call?
	jp	z,chstat	; If so, poll status & spool until char ready
	cp	conbuf		; Fill console buffer call?
	jp	nz,docall	; Jump out if not - else poll as above
;
;	Poll chkbuf and BDOS const (via direct I/O) until key waiting
;	Note that if the intercepted call was from the CCP and there	
;	is a multiple line RSX resident, the poll is skipped as
;	a CCP command has already been entered.
;
chstat:	ld	c,scblk
	ld	de,scb18
	call	gosys		; SCB 18h bits 5 & 7 show whether multi-line
	and	0a0h		; RSX is ready to provide I/P to CCP
	cp	20h		; (Bit 5 set, bit 7 unset)
	jp	z,docall	; If so don't poll const - go to BDOS
chst2:	call	chkbuf		; Fill spool buffer if necessary
	ld	c,dircon
	ld	e,0feh
	call	gosys		; Get console status from BDOS (NB sets locks)
	or	a		; Key waiting?
	jp	z,chst2		; No - continue to poll
;
;	Restore registers & stack before doing user's BDOS call
;
docall:	ld	hl,(bdostk)
	ld	sp,hl		; Restore stack,
	ld	a,(bdosfn)
	ld	c,a		; BDOS function no
	ld	hl,(bdosde)
	ex	de,hl		; & parms
;
;---------------------------------------------------------------------
;	Jump vector to BDOS (doesn't pass thru any more RSX's).
;	Sets internal BDOS re-entrancy lock flag before calling.
;
gosys:	ld	a,0ffh
	ld	(bdosfl),a	; BDOS call flag=TRUE
	call	bios		; Do the user's BDOS call - addr filled in by init
nbdos	equ	$-2
	push	af		; Save returned value
	xor	a
	ld	(bdosfl),a	; BDOS call flag=FALSE
	pop	af
	ret			; To caller (maybe internal BDOS call)
;
;---------------------------------------------------------------------
;	Talk to calling process
;	Uses standard DR RSX parm block
;
talk:	ld	a,(de)		; A=RSX function no
	inc	de
	inc	de		; DE addresses first parameter in RSX call block
	cp	intspl
	jp	z,instal	; Install request
;
	cp	getdir
	jp	z,givdir	; Return spool directory (also cancels uninstallation)
;
	ld	b,a
	ld	a,(remove)
	or	a		; Is RSX installed?
	jp	nz,passit	; No: none of calls below valid, so pass on
;
	ld	a,b
	cp	bugoff		; Disconnect?
	jp	z,uninit	; Act if so - routine checks if already done
;
	cp	getnxt		; Return next fcb?
	jp	z,allocq	; Allocate place in queue & return next fcb
;
	cp	qlist		; List spool queue?
	jp	z,passq		; If so, pass back the spool queue address
;
	cp	abortp		; Cancel spooling of one file?
	jp	z,abort1	; Yes - act
;
	cp	qcopy		; Copy queue entry & open file?
	jp	z,cpynam	; Yes - copy filename
;
;	Pass call on to next RSX or BDOS.
;
passit:	dec	de
	dec	de
	jp	nxtrsx		; Not one of our calls: pass it on 
;
;---------------------------------------------------------------------
;	Copy filename [DE] to queue (range checks made during getnxt call).
;	If the file is the first (queue empty) it is opened, and system
;	intercepts are enabled.
;
cpynam:	ex	de,hl
	ld	e,(hl)
	inc	hl
	ld	d,(hl)		; DE=start address
	ld	a,(qnext)	; A=next queue no
	push	af		; Save for later
	call	pointq		; HL=16*(qnext-1), or offset for new entry
	push	hl
	ld	b,16		; 16 bytes to move
	call	blkmov		; Copy to it
	pop	hl
	ld	bc,12		; Offset for "queue" no entry
	add	hl,bc
	pop	af		; A=qnext
	push	hl
	push	af
	ld	hl,pnext
;	CALL	PSTRNG
	pop	af
	push	af
;	CALL	PHEX
	ld	c,cr
;	CALL	CHROUT
	ld	c,lf
;	CALL	CHROUT
	pop	af
	pop	hl
	ld	(hl),a		; Store in queue
	cp	qentry		; Have we used the last entry in the queue?
	jp	nz,qspace
	xor	a		; Yes: start at beginning again
qspace:	inc	a		; Else use next one
	ld	(qnext),a	; Update end of queue
	ld	a,(qnow)
	or	a		; Test current queue no to see if it's the first entry
	ret	nz		; No - already spooling
;
	inc	a
	ld	(qnow),a	; Else need to update current file pointer
	ld	hl,ifcb
	call	makfcb		; Make an fcb for the file
	call	openit		; And open it for spooling
				; NB ERROR CHECKING REQUIRED HERE
	xor	a
	ld	(nospol),a	; Allow BDOS & BIOS intercepts
	ret
;
pnext:	db	'Copy to queue: qnext = $'
;
;---------------------------------------------------------------------
;	Return H = user & L = drive of spool directory.
;	If this RSX has not yet been installed, or has already been
;	uninstalled, the call is passed on. If the RSX is waiting to
;	uninstall (finish=0ffh), the uninstallation is cancelled,
;	and the queue reset.
;
givdir:	ld	a,(remove)	; RSX temporary/permanent flag
	or	a		; If temporary, either not installed or uninstalled...
	jp	nz,passon	; So must pass it on (only attached RSX is not installed)
	ld	a,(finish)	; "Waiting to uninstall" flag
	or	a
	jp	z,workin	; If false, working so return drive
;
revive:	xor	a		; Else waiting to uninstall, so...
	ld	(finish),a	; Cancel uninitialisation
	ld	(qnow),a	; Queue empty, so reset pointers: qnow=0...
	inc	a
	ld	(qnext),a	; ...and qnext=1
;
workin:	ld	a,(splusr)
	ld	h,a		; H=user
	ld	a,(spldrv)
	ld	l,a		; L=drive
	ret
;
;	RSX not yet installed, or already uninstalled.
;	Pass the call to the next RSX up the chain, to check
;	whether it is active. If not the BDOS will return HL=00ffh.
;
passon:	dec	de
	dec	de		; DE addresses parameter block again
	ld	c,calrsx
	jp	nxtrsx		; Interrogate next RSX for the drive
				; Returns HL=00ffh if none present
;
;---------------------------------------------------------------------
;	Allocate and make an fcb for the next place in the spool queue.
;
allocq:	ld	a,(qnow)	; Queue no of file now being printed
	ld	b,a
	ld	a,(qnext)
	cp	b		; Check whether space available: qnext<>qnow if so
	ld	a,0ffh		; Default=NO
	ret	z		; Can't accept file: flag error
	ex	de,hl		; [HL]=address of fcb
	ld	e,(hl)
	inc	hl
	ld	d,(hl)
	ex	de,hl		; HL=addr of fcb
	ld	a,(qnext)
	call	makfcb		; Make spool fcb at [HL], with index no A
	ld	hl,alloc2
;	call	pstrng	;DEBUG
	xor	a		; A=0 means OK
	ret
;
alloc2:	db	'Allocating fcb',cr,lf,'$'
;
;---------------------------------------------------------------------
;	Cancel spooling of file with queue no at [DE+2].
;	Sends a formfeed to the printer if the file is currently
;	being printed. No other range checks are made by this routine.
;	Note that this routine will NOT delete the copy of the file in
;	the spool directory unless it is currently being printed.
;	The calling program must handle this, using makfcb() and erafil().
;
abort1:	ld	a,(de)		; A=queue no to cancel
	ld	b,a
	ld	a,(qnow)
	cp	b		; Test whether qnow = queue no to cancel
	jp	z,abort2	; Print to cancel is current one
;
;	Abort spooling of file by setting queue entry to 0ffh
;
	ld	a,b		; A=queue no to cancel
	call	pointq		; HL=address of queue entry
	ld	de,12
	add	hl,de		; HL addresses queue no entry
	ld	(hl),0ffh	; Indicates deleted
	ret
;
;	Cancelling current print: formfeed & open next file 
;
abort2:	ld	c,fmfeed
	call	lstchr		; Formfeed
	call	nxtfil		; Open next file (erases current)
	xor	a		; A=0 signifies abort made
	ret
;
;---------------------------------------------------------------------
;	Pass back the spool queue (for listing).
;	HL is returned containing the address of the spool queue, the
;	first 3 bytes of which are qnow (the file currently being spooled),
;	qnext (the next free queue position) and qmax (the maximum queue no).
;	The queue itself consists of 16 byte entries for each file, as
;	follows:
;		1 byte for the source drive and user no
;		8 bytes for the filename
;		3 bytes for the filetype
;		1 byte for the queue index no (note this may not be the queue no)
;		3 bytes for the file size, in sectors.
;		
passq:	ld	hl,qnow
	ret
;
;---------------------------------------------------------------------
;	Check whether RSX already installed, and act if not.
;	Note that if RSX is already installed, init routines will
;	have been overwritten by the disk buffer.
;	The RSX parameter block should contain the following
;	information on entry:
;
;		[DE  ] = Low byte of BDOS entry point address
;		[DE+1] = High "   "   "     "     "      "
;		[DE+2] = Current temporary file drive
;		[DE+3] = User no of spool directory
;
instal:	ld	a,(remove)	; RSX status flag - temporary/permanent
	or	a
	ret	z		; No action if already working
	jp	init		; Else initialise system intercepts
;
;---------------------------------------------------------------------
;	Character spooling routine. 
;	If the printer is free, a character is sent to it via BIOS. 
;	Characters to spool are provided by getchr - note however 
;	that if the buffer is empty it will be filled by chkbuf
;	(or the next file opened) unless a disk/reentrancy lockout
;	is in progress.
;
;	Note that this routine does NOT check for the eof marker (^Z),
;	since files generated by the spool loader are not terminated
;	with such a marker, but are padded out with null characters,
;	which are ignored by the printer.
;	This is to allow the spooler to be used with object files
;	(eg redirected output from a graphics package).
;
splout:	call	lstat		; Printer busy?
	or	a
	ret	z		; Yes, so ret
;	RET
	call	chkbuf		; Check buffer status - A=0 if empty
	or	a		; Buffer empty?
	ret	z		; Yes - waiting to read, or hard eof occured, so ret
	call	getchr		; Else get a byte from the input buffer
	ld	c,a		; Byte to C for possible print
;	cpi	cpmeof	;Have we reached the eof marker?
;	jz	nxtfil	;Yes - eof reached
;	RET
;	JMP	CHROUT
	jp	lstchr		; Else print the byte
;
;---------------------------------------------------------------------
;	Routine to return a byte from the input buffer.
;	This routine assumes the buffer contains valid data -
;	NO CHECKS ARE MADE FOR INVALID BUFFER VARIABLES.
;
getchr:	ld	hl,(icount)	; HL=buffer count
	dec	hl
	ld	(icount),hl	; Decrement count
	ld	hl,(iptr)	; HL=buffer pointer
	ld	a,(hl)		; A=char
	inc	hl
	ld	(iptr),hl	; Increment buffer pointer
	ret
;
;---------------------------------------------------------------------
;	Routine to check whether the spooler disk buffer is empty,
;	and if so fill it from the spooled file. Note that the read
;	will not take place if disk accesses are currently locked
;	out, to prevent a re-entrant BDOS call, or confusing BDOS
;	while a directory search was in progress.
;	A=0 is returned if the read could not take place due to
;	such a lockout.
;	If eof or a disk read error occurs, the next file is opened.
;	If it cannot be opened, the RSX is uninstalled, & A=0 is returned.
;
chkbuf:	ld	a,(finish)
	cpl			; A=0 if spooler finished...
	or	a		; ...also tells splout that buffer is empty
	ret	z		; If so, no action
	ld	a,(qnow)
	or	a		; Any files to spool (may have been re-activated by NOSPOOL)
	ret	z		; No: do nothing (wboot intercept sets finish flag)
	ld	hl,(icount)	; HL=buffer count
	ld	a,l
	or	h		; Null?
	ret	nz		; No - ret
	ld	b,a		; B is count indicator (=0) in case can't read
	ld	a,(lockfl)
	ld	hl,bdosfl
	or	(hl)		; BDOS & disk lockout flags
	ld	a,b		; A=0 in case can't read
	ret	nz		; If either of the above are true, don't try to read
	call	rdbuf		; Try to read buffer (also sets buffer vars)
	ld	hl,(icount)
	ld	a,h
	or	l		; Count=0?
	ret	nz		; No - read OK
	ld	(openfl),a	; Else eof or disk read error - finish with file
;	CALL	CHKBF2
	call	nxtfil		; Open next one if possible
	ld	a,(finish)	; "Waiting to uninstall" flag
	cpl			; Complement: A=0 if finished
	ret			; As "buffer empty" indicator
chkbf2:	ld	hl,chkbf3
	jp	pstrng
chkbf3:	db	'EOF or disk read error in chkbuf',cr,lf,'$'
;
;---------------------------------------------------------------------
;	Routine to read "sectrs" sectors of data from the input file
;	to the spooler buffer. DMA address and multi-sector count
;	are unaffected by this routine.
;	Note that if physical eof occurs during the read, the buffer
;	count is set according to the number of sectors read before
;	eof occured. If, on exit, icount=0000h, no sectors were read,
;	or a disk read error occured, and spooling on the file should
;	be curtailed.
;
rdbuf:	ld	a,0ffh
	ld	(nospol),a	; No BIOS intercepts while reading (for err msgs etc)
;
	ld	c,9
	ld	de,rdmes
;	CALL	GOSYS	;Debug - comment out in working version
	ld	de,scb3c	; SCB parm block - get DMA address
	ld	c,scblk
	call	gosys		; HL=current DMA address
	ld	(cpmdma),hl
;
	ld	de,ibuff
	ld	c,setdma
	call	gosys		; Set DMA address to RSX input buffer
;
	ld	de,scb4a	; SCB parm block - get multi sector count
	ld	c,scblk
	call	gosys		; A=current multi sector count
	ld	(scount),a	; Saved
;
	ld	e,sectrs
	ld	c,nosecs
	call	gosys		; Set RSX multi sector count
;	
	call	gousr		; To spool dir user area (in case new extent)
	ld	c,rdsect
	ld	de,ifcb
	call	gosys		; Try to read sector(s)
	push	af		; Save error indicator for later check
	push	hl		; And no of sectors read (if <sectrs)
	call	bakusr		; Back to current user area
;
	ld	hl,(cpmdma)
	ex	de,hl
	ld	c,setdma
	call	gosys		; Restore DMA addr
;
	ld	a,(scount)
	ld	e,a
	ld	c,nosecs
	call	gosys		; And multi sector count
;
	xor	a
	ld	(nospol),a	; Allow intercepts again
	ld	hl,ibuff
	ld	(iptr),hl	; Reset byte pointer
;
	pop	hl		; Retrieve read sector count
	pop	af		; And error indicator
	or	a		; Read OK?
	ld	de,sectrs*128
	jp	z,readok	; Yes, jump with DE=new icount value
	dec	a		; Returned A=1?
	jp	nz,dskerr	; No - read error (not eof)
				; Else hard eof occured - how many sectors read?
	ld	a,h		; A=no of sectors read
	call	mlt128		; DE=(no of sectors)*128=new icount value
readok:	ex	de,hl		; Move to HL
	ld	(icount),hl	; Store as new sector count
	ret
;
rdmes:	db	'Trying to read...',cr,lf,'$' ; Used for debugging
;
;	Disk error handler.
;	Prints a message and uninstalls spooler RSX.
;	MAY JUST OPEN NEXT FILE WITH ERROR MESSAGE.
;
dskerr:	xor	a
	ld	(openfl),a	; No file open anymore
	ld	hl,errmes
	call	pstrng
	jp	uninit
;
errmes:	db	cr,lf,'SPOOL ERROR: Disk read failed$'
;
;---------------------------------------------------------------------
;	Erase spool file (as spool completed), & open next file for
;	spooling. If there are no more files in the spool queue,
;	the spooler is uninstalled.
;	Note that this routine must check the BDOS re-entrancy lock
;	flag, as a call to it could come from a BIOS intercept routine.
;
nxtfil:	xor	a
	ld	(openfl),a	; File no longer open
	ld	hl,0
	ld	(icount),hl	; Forces repeat call (if locked out) & disk read on next file
	ld	a,(bdosfl)	; Re-entrancy lock flag
	ld	hl,lockfl	; Directory access disk lockout flag
	or	(hl)		; Is either true (nonzero)?
	ret	nz		; Yes: wait (picked up by system intercepts)
;
	cpl			; A=0ffh
	ld	(nospol),a	; Lockout BIOS intercepts
	call	erafil		; Delete copy of spooled file in spool directory
	ld	a,(qnext)	; Pointer to next free position in queue
;	CALL	PHEX
	ld	b,a
	ld	a,(qnow)
;	CALL	PHEX
	cp	qentry		; Was that the last PHYSICAL entry?
	jp	c,ntlast	; No: jump to increment	
	xor	a		; Else back to physical start of queue
ntlast:	inc	a
	ld	(qnow),a	; Point to next file in queue
	cp	b		; Have we reached the end of the queue?
	jp	z,uninit	; Yes: jump out, uninitialising if possible
;	JZ	UNINT2
;
	call	pointq		; [HL]=entry for qnow
	ld	bc,12
	add	hl,bc		; HL addresses queue no entry
	ld	b,(hl)
	inc	b		; Is it 0ffh?
	jp	z,nxtfil	; Yes: skip this file
;
	ld	hl,ifcb
	call	makfcb		; Make an fcb for the next file (A contains queue index no)
	call	openit		; Try to open it
	or	a		; Test error code (0=OK)
	jp	nz,nxtfil	; If error, do it all again, ignoring current file
;	JNZ	NXTDBG
	xor	a
	ld	(nospol),a	; Allow BIOS intercepts again
	dec	a
	ld	(openfl),a	; File open again
;	LXI	H,NXTFL2
;	CALL	PSTRNG
	ret
;
nxtfl2:	db	'Next file opened: last deleted',cr,lf,'$'
nxtdbg:	ld	hl,nxtd2
	call	pstrng
	jp	nxtfil
nxtd2:	db	cr,lf,'File open error in nxtfil',cr,lf,'$'
unint2:	ld	hl,uninms
	call	pstrng
	jp	uninit
uninms:	db	'Uninit called from nxtfil',cr,lf,'$'
;
;---------------------------------------------------------------------
;	Erase current file in spool directory
;
erafil:	call	gousr		; Go to spool user area
	ld	de,ifcb
	ld	c,delete
	call	gosys		; Try to delete spooled file
	call	bakusr		; Back to original user area
	ret
;
;---------------------------------------------------------------------
;	Return HL=address of queue entry with index no A.
;	A, BC and DE are preserved.
;
pointq:	push	af
	dec	a
	push	de
	push	bc
	call	mlt16		; HL=16*(queue no-1), or offset to entry
	ld	bc,queue	; BC=address of queue
	add	hl,bc		; HL addresses queue entry
	pop	bc
	pop	de
	pop	af
	ret
;
;---------------------------------------------------------------------
;	Routine to set up an fcb, at [HL], for a spooled file with
;	queue index no in A.
;	The fcb is of the form d:SPOOLED.nnn, where nnn is the queue
;	index no.
;
makfcb:	push	af
	ld	a,(spldrv)
	ld	(hl),a		; Set up drive code
	ld	de,filnam
	inc	hl
	ld	b,8		; 8 bytes to copy
	call	blkmov		; Copy default filename to fcb ('SPOOLED')
	pop	af
	ex	de,hl		; DE addresses filetype
	ld	l,a
	ld	h,0		; HL=index no to store
	push	de		; Save fcb pointer
	ld	de,-100
	call	places		; Count 100s (returned in A, HL contains remainder)
	pop	de		; HL addresses filetype
	ld	(de),a		; Set first digit
	inc	de
	push	de
	ld	de,-10
	call	places		; Count 10's
	pop	de
	ld	(de),a
	inc	de
	ld	a,l		; A=remainder
	add	a,'0'		; Add bias
	ld	(de),a		; Store least significant digit
	ret
;
places:	ld	c,'0'-1		; Bias less 1
ploop:	inc	c
	add	hl,de
	jp	c,ploop		; Repeat if CY=1
	call	suxhd		; HL=HL-DE
	ld	a,c		; Returned char in A
	ret			; Char in A
;
;---------------------------------------------------------------------
;	Open file at ifcb.
;	Returns A=0 if file was successfully opened, else A=0ffh.
;
openit:	call	gousr		; Go to spool directory's user area (current saved)
	ld	hl,open2
;	call	pstrng	;DEBUG
	ld	hl,ifcb
;	call	pnamef
	ld	c,cr
;	call	chrout
	ld	c,lf
;	call	chrout	;DEBUG
	ld	de,ifcb
	xor	a		; A=0
	ld	hl,12
	add	hl,de
	ld	(hl),a		; Zero fcb extent count
	ld	hl,32
	add	hl,de
	ld	(hl),a		; Zero fcb record count
	ld	c,open
	call	gosys		; Try to open file
	call	bakusr		; Back to original user area
	inc	a		; Error?
	jp	z,opnerr	; Yes - jump
	ld	a,0ffh
	ld	(openfl),a	; Open flag=TRUE
	xor	a		; A=0 indicates open OK
	ret
;
open2:	db	'Trying to open file: $'
;
;	Jump here if error occurs in opening file
;
opnerr:	ld	hl,eropen
	call	pstrng		; Print error message
	dec	a		; A=0ffh indicates open failed
	ret
;
eropen:	db	'ERROR: Unable to open spooled file$'
;
;---------------------------------------------------------------------
;	Save current user no in [userno], and set user area to that of
;	the spool directory.
;
gousr:	push	hl
	push	de
	push	bc
	push	af
	ld	e,0ffh
	ld	c,user
	call	gosys		; Get current user no
	ld	(userno),a	; Saved
	ld	a,(splusr)	; User no to set for spool directory
	ld	e,a
	ld	c,user
	call	gosys		; Go there
	pop	af
	pop	bc
	pop	de
	pop	hl
	ret
;
;---------------------------------------------------------------------
;	Restore user no stored by gousr
;
bakusr:	push	hl
	push	de
	push	bc
	push	af
	ld	a,(userno)
	ld	e,a
	ld	c,user
	call	gosys
	pop	af
	pop	bc
	pop	de
	pop	hl
	ret
;
;---------------------------------------------------------------------
;	Print filename in fcb [HL].
;	Will also print drive & user no if specified
;	ROUTINE FOR DEBUGGING ONLY
;
pnamef:	ld	a,(hl)		; A=user & drive
	push	af
	and	0f0h		; Mask out drive
	rra
	rra
	rra
	rra			; A=user no
	cp	10		; Less than 10?
	ld	b,' '		; Leading space to print if so
	jp	c,less10	; Yes - jump to print
	ld	b,'1'		; Else leading 1
	sub	10		; Subtract bias from remainder
;
less10:	ld	c,a		; Hold trailing digit in C
	push	bc
	push	hl
	ld	c,b
	call	chrout		; Print leading 1 or space
	pop	hl
	pop	bc
	ld	a,c
	add	a,'0'		; Add bias
	ld	c,a
	push	hl
	call	chrout		; Print trailing digit
	pop	hl
;
	pop	af
	and	0fh		; Mask out user no
	or	a		; Is drive the default?
	jp	z,nodrv		; If so don't print
	add	a,'A'-1		; Add bias
	ld	c,a
	push	hl
	call	chrout		; Print it
	ld	c,':'
	call	chrout		; Print drive separator
	pop	hl
nodrv:	inc	hl
	ld	b,8
	call	pfxstr		; Print filename
	ld	c,'.'
	push	hl
	call	chrout		; Print separator
	pop	hl
	ld	b,3
	jp	pfxstr		; Print extension & ret
;
;---------------------------------------------------------------------
;	Print string [HL], length specified in B.
;	Leaves HL pointing at byte beyond end of string.
;	ROUTINE FOR DEBUGGING ONLY
;
pfxstr:	ld	a,b
	or	a
	ret	z
	ld	a,(hl)
	and	07fh		; Strip high bit of each character
	ld	c,a
	push	hl
	push	bc
	call	chrout
	pop	bc
	pop	hl
	inc	hl
	dec	b
	jp	pfxstr
;
;---------------------------------------------------------------------
;	Print hex char in reg A
;	All regs preserved
;	ROUTINE FOR DEBUGGING ONLY
;
phex:	push	af
	rrca
	rrca
	rrca
	rrca			; Divide by 16
	call	pnib		; Print upper nybble
	pop	af
	jp	pnib		; Print lower nybble & ret
;
;	Subroutine: Print nybble in lower 4 bits of A
;
pnib:	push	af
	and	0fh		; Mask out upper nybble
	cp	10
	jp	nc,p10
;
;	Value 0-9
;
	add	a,'0'
	jp	prn
;
;	Value 10-15
;
p10:	add	a,'A'-10
prn:	push	hl
	push	de
	push	bc
	ld	c,a
	call	chrout		; Print nybble in hex
	pop	bc
	pop	de
	pop	hl
	pop	af
	ret
;
;---------------------------------------------------------------------
;	Compare HL & DE.
;	Returns Z=1 if HL=DE, CY=1 if HL<DE.
;
cmphd:	ld	a,h
	cp	d		; Compare high bytes
	ret	nz		; Z=0 if H<>D, CY=1 if H<D
	ld	a,l
	cp	e		; Compare low bytes
	ret
;
;---------------------------------------------------------------------
;	Block move routine.
;	Moves B bytes from [DE] to [HL]
;
blkmov:	ld	a,(de)
	ld	(hl),a
	inc	de
	inc	hl
	dec	b
	jp	nz,blkmov
	ret
;
;---------------------------------------------------------------------
;	Routine to increment DE by 128
;
incde:	push	hl
	ld	hl,128
	add	hl,de
	ex	de,hl
	pop	hl
	ret
;
;---------------------------------------------------------------------
;	Routine to multiply A by 128, returning result in DE.
;
mlt128:	ld	de,0
mult2:	or	a		; Test multiplier
	ret	z		; Ret if 0
	call	incde		; Add 128 to DE
	dec	a		; Decrement counter
	jp	mult2		; Repeat
;
;---------------------------------------------------------------------
;	Routine to multiply A by 16, returning result in HL.
;	DE & A corrupted.
;
mlt16:	ld	hl,0
	ld	de,16
mlt162:	or	a
	ret	z
	add	hl,de
	dec	a
	jp	mlt162
;
;---------------------------------------------------------------------
;	Subtract DE from HL, result in HL.
;
suxhd:	push	de
	push	af
	ld	a,e		; Low byte
	cpl
	ld	e,a		; Complemented
	ld	a,d
	cpl
	ld	d,a		; DE now complemented
	inc	de		; DE negated (two's complement form)
	pop	af
	add	hl,de		; HL=HL-original DE
	pop	de
	ret
;
;---------------------------------------------------------------------
;	BIOS Wboot Intercept Routine.
;	All calls to BIOS Wboot are routed here.
;	This routine clears the disk lock flag (if set) and
;	calls the BIOS warm boot routine. 
;	If the finish flag is set, this routine will also try
;	to restore the BIOS jump table - this will fail if a
;	competing process which modified the table is still
;	active.
;
wboot2:	ld	a,(finish)	; Waiting to uninstall?
	or	a
	call	nz,uninit	; Yes - try to restore BIOS jump table
	ld	a,(qnow)
	or	a		; Queue empty?
	call	z,uninit	; Yes - try to uninstall
	xor	a
	ld	(lockfl),a	; RSX Disk Lock = FALSE
	ld	(bdosfl),a	; Reentrancy flag = FALSE
	jp	bios		; Call BIOS wboot - address filled in by init
nwboot	equ	$-2
;
;---------------------------------------------------------------------
;	BIOS Const Intercept Routine.
;	All calls to BIOS Const are routed here.
;	This routine calls the BIOS Const routine, as well as printing
;	a character from the input buffer (if available & printer ready).
;	
const2:	ld	a,(nospol)
	or	a		; Spool lockout flag TRUE?
	jp	nz,const4	; Yes - so don't alter stack/vars - call direct
	ld	(oldhl),hl
	ld	hl,0
	add	hl,sp
	ld	(oldstk),hl	; Save user/BDOS stack
	ld	sp,stack
	push	de
	push	bc
	call	const3		; Maybe print a byte - and call BIOS const
	pop	bc
	pop	de
	ld	hl,(oldstk)
	ld	sp,hl		; Restore stack
	ld	hl,(oldhl)	; & HL
	ret
;
const3:	call	splout		; Maybe print a byte from the input buffer
const4:	jp	bios		; Call BIOS const - result in reg A
nconst	equ	$-2
;
;---------------------------------------------------------------------
;	BIOS Conin Intercept Routine.
;	All calls to BIOS Conin are routed here.
;	This routine polls the BIOS Conin routine, checking for a waiting
;	keypress, while printing chars from the current buffer. When
;	a keypress is available, it is read and returned.
;
conin2:	ld	a,(nospol)
	or	a		; Spool lockout flag TRUE?
	jp	nz,conin4	; Yes - don't disturb our stack - call direct
	ld	(oldhl),hl
	ld	hl,0
	add	hl,sp
	ld	(oldstk),hl
	ld	sp,stack
	push	de
	push	bc
conin3:	call	const3		; Print a char & get console input status
	or	a		; Keypress ready?
	jp	z,conin3	; No, so continue to poll
;
	call	conin4		; Else read waiting keypress
;
	pop	bc
	pop	de
	ld	hl,(oldstk)
	ld	sp,hl
	ld	hl,(oldhl)
	ret
;
conin4:	jp	bios		; Call BIOS Conin & ret
nconin	equ	$-2
;
;---------------------------------------------------------------------
;	BIOS List Intercept Routine.
;	All calls to BIOS List are routed here.
;	This routine simply returns, so as not to mess up the printer
;	output. Note that eventually it may be directed to a file, or
;	hang the system until SPOOL is finished.
;
list2:	ld	a,(finish)
	or	a
	ret	z		; If false, spooler working - don't let it thru
				; Else pass on
lstchr:	jp	bios		; To BIOS List
nlist	equ	$-2
;
;---------------------------------------------------------------------
;	BIOS Listst Intercept Routine.
;	All calls to BIOS Listst are routed here.
;	This routine simply returns 0 (not ready), for compatibility
;	with the above.
;
lstst2:	ld	a,(finish)
	or	a
	ret	z		; If spooler working, return 0 (printer busy)
				; Else pass on
lstat:	jp	bios		; To BIOS Listst
nlstst	equ	$-2
;
;---------------------------------------------------------------------
;	Print '$' teminated string [HL] to console.
;	BC & DE preserved
;
pstrng:	ld	a,(hl)
	cp	'$'
	ret	z
	push	hl
	push	de
	push	bc
	ld	c,a
	call	chrout
	pop	bc
	pop	de
	pop	hl
	inc	hl
	jp	pstrng
;
;---------------------------------------------------------------------
;	Call BIOS Conout
;
chrout:	jp	bios
nconou	equ	$-2
;
;---------------------------------------------------------------------
;	Uninit routine
;
;	This routine restores the BIOS jump table to its original state, 
;	as if SPOOL had never been used, and sets the RSX header remove 
;	flag so that the CCP will remove the RSX at the next warm boot.
;	A message is also printed.
;	Note that if another process (eg GET, PUT, SUBMIT) has modified
;	any of our BIOS jumps, the spooler can't restore the BIOS jump
;	table until the competing process has also finished - it lies
;	dormant in the meantime, checking whether the other process
;	has finished at every warm boot.
;	
uninit:	ld	a,(remove)
	or	a
	ret	nz		; Not installed - so no action
;
	dec	a		; A=0ffh
	ld	(finish),a	; Set flag to unhook BDOS/BIOS if possible,
	ld	(nospol),a	; And inactivity flag
;
	call	biochk		; Are our intercepted BIOS jumps as we left them?
	or	a		; NO - another process has diverted, so can't restore
	ret	z		; Yet - meanwhile spooler is dormant.
;
	ld	a,0ffh
	ld	(remove),a	; Set RSX remove flag
;
	call	rstjmp		; Restore BIOS jump table
;
	ld	hl,splend
	call	pstrng		; Print completion string
;
	ld	hl,(nbdos)	; BDOS entry point jump addr
	ex	de,hl
	ld	hl,(bdose)
	ld	(hl),e
	inc	hl
	ld	(hl),d		; Restore BDOS entry point jump addr
	ret
;
splend:	db	bel,cr,lf,'SPOOLER uninstalled',cr,lf,'$'
;
;---------------------------------------------------------------------
;	Compare BIOS jump table entries for wboot, const, conin
;	list and listst with those setby spooler - returns A=0ffh
;	if same, A=00h if not.
;
biochk:	
b17:	ld	hl,(bios+4)	; HL=current wboot jump address
	ld	de,wboot2	; That's what we set it to
	call	cmphd		; Are they still the same?
	jp	nz,differ	; NO - so return FALSE - can't restore jumps yet
;
b18:	ld	hl,(bios+7)	; Check const jump
	ld	de,const2
	call	cmphd
	jp	nz,differ
;
b19:	ld	hl,(bios+10)	; Check conin jump
	ld	de,conin2
	call	cmphd
	jp	nz,differ
;
b20:	ld	hl,(bios+16)	; Check list jump
	ld	de,list2
	call	cmphd
	jp	nz,differ
;
b21:	ld	hl,(bios+46)	; Check listst jump
	ld	de,lstst2
	call	cmphd
	ld	a,0ffh
	ret	z		; A=0ffh implies jump table not changed
;
differ:	xor	a		; A=0 implies BIOS jump table changed
	ret
;
;---------------------------------------------------------------------
;	Restore BIOS jump table to its original state.
;
rstjmp:	ld	hl,(nwboot)
b12:	ld	(bios+4),hl	; Restore BIOS Wboot jump
;
	ld	hl,(nconst)
b13:	ld	(bios+7),hl	; Restore Const jump
;
	ld	hl,(nconin)
b14:	ld	(bios+10),hl	; Restore Conin jump
;
	ld	hl,(nlist)
b15:	ld	(bios+16),hl	; Restore List jump
;
	ld	hl,(nlstst)
b16:	ld	(bios+46),hl	; Restore Listst jump
;
	ret
;
;---------------------------------------------------------------------
;	Scratch pad area
;
spldrv:	ds	1		; Drive of spool directory 
splusr:	ds	1		; User no
userno:	ds	1		; Temporary storage for current user no
lockfl:	db	0		; Disk access lockout flag
bdosfl:	db	0		; "BDOS call in progress" flag (prevents re-entrancy)
openfl:	db	0		; File open flag
nospol:	db	0ffh		; BDOS & BIOS Intercept lockout flag
finish:	db	0		; Spooler finished flag - if true, waiting to uninstall
qnow:	db	0		; Queue no of current file
qnext:	db	1		; Next free queue entry
qmax:	db	qentry		; Max no of queue entries
queue:	ds	16*qentry
				; Spool queue
;
;	SCB parm blocks
;
scb3c:	db	03ch,0		; Get DMA addr
scb4a:	db	04ah,0		; Get multi sector count
scb18:	db	018h,0		; Get CCP flags
;
;	BDOS Intercept Scratch Variables
;
bdose:	ds	2		; BDOS entry point jump addr (+1)
bdosfn:	ds	1		; BDOS function no
bdosde:	ds	2		; BDOS call parms: reg DE
bdostk:	ds	2		; Stack on entry to BDOS intercept
;
	ds	50
stack2	equ	$		; Temporary stack for internal use
;
;	BIOS Intercept Scratch Variables
;
oldhl:	ds	2
oldstk:	ds	2
cpmdma:	ds	2
scount:	ds	1
;
;	File Buffer Variables
;
filnam:	db	'SPOOLED '
				; Default filename for spooled files
ifcb:	ds	33
icount:	dw	0000h
iptr:	ds	2
;
;	Stack Area
;
	ds	50
stack	equ	$
;
;---------------------------------------------------------------------
;	Start of disk buffer - overwrites initialisation routines
;	once RSX has been successfully installed.
;
ibuff	equ	$
;
;---------------------------------------------------------------------
;	Initialise RSX and install system intercept hooks
;
init:	ld	a,(de)
	ld	l,a
	inc	de
	ld	a,(de)
	ld	h,a		; HL=BDOS entry point addr (required by init)
	inc	de
	ld	a,(de)
	ld	(spldrv),a	; Set up drive for spool directory
	inc	de
	ld	a,(de)
	ld	(splusr),a	; & user no
	xor	a
	ld	(remove),a	; Else make RSX "permanent"
;
;	Correct references to BIOS 
;
	ld	a,(bios+2)	; A=high byte of BIOS wboot entry
	ld	(b1+2),a
	ld	(b2+2),a
	ld	(b3+2),a
	ld	(b4+2),a
	ld	(b5+2),a
	ld	(b6+2),a
	ld	(b7+2),a
	ld	(b8+2),a
	ld	(b9+2),a
	ld	(b10+2),a
	ld	(b11+2),a
	ld	(b12+2),a
	ld	(b13+2),a
	ld	(b14+2),a
	ld	(b15+2),a
	ld	(b16+2),a
	ld	(b17+2),a
	ld	(b18+2),a
	ld	(b19+2),a
	ld	(b20+2),a
	ld	(b21+2),a
;
;---------------------------------------------------------------------
;	All references to BIOS correct: now splice intercept routines
;	into the BIOS jump table (and BDOS entry point jump at [HL]).
;
	inc	hl		; Go past the JMP
	ld	(bdose),hl	; Save addr of entry point jump addr
	push	hl
	ld	e,(hl)
	inc	hl
	ld	d,(hl)		; DE=BDOS entry point jump addr
	ex	de,hl		; To HL
	ld	(nbdos),hl	; Save in RSX BDOS call routine
	ld	de,rbase
	pop	hl
	ld	(hl),e
	inc	hl
	ld	(hl),d		; Store "rbase" intercept addr in BDOS entry jump
;
b1:	ld	hl,(bios+4)	; Address of BIOS wboot jump
	ld	(nwboot),hl	; Saved
	ld	hl,wboot2
b2:	ld	(bios+4),hl	; Store address of wboot2 routine in BIOS jump
;
b3:	ld	hl,(bios+7)
	ld	(nconst),hl
	ld	hl,const2
b4:	ld	(bios+7),hl	; Const2 routine intercepts BIOS const jump
;
b5:	ld	hl,(bios+10)
	ld	(nconin),hl
	ld	hl,conin2
b6:	ld	(bios+10),hl	; Conin2 routine intercepts BIOS conin jump
;
b7:	ld	hl,(bios+13)
	ld	(nconou),hl	; Conout addr required for messages etc
;
b8:	ld	hl,(bios+16)
	ld	(nlist),hl
	ld	hl,list2
b9:	ld	(bios+16),hl	; List2 routine intercepts BIOS list jump 
;
b10:	ld	hl,(bios+46)
	ld	(nlstst),hl
	ld	hl,lstst2
b11:	ld	(bios+46),hl	; Lstst2 routine intercepts BIOS listst jump
;
	ld	hl,mesint
	jp	pstrng		; Print initialisation message - & ret
;
mesint:	db	'SPOOLER RSX installed',cr,lf,'$'
;
endint	equ	$		; Defines end of init routines for buffer size
;
;---------------------------------------------------------------------
;	Rest of disk buffer follows - must reserve enough space for
;	all of it, taking into account the space within init.
;
	ds	(sectrs*128)-(endint-ibuff)
;
;---------------------------------------------------------------------
;	End of disk buffer
;
endbuf	equ	ibuff+sectrs*128
