*! version 1.0.1 03feb1998  Statalist distribution
program define grand
	version 5.0
	if "$S_E_cmd" != "fit" { error 301 }

	local varlist "req existing"
	local options "HOLD Level(integer $S_level)"
	parse "`*'"
	parse "`varlist'", parse(" ")

	local depv $S_E_depv

	/* establish the sample */
	if "$S_E_exp" != "" { local weight "[$S_E_wgt $S_E_exp]" }
	tempvar touse one
	mark `touse' $S_E_if $S_E_in [$S_E_wgt $S_E_exp]
	markout `touse' $S_E_vl

	/* check if the indicators fully and exactly span the space */
	egen byte `one' = rsum(`varlist')
	capture assert `one' == 1 if `touse'
	if _rc != 0 {
		disp in blue "Warning, indicators `varlist' do not full span the space"
	}


	/* build the grand mean linear combination */
	qui count if `touse'
	local N = _result(1)
	local i 1
	while "``i''" != "" {
		qui count if `touse' & ``i''
		local ct`i' = _result(1)
		local grand "`grand'`plus'(`ct`i''/`N')*``i''"
		local plus "+"
		local i = `i' + 1
	}

	/*  Put lincom results in b vector and V matrix  */
	local k : word count `varlist'
	local k1 = `k' + 1
	tempname b V v holdb
	mat `V' = J(`k1', `k1', 0)
	mat `b' = J(1, `k1', 0)
	mat `v' = J(1, `k1', 0)
	qui lincom `grand', level(`level')
	mat `b'[1,1] = $S_1
	mat `V'[1,1] = $S_2^2
	mat `v'[1,1] = $S_2
	mat colnames `b' = grand `varlist'
	mat colnames `V' = grand `varlist'
	mat rownames `V' = grand `varlist'
	mat colnames `v' = grand `varlist'

	local i 1
	while "``i''" != "" {
		qui lincom ``i'' - (`grand'), level(`level')
		local i = `i' + 1
		mat `b'[1,`i'] = $S_1
		mat `V'[`i',`i'] = $S_2^2
		mat `v'[1,`i'] = $S_2
	}
	local dofopt "dof($S_3)"

	/* Display results */
	disp in green _n "Estimate of grand mean/intercept and marginal impacts"
	tempname esthold
	estimates hold `esthold'
	mat `holdb' = `b'
	matrix post `b' `V', `dofopt' dep(`depv')
	matrix mlout, level(`level')
	estimates unhold `esthold'
	mat S_E_b = `holdb'
	mat S_E_se = `v'

end