*! version 1.0.0  31aug2001
program define lnormhet_ilf_sh2
	version 7.0
	args todo b lnf g negH g1 g2

	tempvar beta
	tempname lnsigma lntheta
	mleval `beta' = `b', eq(1)
	mleval `lnsigma' = `b', eq(2) scalar
	mleval `lntheta' = `b', eq(3) scalar

	local t = "$EREGt"
	local t0 = "$EREGt0"
	local d = "$EREGd"
	local by  = "by $EREG_by"

	quietly {
	        scalar `lntheta'=cond(`lntheta'<-20,-20,`lntheta')
		scalar `lnsigma'=cond(`lnsigma'<-20,-20,`lnsigma')

	        tempname th sg
 	        tempvar sumh sums sumd k k0 b b0 a bes
	        scalar `th' = exp(`lntheta')
		scalar `sg' = exp(`lnsigma')

		gen double `k' = (ln(`t') - `beta')/`sg' if $ML_samp
		gen double `k0' = cond(`t0'>0,(ln(`t0')-`beta')/`sg',0) /*
			*/ if $ML_samp
		gen double `b' = ln(norm(-`k')) if $ML_samp
		gen double `b0' = cond(`t0'>0,ln(norm(-`k0')),0) if $ML_samp

		`by': gen double `sumh' = cond(_n==_N, /*
			*/ sum(`d'*(ln(normd(`k'))-`b'-`lnsigma')),.) /*
			*/ if $ML_samp
		`by': gen double `sums' = cond(_n==_N, /*
			*/ sum(`b'-`b0'),0) if $ML_samp
		`by': gen double `sumd' = cond(_n==_N, /*
			*/ sum(`d'),.) if $ML_samp

 		gen double `a' = sqrt(1-2*`th'*`sums') if `sumh'!=.
 		_lnbessel `bes' = `th'/`a' if `sumh'!=., k(`sumd')
 		mlsum `lnf' = cond(`sumh'!=., `sumh' + (1-`a')/`th' - /*
 			*/  `sumd'*ln(`a') + `bes' , 0)

		if `todo'==0 | `lnf'==. {exit}
	}
end
exit