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

PPROC	fseek, fp:DPTR, off:dword, whence:word
	push	si
	push	di
	MMOV	si,word ptr fp+2
	NMOV	si,ds
	mov	di,word ptr fp
	mov	es,si
	mov	ax,whence
	cmp	ax,SEEK_SET
	jl	fseek_00
	cmp	ax,SEEK_END
	ja	fseek_00
	mov	dx,ax
	mov	ax,es:[di.iob_flag]
	test	ax,_IOREAD or _IOWRT or _IORW
	jnz	fseek_01
    fseek_00:
	mov	errno,EINVAL
	mov	ax,-1
	jmp     fseek_END
    fseek_01:
	push	si
	push	di
	and	ax,not _IOEOF
	mov	es:[di.iob_flag],ax
	cmp	dx,SEEK_CUR
	jne	fseek_02
	push	si
	push	di
	call	ftell
	add	word ptr off,ax
	adc	word ptr off+2,dx
	mov	whence,SEEK_SET
    fseek_02:
	call	fflush
	mov	es,si
	mov	ax,es:[di.iob_flag]
	test	ax,_IORW
	jz      fseek_03
	and	ax,not (_IOWRT or _IOREAD)
	mov	es:[di.iob_flag],ax
	jmp	fseek_04
    fseek_03:
	test	ax,_IOREAD
	jz	fseek_04
	test	ax,_IOMYBUF
	jz	fseek_04
	test	ax,_IOSETVBUF
	jnz	fseek_04
	mov	es:[di.iob_bufsize],_MINIOBUF
    fseek_04:
	push	es:[di.iob_file]
	push	word ptr off+2
	push	word ptr off
	push	whence
	call	lseek
	cmp	ax,-1
	jne	fseek_05
	cmp	dx,-1
	je	fseek_END
    fseek_05:
	xor	ax,ax
    fseek_END:
	pop	di
	pop	si
	ret
PEND	fseek

	END
