*! version 1.0.4  08sep2004  rgg/njc
program bincoverage, rclass
	version 8.2
	syntax [, n(int 10) p(real 0.5) Level(int `c(level)') ///
		  EXAct Wilson Agresti Jeffreys]

	local flavor `exact' `wilson' `agresti' `jeffreys'
	local m : word count `flavor'

	if `m' > 1 {
		di as err "{p}You may only specify one of exact, wilson, " _c
		di as err "agresti, or jeffreys{p_end}"
		exit 198
	}
	else if `m' == 0 {
		local flavor exact
	}
	local mid = round(`n' * `p', 1)
	local kmin `mid'
	local kmax `mid'

	// begin in the middle, branch out until you get no coverage

	while `kmin' >= 0 {
		qui cii `n' `kmin', `flavor' level(`level')
		if missing(r(lb)) | missing(r(ub)) {
			local miss miss
		}
		if r(lb) < `p' & r(ub) > `p' {
			local --kmin
		}
		else {
			continue, break
		}
	}
	while `kmax' <= `n' {
		qui cii `n' `kmax', `flavor' level(`level')
		if missing(r(lb)) | missing(r(ub)) {
			local miss miss
		}
		if r(lb) < `p' & r(ub) > `p' {
			local ++kmax
		}
		else {
			continue, break
		}
	}
	if "`miss'" != "" {
		di as err "confidence limits were missing in one " _c
		di as err "or more outcomes "
		di as err "n is probably too large"
		exit 498
	}
	tempname cp
	scalar `cp' = cond(`kmin'==`kmax',0, ///
		Binomial(`n',`kmin'+1,`p') - Binomial(`n',`kmax',`p'))
	di as txt _n "For N = " as res `n'  as txt " and p = " as res `p' ///
		as txt ", the true coverage probability of the nominal" ///
		_n "    " ///
		as res "`level'% `flavor'" ///
		as txt " CI is " as res %6.4f `cp' ///
		as txt "."

	return scalar n = `n'
	return scalar p = `p'
	return local type `flavor'
	return scalar coverage = `cp'
end