include	clib.inc
include	io.inc
include	stdio.inc

FH_EOFTEXT equ (FH_TEXT or FH_EOF)

PPROC	_filebuf, FP:DPTR
	push	si
	push	di
	MLES	si,FP
	mov	di,es:[si.iob_flag]
	test	di,_IOREAD or _IOWRT or _IORW
	jz	@F
	test	di,_IOSTRG
	jnz	@F
	test	di,_IOWRT
	jz	_filebuf_02
	or	di,_IOERR
	mov	es:[si.iob_flag],di
    @@:
	jmp	filebuf_eof
    _filebuf_02:
	or	di,_IOREAD
	test	di,_IOMYBUF or _IONBF or _IOYOURBUF
	jnz	@F
	push	es
	push	es
	push	si
	call	_getbuf
	pop	es
	jmp	_filebuf_04
    @@:
	movmx	es:[si.iob_bp],es:[si.iob_base]
    _filebuf_04:
	push	es
	push	es:[si.iob_file]
	MPUSH	word ptr es:[si.iob_base+2]
	push	word ptr es:[si.iob_base]
	push	es:[si.iob_bufsize]
	call	read
	pop	es
	mov	es:[si.iob_cnt],ax
	or	ax,ax
	jz	@F
	cmp	ax,1
	je	@F
	cmp	ax,-1
	jne	_filebuf_07
    @@:
	or	ax,ax
	mov	ax,_IOERR
	jnz	@F
	mov	ax,_IOEOF
    @@:
	or	es:[si.iob_flag],ax
	xor	ax,ax
	mov	es:[si.iob_cnt],ax
	jmp	filebuf_eof
    _filebuf_07:
	test	di,_IOWRT or _IORW
	jnz	@F
	mov	bx,offset _osfile
	add	bx,es:[si.iob_file]
	mov	al,[bx]
	and	al,FH_EOFTEXT
	cmp	al,FH_EOFTEXT
	jne	@F
	or      es:[si.iob_flag],_IOCTRLZ
    @@:
	mov	ax,es:[si.iob_bufsize]
	cmp	ax,_MINIOBUF
	jne	@F
	test	di,_IOMYBUF
	jz	@F
	test	di,_IOSETVBUF
	jnz	@F
	mov	es:[si.iob_bufsize],_INTIOBUF
    @@:
	dec	es:[si.iob_cnt]
	inc	word ptr es:[si.iob_bp]
	MLES	si,es:[si.iob_bp]
	dec	si
	mov	al,es:[si]
	mov	ah,0
    filebuf_end:
	pop	di
	pop	si
	ret
    filebuf_eof:
	mov	ax,-1
	jmp	filebuf_end
PEND	_filebuf

	END
