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

PPROC	ftell, fp:DPTR
local   rdcnt:word, offs:word, p:dword, max:dword
	push	si
	MLES	bx,fp
	mov	si,es:[bx.iob_file]
	xor	ax,ax
	cmp	es:[bx.iob_cnt],ax
	jge	ftell_00
	mov	es:[bx.iob_cnt],ax
    ftell_00:
	push	si
	push	ax
	push	ax
	push	SEEK_CUR
	call	lseek
	cmp	dh,0
	jnl	ftell_02
    ftell_01:
	mov	ax,-1
	cwd
	jmp	ftell_END
    ftell_02:
	MLES	bx,fp
	mov	cx,es:[bx.iob_flag]
	test	cx,_IOMYBUF or _IOYOURBUF
	jnz	ftell_03
	sub	ax,es:[bx.iob_cnt]
	sbb	dx,0
	jmp	ftell_END
    ftell_03:
	xor	dx,dx
	mov	ax,word ptr es:[bx.iob_bp]
	sub	ax,word ptr es:[bx.iob_base]
	mov	word ptr offs,ax
	mov	word ptr offs+2,dx
	test	cx,_IOWRT or _IOREAD
	jnz	ftell_04
	test	cx,_IORW
	jnz	ftell_04
	mov	errno,EINVAL
	jmp     ftell_01
    ftell_04:
	mov	si,ax
	or	si,dx
	jnz	ftell_05
	mov	ax,word ptr offs
	mov	dx,word ptr offs+2
	jmp	ftell_END
    ftell_05:
	test	cx,_IOREAD
	jz	ftell_07
	cmp	es:[bx.iob_cnt],0
	jne	ftell_06
	xor	ax,ax
	cwd
	jmp	ftell_07
    ftell_06:
	mov	si,ax
	mov	ax,word ptr es:[bx.iob_bp]
	sub	ax,word ptr es:[bx.iob_base]
	add	ax,es:[bx.iob_cnt]
	xchg	ax,si
	sub	ax,si
	sbb	dx,0
    ftell_07:
	add	ax,word ptr offs
	adc	dx,word ptr offs+2
    ftell_END:
	pop	si
	ret
PEND	ftell

	END
