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

	tempvar beta
	tempname lngamma lntheta
	mleval `beta' = `b', eq(1)
	mleval `lngamma' = `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 `lngamma'=cond(`lngamma'<-20,-20,`lngamma')

	        tempname th ga
 	        tempvar sumh sums sumd b b0 a bes
	        scalar `th' = exp(`lntheta')
		scalar `ga' = exp(-`lngamma') /* gamma really 1/gamma */

		gen double `b' = ln(1 + (exp(-`beta')*`t')^`ga') if $ML_samp
		gen double `b0' = ln(1 + (exp(-`beta')*`t0')^`ga') if $ML_samp

		`by': gen double `sumh' = cond(_n==_N, /*
			*/ sum(`d'*(`ga'*(ln(`t')-`beta') - `lngamma' - /*
			*/     `b')),.) if $ML_samp
		`by': gen double `sums' = cond(_n==_N, /*
			*/ sum(`b0'-`b'),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