include	clib.inc

	public	_argc
	public	_argv
	public	__setargv__

	extrn	C0_argc:word
	extrn	C0_argv:word

_DATA	SEGMENT

__setargv__ label word
_argc	dw ?
_argv	dw ?
	dw ?
_ip	dw ?
_si	dw ?
_di	dw ?

_DATA	ENDS

_TEXT	SEGMENT

copyargc PROC
	test	ax,ax
	jz	copyargc_00
	inc	dx
	stosb
	test	al,al
	jnz	copyargc_00
	inc	bx
    copyargc_00:
	mov	ah,al
	mov	al,0
	test	cx,cx
	stc
	jz	copyargc_02
	lodsb
	dec	cx
	sub	al,'"'
	jz	copyargc_02
	add	al,'"'
	cmp	al,'\'
	jne	copyargc_01
	cmp	BYTE PTR [si],'"'
	jne	copyargc_01
	lodsb
	dec	cx
    copyargc_01:
	test	si,si
    copyargc_02:
	ret
copyargc ENDP

setargv	PROC
	pop	ax		; return adress - only 2 byte on stack!!
	mov	_ip,ax
	mov	_si,si		; save SI and DI
	mov	_di,di
	mov	bp,_psp		; command line at _psp[0080]
	mov	es,bp
	mov	si,0080h
	sub	bx,bx
	cld
	mov	bl,es:[si]	; BX to length of command line + 1
	inc	si
	inc	bx
	mov	dx,si
	mov	si,envlen	; program name - _argv[0]
	inc	si
	inc	si
	mov	es,envseg
	mov	di,si
	mov	cx,007Fh
	xor	ax,ax
	repnz	scasb
	test	cx,cx
	jz	setargv_04
	xor	cl,7Fh
	push	ax		; set end of buffer to 0
	mov	ax,cx
	add	ax,bx
	inc	ax
	and	ax,not 1
	mov	di,sp
	sub	di,ax
	jb	setargv_04
	mov	sp,di
	push	es
	pop	ds
	push	ss
	pop	es
	push	cx
	dec	cx
	rep	movsb
	xor	al,al
	stosb
	mov	ds,bp
	xchg	dx,si
	xchg	cx,bx
	mov	ax,bx
	mov	dx,ax
	inc	bx
    setargv_00:
	call	copyargc
	ja	setargv_02
    setargv_01:
	jb	setargv_05
	cmp	al,13
	je	setargv_03
	call	copyargc
	ja	setargv_01
    setargv_02:
	cmp	al,' '
	je	setargv_03
	cmp	al,13
	je	setargv_03
	cmp	al,9
	jnz	setargv_00
    setargv_03:
	xor	al,al
	jmp	setargv_00
    setargv_04:
	jmp	_abort
    setargv_05:
	pop	cx
	add	cx,dx
	push	ss
	pop	ds
	mov	_argc,bx
	mov	C0_argc,bx
	inc	bx
	add	bx,bx
	add	bx,bx
	mov	si,sp
	mov	bp,sp
	sub	bp,bx
	jb	setargv_04
	mov	sp,bp
	mov	_argv,bp
	mov	_argv+2,ss
	mov	C0_argv,bp
	mov	C0_argv+2,ss
    setargv_06:
	test	cx,cx
	jz	setargv_08
	mov	[bp],si
	mov	[bp+2],ss
	add	bp,4
    setargv_07:
	lodsb
	test	al,al
	loopnz	setargv_07
	jz	setargv_06
    setargv_08:
	xor	ax,ax
	mov	[bp],ax
	push	ss
	pop	ds
	mov	[bp+2],ax
	mov	si,_si
	mov	di,_di
	jmp	_ip
setargv	ENDP

_TEXT	ENDS

_INIT_	SEGMENT
	dw	setargv
_INIT_	ENDS

	END
