IF elzet
inchr0:	lda	elbflg		;Check flag if character in input buffer
	ora	a
	jnz	inchr2		;If so go read it
ENDIF;elzet


IF elzet
inchr2:	call	elread		;Get next char out of input buffer
ENDIF;elzet


IF elzet
elread:	push	d
	push	h
	lhld	elrptr		;Increment read pointer
	inx	h
	mov	a,m		;Get char
	push	psw		; and save it
	xchg
	di			;Disable interrupt of further input chars
	lhld	elwptr		;Compare read and write pointer
	stc			;Clear
	cmc			; carry flag
;* SBC HL,DE			;Sorry, but I couldn't resist.
	db	0EDH,052H	;Op-code for above Z80 command
	xchg
	jnz	elrea1		;If read hasn't caught up with write yet, fine.
	lxi	h,elbuff-1	;Else reset both pointers
	shld	elwptr		; to beginning of buffer
	xra	a		;Clear availability flag
	sta	elbflg
elrea1:	shld	elrptr
	shld	elrptr
	pop	psw		;Return with char in accu
	pop	h
	pop	d
	shld	elrptr
	ei			;Enable further interrupts
;* RETI				;I don't know if it's really necessary 
	db	0EDH,04DH	;Op-code for above Z80 command
ENDIF;elzet


IF elzet
;Interrupt service routine for reading input character from SIO
; and storing it in buffer queue.
elints:	di			;Disable interrupt of further input chars
	push	d
	push	h
	push	psw
	lhld	elwptr		;Increment write pointer
	inx	h
	xchg			;Check against end of buffer
	lhld	elbend
	stc			;Clear
	cmc			; carry flag
;* SBC HL,DE			;Sorry again.
	db	0EDH,052H	;Op-code for above Z80 command
	xchg			;Restore write pointer
	cc	elmove		;If at end of buffer go and reshuffle
	in	mnport		;Read character from SIO
	mov	m,a		;Store it in buffer
	shld	elwptr		;Store new write pointer
	mvi	a,0FFH		;Set availability flag
	sta	elbflg
elintx:	pop	psw
	pop	h
	pop	d
	ei			;Enable further interrupts
;* RETI				;Again, I don't know ...
	db	0EDH,04DH	;Op-code for above Z80 command

;If possible move remaining input up to beginning of buffer
elmove:	push	d		;Save write pointer
	lhld	elrptr		;Check if read pointer still at beginning
	xchg
	lxi	h,elbuff-1
	stc			;Clear
	cmc			; carry flag
;* SBC HL,DE			;What can I say?
	db	0EDH,052H	;Op-code for above Z80 command
	pop	h		;Balance stack before beating it
	jz	elfull		;If buffer full go apologize 
	stc			;Else compute length of remaining input
;* SBC HL,DE			;Don't yell at me.
	db	0EDH,052H	;Op-code for above Z80 command
	push	b		;Save BC pair before using it.
	mov	b,h		;Store length in BC
	mov	c,l
	lxi	h,elbuff	;Set up target
	xchg
	lhld	elrptr		; and source address
	inx	hl
	call	mover		; and move it!
	xchg			;Store the new write pointer
	shld	elwptr
	lxi	h,elbuff-1	;Update read pointer
	pop	b		;Restore that one
	ret			; and proceed

elmes1:	db 	'Input buffer overflow. Characters might be lost.',cr,lf,'$'
elfull:	lxi	d,elmes1
	call	prtstr
	pop	h		;Discard return address
	jmp	elintx		;Skip input part
ENDIF;elzet
