function [ xmean ] = bw_trend( x, bw_bw)
%BW_TREND: Biweight Filter
%Description: This algorithm filters the series using Biweight method.
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Input%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  [ xmean ] = bw_trend( x, bw_bw)
%
%   x     == (nobs x 1) series to be filtered.
%   bw_bw == Bi-Weight parameter for local demeaning
%            Note: 100 is used by Stock & Watson's original code.
%
%Created by John Fernald and Kuni Natsuki
%
% The original algorithm was acquired from the Gauss files in 
% Stock & Watson's replication files for
% "Disentangling the Channels of the 2007-2009 Recession" paper. 
% http://www.princeton.edu/~mwatson/ddisk/Stock_Watson_Disentangling_ReplicationFiles_May11_2012.zip

nobs = size(x,1);
tmp  = zeros(nobs,1);
trend = 1:nobs;

for t=1:nobs;
    dt = (trend - t)/bw_bw;
    bw_weight = (15/16)*((1-dt.^2).^2);
    bw_weight = bw_weight.*(abs(dt)< 1);
    bw_weight = bw_weight/sum(bw_weight);
    tmp(t)=dot(bw_weight,x);
end

xmean = tmp;