	zpage	r0
	zpage	r1
	zpage	r2
	zpage	r3

MAXARGS equ 8
MAXLEN  equ 80

	global initmainargs

	section	rodata
pname:
	db	"n/a"
	db	0
	section	bss
argv:
	reserve	(MAXARGS+1)*2
buf:
	reserve MAXLEN+1

	section text
initmainargs:
	lda	#<pname
	sta	argv
	lda	#>pname
	sta	argv+1
	lda	#1
	ldx	#r0
	ldy	#0
	sty	r30	; quote
	jsr	0xffda
	ldx	#1
	stx	r31	; argc
	ldy	#-1
	jmp	skiploop
loop:
	lda	(r0),y
	sta	buf,y
	beq	done
	cmp	#$d
	beq	done
	cmp	#'"'
	beq	quote
	cmp	#' '
	beq	space
next:
	iny
	cpy	#MAXLEN
	beq	done
	jmp	loop
quote:
	lda	r30
	bne	endquote
	inc	r30
	jmp	next
endquote:
	dec	r30
; fallthrough
space:
	lda	r30
	bne	next
	lda	#0
	sta	buf,y
skiploop:
	iny
	cpy	#MAXLEN
	beq	done
	lda	(r0),y
	sta	buf,y
	beq	done
	cmp	#$d
	beq	done
	cmp	#' '
	beq	skiploop
	cmp	#'"'
	bne	nostartquote
	inc	r30
	iny
nostartquote:
	inc	r31
	lda	r31
	cmp	#MAXARGS
	beq	done
	clc
	tya
	adc	#<buf
	inx
	sta	argv,x
	lda	#0
	adc	#>buf
	inx
	sta	argv,x
	jmp	loop

done:
	lda	#0
	sta	buf,y
	lda	r31
	sta	r0
	lda	#0
	sta	r1
	lda	#<argv
	sta	r2
	lda	#>argv
	sta	r3
	rts
