*! version 6.0.2  22jan1999
program define median, rclass
	version 6
        syntax varlist(max=1) [if] [in] [fweight], by(varname) [ Exact ]
        marksample touse, strok

	local x "`varlist'"
	tempname hilab
	tempvar median hi
	if "`weight'"!="" {
		local wtopt="[fw `exp']"
	}
	quietly {
		summarize `by' if `touse' `wtopt', meanonly
		if r(N) == 0 { noisily error 2000 }
		if r(min) == r(max) {
			di in red "1 group found, 2 required"
			exit 499
		}

		sum `x' if `touse' `wtopt', detail
		gen double `median' = r(p50) if `touse'

		gen double `hi' = 0 if `touse'
		replace `hi' = 1 if `x'>=`median' & `touse'
		label var `hi' "Greater or equal to the median"
		label def `hilab'  0 "No" 1 "yes"
		label values `hi' `hilab'
	}
	tempname CM
	di in gr _n "Median test" _n
	tab `hi' `by' if `touse' `wtopt' , chi `exact' matcell(`CM')
	local N = r(N)
	local numcol=r(c)
	ret add
	if `numcol' == 2 {
		di in gr _n "   Continuity corrected:"
		local A=`CM'[1,1]
		local B=`CM'[1,2]
		local C=`CM'[2,1]
		local D=`CM'[2,2]
		tempname chi2
		*scalar `N'= `A'+`B'+`C'+`D'
		scalar `chi2'=`N'* (abs(`A'*`D' - `B'*`C')-(`N'/2))^2
		scalar `chi2'=`chi2'/((`A'+`B')*(`C'+`D')*(`A'+`C')*(`B'+`D'))
		noi di in gr "          Pearson chi2(" in ye "1" in gr ") = " /*
		*/ in ye %8.4f `chi2' /*
		*/ in gr "   Pr = " in ye %5.3f chiprob(1,`chi2')
       		ret scalar chi2_cc = `chi2'
		ret scalar p_cc = chiprob(1,`chi2')
	}
end