	title 'Character I/O handler for z80 chip based system'

; Character I/O for the Modular CP/M 3 BIOS

	public	?cinit,?ci,?co,?cist,?cost
	public	@ctbl

	maclib Z80	; define Z80 op codes
	maclib ports	; define port addresses
	maclib modebaud	; define mode bits and baud equates

max$devices	equ 4	

	cseg

?cinit:
	xra	a
	ret

?ci:		; character input

	mov a,b ! cpi 4 ! jnc null$input ; can't read from printer or above
ci1:
	call ?cist ! jz ci1		; wait for character ready
	dcr c ! inp a			; get data
	ani 7Fh				; mask parity
	ret

null$input:
	mvi a,1Ah			; return a ctl-Z for no device
	ret

?cist:		; character input status

	mov a,b ! cpi 4 ! jnc null$status ; can't read from printer or above
	mov l,b ! mvi h,0		; make device number 16 bits
	lxi d,data$ports ! dad d	; make pointer to port address
	mov c,m ! inr c			; get SIO status port
	inp a				; read from status port
	ani 2			; isolate RxRdy
	rz				; return with zero
	ori 0FFh
	ret

null$status:
	xra a ! ret

?co:		; character output
	mov a,b ! cpi 5 	;all above 5 is null
	jnc null$output
	mov a,c ! push psw		; save character from <C>
	push b				; save device number
co$spin:
	call ?cost ! jz co$spin		; wait for TxEmpty
	pop h ! mov l,h ! mvi h,0	; get device number in <HL>
	lxi d,data$ports ! dad d	; make address of port address
	mov c,m				; get port address
	pop psw ! outp a		; send data
null$output:
	ret

?cost:		; character output status
	mov a,b ! cpi 5 	;all above 5 is null
	jnc null$status
	mov l,b ! mvi h,0
	lxi d,data$ports ! dad d
	mov c,m ! inr c 
	inp a				; get input status
	ani 1 ! rz			; test transmitter empty
	ori 0FFh ! ret			; return true if ready


data$ports:		; serial base ports by physical device number
	db	07ch,07ah,070h,072h
	db	07eh,00


@ctbl	db 'TTY   '	; device 0, TTY 
	db mb$in$out+mb$serial
	db baud$none
	db 'CRT   '	; device 1, CRT 
	db mb$in$out+mb$serial 
	db baud$none
	db 'SERA  '	; device 2, Serial A 
	db mb$in$out+mb$serial 
	db baud$none
	db 'SERB  '	; device 3, Serial B 
	db mb$in$out+mb$serial 
	db baud$none
	db 'LPT   '	; device 4, Printer 
	db mb$output
	db baud$none
	db 0			; table terminator



	end
