*! 1.1.0 Post-Estimation calculation of AIC statistic  Joseph Hilbe 19Oct2005
program define aic
	version 9.1
	quietly {
		capture qui fitstat
		if "`r(aic)'"!="" {
			noi di as txt _col(1) "AIC Statistic =  " as res %9.0g r(aic)
			exit
		}
	}

	quietly {
		local  ll   = e(ll)
		if `ll' == . {			/* In case deviance-based */
			local ll = -.5*e(dev)
		}

		if `ll' == . {			/* In case estimation program is old */
			if "$S_E_ll" == "" {
				noi di as err "Previous command was not an estimation command or is too old"
				exit 198
			}
			local ll   = $S_E_ll
			local p    = $S_E_mdf
			local nobs = $S_E_nobs
			local df   = `nobs'-`p'-1
		}
		else {				/* Estimation command is not old */
			tempname b
			local nobs  = e(N)
			matrix `b'  = e(b)
			local  p    = colsof(`b')
			local  nc   = 0 		/* Number of _cons values and constraints */

			local ss "`e(plvars)'" 	/* Number of gologit2 constraints */
			if "`ss'" != "" {
				local nc : word count `ss'
				local f "`e(eqnames)'"
				local nn : word count `f'
				local nc = `nc'+`nn'
			}
			else {
				local f : colnames(`b')
				local nc = 0
				local i 1
				while `i' <= `p' {
					local d : word `i' of `f'
					if "`d'" == "_cons" {
						local nc = `nc'+1
					}
					local i = `i'+1
				}
			}

			local p = `p'-`nc'
			local df = `nobs'-`p'-`nc'
			if "`e(cmd)'" == "glm" {
				local p  = `p'+1
			}
		}
		local aic   = 2*(`p'-`ll')/`nobs'
		local bic   = -2*`ll'-`df'*log(`nobs')
	}

	di as txt _col(1) "AIC Statistic =  " as res %9.0g `aic'
	*di as txt _col(1) "BIC Statistic =  " as res %9.0g `bic'
end