; Change history:
; 11/15/2011 - limit size of %environ% to 128 -- crash: echo %path%
include	clib.inc
include	string.inc
include	stdlib.inc

	; expand '%TEMP%' to 'C:\TEMP'

PPROC	expenviron, string:dword ; [128]
local	envl:word
local	environ[132]:byte
local	expanded[132]:byte
	push si
	push di
	mov di,word ptr string
	.repeat
	    mov ax,word ptr string+2
	    .break .if !func(strchr, ax::di, '%'); get start of [%]environ%
	    mov si,ax
	    inc ax
	    .break .if !func(strchr, dx::ax, '%'); get end of %environ[%]
	    mov di,ax
	    sub ax,si
	    inc ax   	; = length of %environ%
	    mov envl,ax
	    .if ax < 128
		lea bx,environ
		invoke strncpy, ss::bx, dx::si, ax ; copy %environ% to stack
		inc ax
		.if func(getenvp, dx::ax)
		    lea bx,expanded
		    invoke strncpy, ss::bx, dx::ax, 128
		    invoke strlen, dx::ax
		    mov bx,ax
		    invoke strlen, string
		    add ax,bx
		    sub ax,envl
		    .if ax < 128
			mov cx,di
			sub cx,si
			inc cx ; xchg %environ% with value
			invoke strxchg, string, addr environ, addr expanded, cx
			invoke strlen, addr expanded
			add ax,si
			dec ax
			mov di,ax ; move to end of %environ%
		    .endif
		.endif
	    .endif
	    inc di
	.until 0
	pop di
	pop si
	ret
PEND	expenviron

	END
