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

	extrn	_iob:byte
	extrn	__STDIO:word

stdout	equ (offset _iob + size S_FILE)
stderr	equ (stdout + size S_FILE)

PPROC	_flsbuf, char:word, fp:DPTR
	push	si
	push	di
	MLES	si,fp
	mov	di,es:[si.iob_flag]
	test	di,_IOREAD or _IOWRT or _IORW
	jz	_flsbuf_00
	test	di,_IOSTRG
	jz	_flsbuf_01
    _flsbuf_00:
	or	di,_IOERR
	mov	es:[si.iob_flag],di
	jmp	_flsbuf_EOF
    _flsbuf_01:
	test	di,_IOREAD
	jz	_flsbuf_02
	xor	ax,ax
	mov	es:[si.iob_cnt],ax
	test	di,_IOEOF
	jz	_flsbuf_00
	movmx	es:[si.iob_bp],es:[si.iob_base]
	and	di,not _IOREAD
    _flsbuf_02:
	or	di,_IOWRT
	and	di,not _IOEOF
	mov	es:[si.iob_flag],di
	xor	ax,ax
	mov	es:[si.iob_cnt],ax
	test	di,_IOMYBUF or _IONBF or _IOYOURBUF
	jnz     _flsbuf_04
	push	es
	push	es:[si.iob_file]
	call	isatty
	pop	es
	or	ax,ax
	jz	_flsbuf_04
	cmp	si,stdout
	je	_flsbuf_03
	cmp	si,stderr
	jne	_flsbuf_04
    _flsbuf_03:
	push	es
	push	es
	push	si
	call	_getbuf
	pop	es
    _flsbuf_04:
	mov	ax,di
	xor	di,di
	mov	es:[si.iob_cnt],di
	and	ax,_IOMYBUF or _IOYOURBUF
	jz	_flsbuf_07
	MMOV	ax,word ptr es:[si.iob_base+2]
	MMOV	word ptr es:[si.iob_bp+2],ax
	mov	ax,word ptr es:[si.iob_base]
	mov	di,word ptr es:[si.iob_bp]
	sub	di,ax
	inc	ax
	mov	word ptr es:[si.iob_bp],ax
	mov	ax,es:[si.iob_bufsize]
	dec	ax
	mov	es:[si.iob_cnt],ax
	xor	ax,ax
	cmp	di,0
	jle	_flsbuf_05
	push	es
	push	es:[si.iob_file]
	MPUSH	word ptr es:[si.iob_base+2]
	push	word ptr es:[si.iob_base]
	push	di
	call	write
	pop	es
	jmp	_flsbuf_06
    _flsbuf_05:
	mov	bx,offset _osfile
	add	bx,es:[si.iob_file]
	mov	dl,[bx]
	and	dl,FH_APPEND
	jz	_flsbuf_06
	push	ax
	push	es
	push	es:[si.iob_file]
	push	0
	push	0
	push	SEEK_END
	call	lseek
	pop	es
	pop	ax
    _flsbuf_06:
	mov	dx,char
	push	es
	les	bx,es:[si.iob_base]
	mov	es:[bx],dl
	pop	es
	jmp	_flsbuf_08
    _flsbuf_07:
	inc	di
	push	es:[si.iob_file]
	lea	dx,char
	push	ss
	push	dx
	push	di
	call	write
    _flsbuf_08:
	cmp	ax,di
	je	_flsbuf_09
	jmp	_flsbuf_00
    _flsbuf_09:
	mov	ax,char
	mov	ah,0
    _flsbuf_END:
	pop	di
	pop	si
	ret
    _flsbuf_EOF:
	mov	ax,-1
	jmp	_flsbuf_END
PEND	_flsbuf

	END
