	.include "os9.d"
	.global	__ehdr
	.global	__etext
	.global	__bsslen
	.global	__main

	.text

	.global	_start
_start:
; u,dp = start of data segment
; y = end of data segment, end of command line, top of stack
; s = start of command line arguments

	pshs	y
	bsr	init			; init data, relocate

	ldx	,s			; x: end of cmdline + 1, s: cmdline
	clra
	clrb
	std	,s			; last argv[] is NULL
	incb				; b: argc has at least the module name

	; skip white-space between arguments
.1:	lda	,-x
	beq	.3			; hit the start of the cmdline
	cmpa	#32
	bls	.1

	; found end of an argument
	clr	1,x			; terminate it with \0
	incb				; argc++
.2:	lda	,-x
	cmpa	#32
	bhi	.2

	; save pointer to argument's start address in argv[]
	leay	1,x
	pshs	y
	tsta
	bne	.1			; find next argument

	; put module name as a real string on the stack
.3:	pshs	d			; save argc in argv[0] position
	leay	,s			; y: &argv[0]
	leax	__ehdr-13,pcr		; module header
	ldd	4,x			; module name offset
	leax	d,x			; x: module name
	clrb
.4:	incb				; b: module name length
	lda	,x+
	bpl	.4
	clr	,-s			; argv[0] terminator
.5:	lda	,-x
	anda	#0x7f
	sta	,-s
	decb
	bne	.5
	ldd	,y			; d: argc
	sts	,y			; set argv[0] as module-name

	; call vclib's __main(argc,argv)
	pshs	y
	lbsr	__main

	; __main returned? Call __exit(0)
	clrb


	.global	__exit
__exit:
; b: return code

	os9	F$Exit


init:
; u = start of data segment

	pshs	u

	; initialize data
	leay	__etext,pcr
	ldx	,y++			; size of initdata in bytes
	beq	.2
.1:	lda	,y+
	sta	,u+
	leax	-1,x
	bne	.1

	; clear bss
.2:	ldx	#__bsslen
	beq	.4
.3:	clr	,u+
	leax	-1,x
	bne	.3

.4:	puls	u			; restore U as data base

	; relocate
	leax	__ehdr-13,pcr		; text-base for data-text relocs
	bsr	relocate
	leax	,u			; data-base for data-data relocs

relocate:
; u = data base
; x = base to add
; y = ptr to number of relocs, relocs-offsets...
; -> y updated, u will be preserved

	leas	-4,s
	stx	2,s			; save addend
	ldd	,y++			; number of relocs
	beq	.2

.1:	std	,s
	ldx	,y++			; data-offset to fix
	tfr	x,d
	ldd	d,u
	addd	2,s
	exg	d,x
	stx	d,u

	ldd	,s
	subd	#1
	bne	.1

.2:	leas	4,s
	rts
