include	clib.inc
include io.inc
include errno.inc
include string.inc
include stdio.inc

PPROC	fwrite, buf:DPTR, rsize:word, num:word, fp:DPTR
local	total:word
local	bufsize:word
	push	si
	push	di
	mov	si,word ptr buf
	mov	ax,rsize
	mul	num
	mov	di,ax
	mov	total,ax
	test	ax,ax
	jz	fwrite_07
	MLES	bx,fp
	mov	dx,_MAXIOBUF
	mov	ax,es:[bx.iob_flag]
	and	ax,_IOMYBUF or _IONBF or _IOYOURBUF
	jz	fwrite_01
	mov	dx,es:[bx.iob_bufsize]
    fwrite_01:
	mov	bufsize,dx
    fwrite_02:
	xor	ax,ax
	cmp	di,ax
	je	fwrite_06
	mov	ax,es:[bx.iob_flag]
	and	ax,_IOMYBUF or _IOYOURBUF
	jz	fwrite_04
	mov	ax,es:[bx.iob_cnt]
	test	ax,ax
	jz	fwrite_04
	cmp	ax,di
	jb	fwrite_03
	mov	ax,di
    fwrite_03:
	push	ax
	MMOV	dx,word ptr es:[bx.iob_bp+2]
	MPUSH	dx
	push	word ptr es:[bx.iob_bp]
	MPUSH	dx
	push	si
	push	ax
	call	memcpy
	MLES	bx,fp
	pop	ax
	sub	di,ax
	sub	es:[bx.iob_cnt],ax
	add	word ptr es:[bx.iob_bp],ax
	add	si,ax
	jmp	fwrite_02
    fwrite_04:
	mov	ax,di
	cmp	ax,bufsize
	jb	fwrite_05
	mov	ax,es:[bx.iob_flag]
	and	ax,_IOMYBUF or _IOYOURBUF
	jz	fwrite_04B
	MPUSH	es
	push	bx
	call	fflush
	test	ax,ax
	jz	fwrite_04B
    fwrite_04A:
	mov	ax,total
	sub	ax,di
	xor	dx,dx
	div	rsize
	jmp	fwrite_07
    fwrite_04B:
	mov	ax,di
	mov	cx,bufsize
	test	cx,cx
	jz	fwrite_04C
	xor	dx,dx
	div	cx
	mov	ax,di
	sub	ax,dx
    fwrite_04C:
	push	ax
	MLES	bx,fp
	push	es:[bx.iob_file]
	MPUSH	word ptr buf+2
	push	si
	push	ax
	call	write
	pop	dx
	MLES	bx,fp
	cmp	ax,-1
	jne	fwrite_04E
    fwrite_04D:
	or	es:[bx.iob_flag],_IOERR
	jmp	fwrite_04A
    fwrite_04E:
	sub	di,ax
	add	si,ax
	cmp	ax,dx
	jb	fwrite_04D
	jmp	fwrite_02
    fwrite_05:
	mov	dx,es
	mov	cx,bx
	MLES	bx,buf
	mov	al,es:[si]
	mov	ah,0
	push	ax
	push	dx
	push	cx
	call	_flsbuf
	cmp	ax,-1
	je	fwrite_04A
	inc	si
	dec	di
	MLES	bx,fp
	mov	ax,es:[bx.iob_bufsize]
	cmp	ax,0
	jg	fwrite_05A
	mov	ax,1
    fwrite_05A:
	mov	bufsize,ax
	jmp	fwrite_02
    fwrite_06:
	mov	ax,num
    fwrite_07:
	pop	di
	pop	si
	ret
PEND	fwrite

	END
