include	clib.inc
include stdio.inc
include malloc.inc
include limits.inc

PPROC	setvbuf, fp:DPTR, buf:DPTR, tp:WORD, bsize:WORD
	push	si
	mov	ax,tp
	cmp	ax,_IONBF
	je	setvbuf_01
	cmp	ax,_IOLBF
	je	setvbuf_01
	cmp	ax,_IOFBF
	jne	setvbuf_00
	mov	ax,bsize
	cmp	ax,2
	jb	setvbuf_00
	cmp	ax,INT_MAX
	jbe	setvbuf_01
    setvbuf_00:
	mov	ax,-1
	jmp	setvbuf_END
    setvbuf_01:
	mov	ax,word ptr fp
	MMOV	dx,word ptr fp+2
  ifdef LDATA
	push	dx
  else
	push	ds
  endif
	push	ax
	MPUSH	dx
	push	ax
	MPUSH	dx
	push	ax
	call	fflush
	call	_freebuf
	pop	bx
	pop	es
	mov	ax,es:[bx.iob_flag]
	and	ax,NOT (_IOMYBUF or _IOYOURBUF or _IONBF or _IOSETVBUF or _IOFEOF or _IOFLRTN or _IOCTRLZ)
	mov	si,ax
	mov	ax,tp
	test	ax,_IONBF
	jz	setvbuf_02
	or	si,_IONBF
	mov	ax,bx
	add	ax,iob_charbuf
	MMOV	word ptr buf+2,es
	mov	word ptr buf,ax
	mov	bsize,2
	jmp	setvbuf_04
    setvbuf_02:
	mov	ax,word ptr buf
	or	ax,ax
	jnz	setvbuf_03
	push	bsize
	call	malloc
	MMOV	word ptr buf+2,dx
	mov     word ptr buf,ax
	MLES	bx,fp
	mov	ax,-1
	jz	setvbuf_END
	or	si,_IOMYBUF or _IOSETVBUF
	jmp	setvbuf_04
    setvbuf_03:
	or	si,_IOYOURBUF or _IOSETVBUF
    setvbuf_04:
	mov	es:[bx.iob_flag],si
	mov	ax,bsize
	mov	es:[bx.iob_bufsize],ax
	MMOV	dx,word ptr buf+2
	MMOV	word ptr es:[bx.iob_bp+2],dx
	MMOV	word ptr es:[bx.iob_base+2],dx
	mov     ax,word ptr buf
	mov	word ptr es:[bx.iob_bp],ax
	mov	word ptr es:[bx.iob_base],ax
	xor	ax,ax
	mov	es:[bx.iob_cnt],ax
    setvbuf_END:
	pop	si
	ret
PEND	setvbuf

	END
