*! betacoef 1.0.3  cfb 4113
* 1.0.2: deal with ts operators, return syntax
* 1.0.3: allow execution after ivreg, ivreg2, ivreg3

program define betacoef, rclass
	version 7.0

	if "`e(cmd)'" != "regress" & "`e(cmd)'" !=  "ivreg" & "`e(cmd)'" !=  "ivreg2" /*
	*/ & "`e(cmd)'" !=  "ivreg3"  {
		error 301
	}
	if "`e(wtype)'" != "" {
		local wt "[`e(wtype)'`e(wexp)']"
	}
		tempname b
	/* get depvar and regressorlist from previous regression */
		local depvar = e(depvar)
        mat `b' = e(b)
        local rvarlst : colnames `b'
        local rvarlst : subinstr local rvarlst "_cons" "", /*
        */ word count(local hascons)

	marksample touse
	if "`sample'" == "" {
		qui replace `touse' = 0 if !e(sample)
		}

	qui summ `depvar' `wt' if `touse'
	scalar ysd = r(sd)
	local i
	foreach v of local rvarlst {
		local i = `i'+1
		qui summ `v' `wt' if `touse'
		scalar sd`i' = r(sd)
		mat `b'[1,`i'] = `b'[1,`i'] * sd`i' / ysd
		}
* set to zero, not missing, for v7 compatibility
	if (`hascons') {
		mat `b'[1,`i'+1] = 0
		}

	return mat beta `b'
	end