*! version 1.0.1  1330  CFBaum   (TSJ-1: st0004)
* from xttest1 v1.0.3 and sureg
* following Greene, 2000, p. 601
* mod 1.0.1 to allow xtgls

program define xttest2, rclass
	version 6.0

	if "`e(cmd)'"=="xtreg" { local est 1 }
	if "`e(cmd)'"=="xtgls" { local est 2 }
	if "`est'" ==""	{ error 301 }
	if "`e(model)'" != "fe" & "`est'"=="1" {
		di in red "last estimates not xtreg, fe"
		exit 301
	}
	if "`*'"!="" { error 198 }

	tempvar touse iota xb
	tempname cov cor CCp

	qui gen byte `touse' = e(sample)
	preserve
	qui drop if `touse'==0
* cross-section indicator
	local ivar "`e(ivar)'"
* number of cross sections
	local ng "`e(N_g)'"
* min length of time series
	local tb "`e(g_min)'"
* compute fixed effect e(i,t)
	if "`est'"   == "1" {
		qui predict double __e if `touse', e
	}
	else {
		qui predict double `xb' if `touse'
		qui gen double __e = `e(depvar)'-`xb'
	}
* reshape to wide so that VCE may be computed
	sort `ivar'
	qui by `ivar': gen `iota'=_n
	keep __e `e(ivar)' `iota'
	qui reshape wide __e, i(`iota') j(`e(ivar)')
	qui mat accum `cov' = __e*,dev noc
	local nbal "`r(N)'"
* code adapted from sureg BP test
	di " "
	di in gr "Correlation matrix of residuals:"
    mat `cor' = corr(`cov')
    mat list `cor', nohead format(%9.4f)
    mat `CCp' = `cor' * `cor''
    local tsig = (trace(`CCp') - `ng')*`tb' / 2
    local df = `ng' * (`ng' - 1) / 2
    di
    di in gr "Breusch-Pagan LM test of independence: chi2(`df') = " /*
    */ in ye %9.3f `tsig' in gr ", Pr = " %6.4f /*
    */ in ye chiprob(`df',`tsig')
	di in gr "Based on `nbal' complete observations"
    ret scalar chi2_bp = `tsig'
    ret scalar df_bp   = `df'
    ret scalar n_bp    = `nbal'
end
exit