*! version 1.0.0  statalist distribution 16 mar 1998
program define tpred
	version 5.0

	if "$S_E_cmd"!="tobit" {
		error 301
	}

	tempvar user new yhat
	local varlist "new min(1)"
	local if "opt"
	local in "opt"
	local options "P(string) E(string) Ystar(string)"
	parse "`*'"
	rename `varlist' `user'

	local y "`ystar'"

	if "`p'"!="" & "`e'"!="" & "`y'"!="" {
		error 198
	}
	if "`p'"=="" & "`e'"=="" & "`y'"=="" {
		error 198
	}
	local r "`p'`e'`y'"
	parse "`r'", parse(",")
	if "`2'" != "," {
		error 198
	}

	if "`1'" != "." {
		confirm number `1'
	}
	if "`3'" != "." {
		confirm number `3'
	}

	if "`4'"!="" {
		error 198
	}
	local r1 "`1'"
	local r2 "`3'"

	qui predict double `yhat' `if' `in'

	if "`p'" != "" {
		CalcP `new' `yhat' `r1' `r2'
	}
	else if "`e'" != "" {
		CalcE `new' `yhat' `r1' `r2'
	}
	else {
		CalcY `new' `yhat' `r1' `r2'
	}
	qui replace `user' = `new' `if' `in'
	rename `user' `varlist'
	quietly count if `varlist'==.
	if _result(1) {
		if _result(1)>1 {
			local s "s"
		}
		di in gr "(" _result(1) missing value`s' generated)"
	}
end

program define CalcP
	local p "`1'"
	local yhat "`2'"
	local r1 "`3'"
	local r2 "`4'"

	if `r1'==. & `r2'==. {
		qui gen byte `p'  = 1
	}
	else if `r2'==. {
		qui gen double `p' = normprob(-(`r1'-`yhat')/_b[_se])
	}
	else if `r1'==. {
		qui gen double `p' = normprob((`r2'-`yhat')/_b[_se])
	}
	else {
		qui gen double `p' = 1 - normprob(-(`r2'-`yhat')/_b[_se]) - /*
				*/ normprob((`r1'-`yhat')/_b[_se])
	}
end


program define CalcE
	local E "`1'"
	local yhat "`2'"
	local r1 "`3'"
	local r2 "`4'"

	if `r1'==. & `r2'==. {
		qui gen double `E' = `yhat'
	}
	else if `r2'==. {
		qui gen double `E' = `yhat' + _b[_se]*( /*
			*/    normd( (`r1'-`yhat')/_b[_se]) / /*
			*/ normprob(-(`r1'-`yhat')/_b[_se]) /*
			*/ )
	}
	else if `r1'==. {
		qui gen double `E' = `yhat' - _b[_se]*( /*
			*/    normd((`r2'-`yhat')/_b[_se]) / /*
			*/ normprob((`r2'-`yhat')/_b[_se]) /*
			*/ )
	}
	else {
		qui gen double `E' = `yhat' + _b[_se]*( /*
			*/ ( normd((`r1'-`yhat')/_b[_se]) - /*
			*/   normd((`r2'-`yhat')/_b[_se]) ) / /*
			*/ ( 1 - normprob(-(`r2'-`yhat')/_b[_se]) - /*
			*/   normprob((`r1'-`yhat')/_b[_se])) /*
			*/ )
	}
end

program define CalcY
	local Y "`1'"
	local yhat "`2'"
	local r1 "`3'"
	local r2 "`4'"

	tempvar E p
	CalcE `E' `yhat' `r1' `r2'
	CalcP `p' `yhat' `r1' `r2'

	if `r1'==. & `r2'==. {
		rename `E' `Y'
	}
	else if `r2'==. {
		qui gen double `Y' = `p'*`E' + (1-`p')*`r1'
	}
	else if `r1'==. {
		qui gen double `Y' = `p'*`E' + (1-`p')*`r2'
	}
	else {
		tempvar p2
		CalcP `p2' `yhat' . `r1'
		qui gen double `Y' = `p'*`E' + `p2'*`r1' + (1-`p'-`p2')*`r2'
	}
end
exit