include	clib.inc
include	io.inc
include	errno.inc

PPROC	write, h:WORD, b:DWORD, l:WORD
local	lb[1026]:BYTE
local	count:WORD
local	result:WORD
	push	si
	push	di
	mov	ax,l
	test	ax,ax
	jnz	write_00
	jmp	write_15
    write_00:
	mov	bx,h
	cmp	bx,_NFILE_
	jb	write_01
	xor	ax,ax
	mov	doserrno,ax
	mov	errno,EBADF
	dec	ax
	jmp	write_15
    write_01:
	test	[bx+_osfile],FH_APPEND
	jz	write_02
	push	bx
	xor	ax,ax
	push	ax
	push	ax
	push	SEEK_END
	call	lseek
    write_02:
	xor	ax,ax
	mov	result,ax
	mov	count,ax
	mov	bx,h
	test	[bx+_osfile],FH_TEXT
	jnz	write_03
	jmp	write_10
    write_03:
	les	si,b
    write_04:
	mov	ax,si
	sub	ax,WORD PTR b
	cmp	ax,l
	jb	write_05
	jmp	write_11
    write_05:
	lea	di,lb
    write_06:
	lea	dx,lb
	mov	ax,di
	sub	ax,dx
	cmp	ax,1024
	jnb	write_08
	mov	ax,si
	sub	ax,WORD PTR b
	cmp	ax,l
	jnb	write_08
	mov	al,es:[si]
	cmp	al,10
	jne	write_07
	mov	BYTE PTR [di],13
	inc	di
    write_07:
	mov	[di],al
	inc	si
	inc	di
	inc	count
	jmp	write_06
    write_08:
	push	h
	push	ss
	lea	ax,lb
	push	ax
	mov	dx,di
	sub	dx,ax
	push	dx
	call	oswrite
	test	ax,ax
	jz	write_09
	lea	cx,lb
	mov	dx,di
	sub	dx,cx
	cmp	ax,dx
	jb	write_11
	jmp	write_04
    write_09:
	inc	result
	jmp	write_11
    write_10:
	push	h
	pushm	b
	push	l
	call	oswrite
	test	ax,ax
	jz	write_09
	mov	result,0
	mov	count,ax
    write_11:
	mov	ax,count
	test	ax,ax
	jnz	write_15
	cmp	ax,result
	jne	write_13
	cmp	doserrno,5 	; access denied
	jne	write_12
	mov	errno,EBADF
    write_12:
	mov	ax,-1
	jmp	write_15
    write_13:
	mov	bx,h
	test	[bx+_osfile],FH_DEVICE
	jz	write_14
	les	bx,b
	cmp	BYTE PTR es:[bx],26
	jne	write_14
	xor	ax,ax
	jmp	write_15
    write_14:
	mov	errno,ENOSPC
	mov	doserrno,0
	mov	ax,-1
    write_15:
	pop	di
	pop	si
	ret
PEND	write

	END
