*! version 3.0.0  1/20/94
program define _robksm
	version 3.0
*Last revised: 27/03/2001
/*
	Args: 1=Y, 2=X, 3=count, 4=bandwidth, 5=smoothed Y,
	6=0 (unwtd mean), 1(unwtd line), 2(wtd mean), 3(wtd line), 7=robust
        residuals.
	NOTE: bandwidth is expressed as a fraction of the sample size,
	not a number of sample values.
*/
	tempvar W
        capture drop `5'
/*
	Using symmetric neighbourhoods.
	`k' is half-bandwidth. Initialise using points 1,...,k+1.
	Delta is distance between current Y and furthest neighbour in the
	interval. `W' is tricube weight function within the interval.
*/
	gen `W' = 1
	gen `5' = .
	local wtd = (`6'>1)
	local mean = (`6'==0 | `6'==2)
	local k = int((`4'*`3'-0.5)/2)
	local i 0
	while `i'<`3' {
		local i = `i'+1
		local x0 = `2'[`i']
                if `i'>`3'-`k' {
                    local imk=`3'-`k'*2
                }
                else {
		    local imk = max(1, `i'-`k')
                }
                if `i'<`k'+1 {
                    local ipk=`k'*2+1
                }
                else {
		    local ipk = min(`i'+`k', `3')
                }
		if `wtd' {
			#delimit ;
			local delta = 1.0001*
				max(`2'[`ipk']-`x0', `x0'-`2'[`imk']) ;
			replace `W' = cond(`delta'>1e-30,
				(1-(abs(`2'-`x0')/`delta')^3)^3 , 1)
				in `imk'/`ipk' ;
                        replace `W' = robwei*`W' in `imk'/`ipk' ;
			#delimit cr
		}
		if `mean' {
			sum `1' [aw=`W'] in `imk'/`ipk'
			replace `5' = _result(3) in `i'
		}
		else {
			reg `1' `2' [aw=`W'] in `imk'/`ipk'
			replace `5' = _b[_cons]+_b[`2']*`x0' in `i'
		}
	}
end