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

	extrn	__STDIO:word
	extrn	_iob:	byte
	extrn	_stdbuf:word

stdout	equ offset _DATA:_iob + size S_FILE
stderr	equ stdout + size S_FILE

PPROC	_stbuf, fp:dword
	les	bx,fp
	invoke	isatty, es:[bx.iob_file]
	test	ax,ax
	jz	_stbuf_END
	les	bx,fp
	xor	ax,ax
	mov	dx,ax
	cmp	bx,stdout
	je      _stbuf_00
	cmp	bx,stderr
	jne	_stbuf_END
	inc	dx
    _stbuf_00:
	mov	cx,es:[bx.iob_flag]
	and	cx,_IOMYBUF or _IONBF or _IOYOURBUF
	jnz	_stbuf_END
	or	cx,_IOWRT or _IOYOURBUF or _IOFLRTN
	mov	es:[bx.iob_flag],cx
	push	di
	add	dx,dx
	mov	di,dx
	add	di,offset _stdbuf
	mov	ax,[di]
	mov	dx,[di+2]
	mov	cx,_INTIOBUF
	or	ax,ax
	jnz	_stbuf_01
	invoke	malloc, cx
	mov	[di],ax
	mov	[di+2],dx
	les	bx,fp
	mov	cx,_INTIOBUF
	jnz	_stbuf_01
	mov	ax,bx
	mov	dx,es
	add	ax,iob_charbuf
	mov	cx,2
    _stbuf_01:
	pop	di
	mov     word ptr es:[bx.iob_bp],ax
	mov     word ptr es:[bx.iob_bp+2],dx
	mov     word ptr es:[bx.iob_base],ax
	mov     word ptr es:[bx.iob_base+2],dx
	mov	es:[bx.iob_bufsize],cx
    _stbuf_02:
	mov	ax,1
    _stbuf_END:
	ret
PEND	_stbuf

	END
