;--------------------------------------------------------------------------
; textin
;
; Capture a smallish text file (less than about 60 kB) from the auxiliary
; device.
;
; There is no error checking!  This proram is not meant for general
; distribution.
;--------------------------------------------------------------------------

	.z80

auxist	equ	7
auxin	equ	3
auxout	equ	4
conout	equ	1
cpm	equ	5
eof	equ	1Ah
esc	equ	1Bh
conin	equ	1
conist	equ	11
setdma	equ	26

bdos	macro	fn
	ld	c,fn
	call	cpm
	or	a
	endm

fopen	macro
	ld	de,5Ch
	bdos	19
	ld	de,5Ch
	bdos	22
	endm

fwrite	macro
	ld	de,5Ch
	bdos	21
	endm

fclose	macro
	ld	de,5Ch
	bdos	16
	endm

	aseg
	org	100h

	fopen
setbuf:
	ld	hl,capbuf
	ld	(bufadr),hl
chkcon:
	bdos	conist		; Terminate if ESC is
	jr	z,chkaux	; entered at the console
	bdos	conin
	cp	esc
	jr	z,finis
chkaux:
	bdos	auxist
	jr	z,chkcon
	bdos	auxin		; Receive a character
	ld	hl,(bufadr)	; Store it in the capture
	ld	(hl),a		;  buffer
	inc	hl		; Increment the buffer
	ld	(bufadr),hl	;  pointer
	cp	eof		; Finish when an EOF
	jr	z,finis		;  marker is received
	jr	chkaux
finis:
	ld	de,capbuf	; Write captured data
nextrec:			;  to file named on
	push	de		;  command line
	bdos	setdma
	fwrite
	pop	hl
	ld	de,128
	add	hl,de
	ex	de,hl		; Write address to DE
	ld	hl,(bufadr)
	or	a
	sbc	hl,de
	jp	m,nextrec
	fclose
flush:				; Eat all remaining
	ld	bc,1000
nothing:
	push	bc		; Save idle counter
	bdos	auxist		; Check for auxiliary input
	pop	bc		; Recover counter
	jr	nz,sio		; Something waiting
	dec	bc		; Decrement idle counter
	ld	a,b
	or	c
	jr	z,done		; Exit if limit was reached
	jr	nothing
sio:
	bdos	auxin
	jr	flush
done:
	ld	hl,msg		; Point at message
	push	hl		; Precondition stack
emit:
	pop	hl		; Fetch message pointer
	ld	a,(hl)		; Load character
	inc	hl		; Increment pointer
	push	hl		; Save it for next time
	or	a		; Check for terminator
	jr	nz,putc		; Continue if more to go
	rst	0
putc:
	push	af		; Save output character
	ld	e,a		; Send it to the auxiliary
	bdos	auxout		;  output device
	pop	af		; Retrieve output character
	ld	e,a		; Send a copy to the console
	bdos	conout
	jr	emit		; Loop through message
msg:
	defb	'Complete',13,10,0

	rst	0
bufadr:
	defs	2
capbuf:
	end
