; this is a simple terminal emulator for the CPM2.2
; requires that xbios be loaded(IObyte inplemented)
; uses IOByte to switch CON: between TTY: and UC1:
; this allows standard CPM calls to be used to do all IO

; on z80 emulator-
;  TTY is (TTY)Generic DEV0
;  UC1 is (SerA)Generic DEV14
; CRT is the Screen/Keyboard and UC1 is the Host system

;      	LST: 	PUN:	RDR:	CON:	
;	10	00	00	01
;------------------------------------
;00	tty:	tty:	tty:	tty:
;01	crt:	ptp:	ptr:	crt:
;10	lpt:	up1:	ur1:	bat:
;11	ul1:	up2:	ur2:	uc1:

	z80

BDOS	equ	5

DIO	equ	6
GetIOB	equ	7
SetIOB	equ	8
PrtStr	equ	9
GetSTS	equ	11

CONmask	equ	0xfc
TTY	equ	0x00
UC1	equ	0x03	

CR	equ	0x0d
LF	equ	0x0a
TILDE	equ	0x7e

	org	0x100
Entry	jmp	start

OpenMsg	db	"Terminal Program - Type a Tilde to Exit",cr,lf
	db	"      CON:=TTY to CON:=UC1",cr,lf
	db	" For Z80 Emulator-DEV0(TTY) to DEV14(serialA)",cr,lf,'$',0
NoXbiosMsg	db	cr,lf,"  XBIOS NOT detected - Exiting...",cr,lf,'$',0

OldIOB	db	0
OldStack	dw	0

Start:
	sspd	OldStack
	mvi	c,GetIOB
	call	BDOS
	sta	OldIOB

	lxi	de,OpenMsg
	mvi	c,PrtStr
	call	BDOS
; test for Xbios
	lixd	1
	mov	a,-1(ix)
	cmp	5(ix)
	jz	NoXbios

TxLoop:
	mvi	e,TTY	;CON:=TTY
	call	select
TxLoop2:
	mvi	e,0xff	;raw input
	mvi	c,DIO
	call	BDOS	;A=char or 0x00
	cmpi	0	;char?
	jrz	Next	;no char

	cmpi	TILDE	;escape is TILDE
	jrz	Exit

	mvi	e,UC1	;CON:=UC1
	call	select
	
	mov	e,a
	mvi	c,DIO
	call	BDOS
	
	jmpr	Next2
Next:
	mvi	e,UC1	;CON:=UC1
	call	select
Next2:
	mvi	e,0xff	;raw input
	mvi	c,DIO
	call	BDOS
	cmpi	0	;char?
	jrz	TxLoop	;no char

	mvi	e,TTY	;CON:=TTY
	call	select

	mov	e,a
	mvi	c,DIO
	call	BDOS
	jmpr	TxLoop2


Exit:
	lda	OldIOB
	mov	e,a
	mvi	c,SetIOB
	call	BDOS
	lspd	OldStack
	ret
NoXbios:
	lxi	d,NoXbiosMsg
	mvi	c,PrtStr
	call	bdos
	jmp	exit

;enter with b=CON:(either TTY or UC1)
;all registers preserved
Select:
	push	psw
	push	bc
	push	de
	mvi	c,GetIOB
	call	BDOS
	ani	CONmask
	ora	e
	mov	e,a
	mvi	c,SetIOB
	call	BDOS
	pop	de
	pop	bc
	pop	psw
	ret

	dw	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
Stack
	end	entry