	.include "os9.d"
	.global	errno

	.text

	.global	lseek
	; long lseek(int,long,int) SET=0, CUR=1, END=2
lseek:
	pshs	b,u

	lda	10,s			; whence-code: SET/CUR/END, LSB
	bne	.1

	; SEEK_SET
	ldx	#0			; offset from start of file, x:u=0
	leau	,x
	bra	.4

.1:	deca
	bne	.2

	; SEEK_CUR
	tfr	b,a			; a: path number
	ldb	#SS_POS
	bra	.3

	; SEEK_END
.2:	tfr	b,a			; a: path number
	ldb	#SS_SIZE

.3:	os9	I$GetStt		; current pos or file length -> x:u
	bcs	.syserr

	; x:u has whence-position: start of file, current pos or end of file.
	; Now add the 32-bit offset.
.4:	tfr	u,d
	addd	7,s
	tfr	d,u
	tfr	x,d
	adcb	6,s
	adca	5,s
	bmi	.e_inval		; negative position is illegal
	tfr	d,x
	lda	,s
	os9	I$Seek
	bcs	.syserr

	; return new 32-bit position
	lda	,s
	ldb	#SS_POS
	os9	I$GetStt
	bcs	.syserr
	tfr	u,d
	leas	1,s
	puls	u,pc

.e_inval:
	ldb	#22			; EINVAL
.syserr:
	stb	<errno+1
	ldd	#-1			; return -1L
	tfr	d,x
	leas	1,s
	puls	u,pc
