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

PPROC	fflush, FP:DPTR
	push	si
	push	di
	MLES	bx,FP
	xor	si,si
	assert	bx,si,jne,"fflush"
	mov	ax,es:[bx.iob_flag]
	mov	di,ax
	and	ax,_IOREAD or _IOWRT
	cmp	ax,_IOWRT
	jne	fflush_02
	test	di,_IOMYBUF or _IOYOURBUF
	jz	fflush_02
	mov	ax,word ptr es:[bx.iob_bp]
	sub	ax,word ptr es:[bx.iob_base]
	cmp	ax,0
	jle	fflush_01
    fflush_00:
	push	es
	push	bx
	push	ax
	push	es:[bx.iob_file]
	pushm	es:[bx.iob_base]
	push	ax
	call	write
	pop	dx
	pop	bx
	pop	es
	cmp	ax,dx
	jne	fflush_02
	mov	ax,es:[bx.iob_flag]
	test	ax,_IORW
	jz	fflush_02
	and	ax,not _IOWRT
	jmp	fflush_02
    fflush_01:
	or	di,_IOERR
	mov	es:[bx.iob_flag],di
	mov	si,-1
    fflush_02:
	movmx	es:[bx.iob_bp],es:[bx.iob_base]
	xor	ax,ax
	mov	word ptr es:[bx.iob_cnt],ax
    fflush_04:
	mov	ax,si
	pop	di
	pop	si
	ret
PEND	fflush

	END
