*! version 2.0.4 11jan2006   Richard Williams, rwilliam@nd.edu

* This is a rewrite of Vincent Kang Fu's goll.ado program
* and is called by gologit2 written by Richard Williams

program gologit2_ll
	version 8.2
	gettoken lnf xbeta: 0
	foreach xb in `xbeta' {
		local i = `i' + 1
		local xb`i' `xb'
	}
	local Numeqs = `i'
	local M = `i' + 1

	// M = # of categories in DV
	// Numeqs = Number of equations = number of categories - 1

	// The global variables $dv_ contain the values for the 1rst, 2nd, 3rd
	// etc. values of Y.  e.g. if Y is coded -3, 0, 3, then
	// $dv_1 = -3, $dv_2 = 0, $dv_3 = 3.
	// These should be set by the calling program.
	// If not already set, default Y coding is 1, 2, 3,...

	forval i = 1/`M' {
		if "${dv_`i'}"=="" {
			local dv_`i' `i'
		}
		else local dv_`i' ${dv_`i'}
	}

	// These formulas are algebraically equivalent but quicker than
	// formulas presented in other documentation

	// First (lowest) value of Y
	quietly replace `lnf' =  -ln(1 + exp(`xb1')) if $ML_y1 == `dv_1'

	// Middle values of Y
	forval i = 2/`Numeqs'	{
		local j = `i' - 1
		quietly replace `lnf' =  ln( 1 / (1 + exp(`xb`i'')) - 1 / ( 1 + exp(`xb`j''))) ///
			if $ML_y1 == `dv_`i''
	}

	// Last (highest) value of Y
	quietly replace `lnf' =  -ln(1 + exp(-`xb`Numeqs'')) if $ML_y1 == `dv_`M''

end