*! version 1.1.0  15jan1999
program define st_rpool
	version 6
	if _caller()<=5 {
		zt_rpoo5 `0'
		exit
	}

	st_is 2 analysis
	syntax newvarname [if] [in] [, noPreserve Strata(varlist)]

	if "`preserv'" == "" {
		preserve
		local Done "restore, not"
	}
	quietly {
		keep if _st
		if `"`if'"'!="" | "`in'"!="" {
			keep `if' `in'
		}
		tempvar touse
		mark `touse'
		markout `touse' `strata', strok
		keep if `touse'
		drop `touse'

		if "`strata'"=="" {
			Expand `typlist' `varlist'
		}
		else	Expands `typlist' `varlist' `strata'
		tempvar holdt0 holdt holdd
		nobreak {
			rename _t0 `holdt0'
			rename _t `holdt'
			rename _d `holdd'
			if "`_dta[st_bt]'" != "" {
				drop `_dta[st_bt]'
			}
			if "`_dta[st_bt0]'" != "" {
				drop `_dta[st_bt0]'
			}
			if "`_dta[st_bd]'" != "" {
				drop `_dta[st_bd]'
			}
			stset, clear
			rename `holdt0' _t0
			rename `holdt' _t
			rename `holdd' _d
			mac drop S_FN S_FNDATE
		}
	}
	`Done'
end

program define Expand /* newtype newvar */
	args evtype event

	sort _t _d
	by _t: gen `evtype' `event' = cond(_n==_N & _d!=0,-1,.)
	sort `event' _t
	count if `event' == -1
	local nevent = _result(1)
	local nobs = _N
	local ev 1
	while `ev' <= `nevent' {
		local nobs1 = _N + 1
		expand 2 if _t0<_t[`ev'] & _t>=_t[`ev'] in 1/`nobs'
		replace `event' = `ev' in `nobs1'/l
		replace _d = 0 if _t>_t[`ev'] in `nobs1'/l
		local ev = `ev' + 1
	}
	drop if `event'==-1 | `event'==.
end

program define Expands /* netype newvar stratavars */
	args evtype event
	mac shift 2
	local by "`*'"
	local n : word count `by'
	if `n'>1 {
		tempvar s
		quietly {
			egen `s' = group(`by'), missing
			compress `s'
		}
		local by "`s'"
	}

	sort `by' _t _d
	by `by' _t: gen `evtype' `event' = cond(_n==_N & _d!=0,-1,.)
	sort `event' `by' _t
	count if `event' == -1
	local nevent = _result(1)
	local nobs = _N
	local ev 1
	while `ev' <= `nevent' {
		local nobs1 = _N + 1
		expand 2 if _t0<_t[`ev'] & _t>=_t[`ev'] & /*
			*/ `by'==`by'[`ev'] in 1/`nobs'
		replace `event' = `ev' in `nobs1'/l
		replace _d = 0 if _t>_t[`ev'] in `nobs1'/l
		local ev = `ev' + 1
	}
	drop if `event'==-1 | `event'==.
end