*! version 1.0.2  08jun2007
program define gengammareg
	version 9
	syntax newvarname [if] [in] [, tr(string) XBeta(string) ///
				       Kappa(real 0.0) Sigma(real 1.0)]

//  Function to generate a random response appropriate for use with
//  Stata's -streg, dist(gamma)- command

	local x `varlist'
	marksample touse, novarlist

	if `"`tr'"' != "" & `"`xbeta'"' != "" {
		di as err "{p 0 4 2}tr() and xbeta() may not be "
		di as err "specified together{p_end}"
		exit 198
	}

	if `"`tr'"' == "" & `"`xbeta'"' == "" {
		local tr 1
	}
	if `"`tr'"' != "" {
		local w : word count `tr'
		if `w'!=1 {
			di as err "{p 0 4 2}tr() invalid{p_end}"
			exit 198
		}
		capture confirm number `tr'
		if _rc {
			confirm numeric variable `tr'
		}
		capture assert `tr' > 0 if `touse'
		if _rc {
			di as err "{p 0 4 2}tr() must be positive-valued"
			di as err "{p_end}"
			exit 198
		}
	}
	else {					// xbeta specified
		local w : word count `xbeta'
		if `w'!=1 {
			di as err "{p 0 4 2}xbeta() invalid{p_end}"
			exit 198
		}
		capture confirm number `xbeta'
		if _rc {
			confirm numeric variable `xbeta'
		}
		tempvar tr
		qui gen double `tr' = exp(`xbeta') if `touse'
	}
	cap assert `sigma' > 0
	if _rc {
		di as err "{p 0 4 2}sigma() must be positive-valued{p_end}"
		exit 198
	}

	// At this point, tr is all I need

	tempvar t b

	if abs(`kappa') < 1e-6 {		// treat kappa as zero
		qui gen double `t' = `tr'*exp(`sigma'*invnorm(uniform())) ///
					if `touse'
		generate `typlist' `x' = `t' if `touse'
		exit
	}

	local a = 1/(`kappa'*`kappa')
	local g = `kappa'/`sigma'
	qui gen double `b' = `tr'*(abs(`kappa'))^(2*`sigma'/`kappa')
	qui GenGamma_w double `t' if `touse', alpha(`a') beta(`b') gamma(`g')

	generate `typlist' `x' = `t' if `touse'
end

program define GenGamma_w
	syntax newvarname [if] [in] [, alpha(string) beta(string) /*
	*/ gamma(string)]

	local x `varlist'

	if "`alpha'" == "" {
		local alpha = 1.0
	}
	else {
		capture confirm number `alpha'
		if _rc {
			confirm numeric variable `alpha'
		}
	}
	if "`beta'" == "" {
		local beta = 1.0
	}
	else {
		capture confirm number `beta'
		if _rc {
			confirm numeric variable `beta'
		}
	}

	if "`gamma'" == "" {
		local gamma = 1.0
	}
	else {
		capture confirm number `gamma'
		if _rc {
			confirm numeric variable `gamma'
		}
	}

	qui generate `typlist' `x' = invgammap(`alpha',uniform()) `if' `in'
 	qui replace `x' = `x'*`beta' `if' `in'
	qui replace `x' = `beta'*(`x'/`beta')^(1/`gamma') `if' `in'
	qui count if missing(`x')
	local cn = r(N)
	if `cn'>0 {
		di as txt "(`cn' missing values generated)"
	}
end

exit