*! version 3.0.1  1/20/94
program define robksm
	version 3.0
	local varlist "req ex min(2) max(2)"
	local if "opt"
	local in "opt"
	#delimit ;
	local options "Line Weight noGraph GEN(string) BWidth(real 0) Adjust
		LOWess LOgit T1title(string) Symbol(string) Connect(string) *";
	#delimit cr
	parse "`*'"
	if "`gen'"~="" {
		confirm new var `gen'
	}
	parse "`varlist'", parse(" ")
	if "`lowess'"!="" {
		local weight "weight"
		local line "line"
	}
	tempvar Y X smooth
	quietly {
		gen `Y'=`1' `if' `in'
		gen `X'=`2' `if' `in'
		replace `X'=. if `Y'==.
		summ `X'
		local cnt = _result(1)
		if `cnt'<3 { noisily error 2001 }
		if _result(6)-_result(5)<1e-30 {
			di in red "Range of `2' is too small"
			exit 499
		}
		_crcslbl `Y' `1'
		_crcslbl `X' `2'
		sort `X'
/*
	Set up complete.
*/
		local bw = `bwidth'
		if `bw' <= 0 | `bw' >= 1 { local bw .8 }
/*
	smopt=0 (unwtd mean), 1(unwtd line), 2(wtd mean), 3(wtd line).
*/
		if "`line'" == "line" { local smopt = 1 }
		else { local smopt = 0 }
		if "`weight'" == "weight" { local smopt = `smopt'+2 }
		_robksm `Y' `X' `cnt' `bw' `smooth' `smopt'
/*
	Adjust smooth so that mean of Y-values equals mean of smoothed values.
*/
		if "`adjust'" == "adjust" {
			sum `smooth'
			local mean = _result(3)
			sum `Y'
			replace `smooth' = `smooth'*_result(3)/`mean'
		}
		if "`logit'" == "logit" {
			local adj = 1/`cnt'
			local small = 0.0001
			replace `smooth' = `adj' if `smooth'<`small'
			replace `smooth' = 1-`adj' if `smooth'>(1-`small')
			replace `smooth' = log(`smooth'/(1-`smooth'))
		}
	}
/*
	Graph (if required)
*/
	if "`graph'" ~= "nograph"  {
		if "`t1title'" ==""{
			if "`lowess'"!="" {
				local t1title "Lowess smoother"
			}
			else if "`line'" == "line" {
				local t1title "Running line smoother"
			}
			else {
				local t1title "Running mean smoother"
			}
			local t1title "`t1title', bandwidth = `bw'"
		}
		if "`logit'"=="" {
			if "`symbol'"=="" { local symbol "oi" }
			if "`connect'"=="" { local connect ".l" }
			graph `Y' `smooth' `X', `options' /*
				*/ t1("`t1title'") /*
				*/ s(`symbol') c(`connect')
		}
		else {
			if "`symbol'"=="" { local symbol "i" }
			if "`connect'"=="" { local connect "l" }
			gr `smooth' `X', `options' t1("`t1title'") /*
				*/ s(`symbol') c(`connect')
		}
	}
	if "`gen'"~="" {
		rename `smooth' `gen'
	}
end