*! version 1.0.0  Statalist distribution  02feb1999
program define gennorm
	version 6
	syntax newvarlist [if] [in] [, Corr(string)]
	local n : word count `varlist'
	if `n'==1 {
		if `"`corr'"' != "" {
			di in red "option corr() not allowed"
			exit 198
		}
		gen `typlist' `varlist' = invnorm(uniform()) `if' `in'
		exit
	}
	if `"`corr'"' == "" {
		di in red "option corr() required"
		exit 198
	}
	tokenize `"`corr'"', parse(" \,")

	tempname P row

	capture confirm number `1'
	if _rc {
		if "`2'" != "" {
			di in red `"option corr(`corr') incorrectly specified"'
			exit 198
		}
		mat `P' = `1'
		if rowsof(`P') != colsof(`P') {
			error 505
		}
		if rowsof(`P') != `n' {
			di in red /*
	*/ "`n' variables specified but specified correlation matrix is " /*
	*/ rowsof(`P') " x " colsof(`P')"
			exit 503
		}
	}
	else {
		mat `P' = I(`n')
		local k 1
		local i 1
		while `i' <= `n' {
			local j = `i' + 1
			while `j' <= `n' {
				if "``k''"=="," | "``k''"=="\" {
					local k = `k' + 1
				}
				confirm number ``k''
				if ``k''< -1 | ``k''>1 {
					di in red /*
				*/ "correlations must be bounded by -1 and 1"
					exit 198
				}
				mat `P'[`i',`j'] = ``k''
				mat `P'[`j',`i'] = ``k''
				local j = `j' + 1
				local k = `k' + 1
			}
			local i = `i' + 1
		}
		if "``k''" != "" {
			di in red "option corr():  too many elements specified"
			exit 198
		}
	}

	quietly {
		local i 1
		while `i' <= `n' {
			tempname c`i'
			local list "`list' `c`i''"
			gen `c`i'' = invnorm(uniform()) `if' `in'
			local i = `i' + 1
		}
		mat roweq `P' = _:
		mat coleq `P' = _:
		mat rownames `P' = `list'
		mat colnames `P' = `list'
		mat `P' = cholesky(`P')
		local i 1

		tokenize `varlist'
		while `i' <= `n' {
			local typ : word `i' of `typlist'
			mat `row' = `P'[`i',1...]
			mat score `typ' ``i'' = `row'
			local i = `i' + 1
		}
		count if `1'==.
	}
	if r(N) {
		local s = cond(r(N)==1,"","s")
		di in gr "(" r(N) "missing value`s' per variable generated"
	}
end
exit