function [x,t] = bpass(x,band,range,varargin)
% bpass  Band-pass filter.
%
% Syntax
% =======
%
%     [X,T] = bpass(X,BAND,RANGE,...)
%
% Output arguments
% =================
%
% * `X` [ tseries ] - Band-pass filtered tseries object.
%
% * `T` [ tseries ] - Estimated trend tseries object.
%
% Input arguments
% ================
%
% * `X` [ tseries ] - Input tseries object that will be filtered.
%
% * `RANGE` [ numeric | Inf ] Date range on which the data will be
% filtered.
%
% * `BAND` [ numeric ] - Band of periodicities to be retained in the output
% data, `BAND = [LOW,HIGH]`.
%
% Options
% ========
%
% * `'addTrend='` [ *`true`* | `false` ] - Add the estimated linear time trend
% back to filtered output series if `band` includes Inf.
%
% * `'detrend='` [ *`true`* | `false` ] - Remove an estimated time trend from
% the data before filtering.
%
% * `'log='` [ `true` | *`false`* ] - Logarithmise the data before filtering,
% de-logarithmise afterwards.
%
% * `'method='` [ *`'cf'`* | `'hwfsf'` ] - Type of band-pass filter:
% Christiano-Fitzgerald, or h-windowed frequency-selective filter.
%
% * `'unitRoot='` [ *`true`* | `false` ] - Assume unit root in the input
% data.
%
% See help on [`tseries/trend`](tseries/trend) for other options available
% when `'detrend='` is set to true.
%
% Description
% ============
%
% Christiano, L.J. and T.J.Fitzgerald (2003). The Band Pass Filter.
% International Economic Review, 44(2), 435--465.
%
% Iacobucci, A. & A. Noullez (2005). A Frequency Selective Filter for
% Short-Length Time Series. Computational Economics, 25, 75--102.
%
% Example
% ========
%

% -IRIS Toolbox.
% -Copyright (c) 2007-2012 Jaromir Benes.

if nargin < 3
    range = Inf;
end

if length(band) ~= 2 && length(range) == 2
    % Swap input arguments.
    [range,band] = deal(band,range);
end

% Parse input arguments.
P = inputParser();
P.addRequired('x',@istseries);
P.addRequired('band',@(x) isnumeric(x) && length(x) == 2);
P.addRequired('range',@isnumeric);
P.parse(x,band,range);

% Parse options.
[options,varargin] = passvalopt('tseries.bpass',varargin{:});
trendoptions = passvalopt('tseries.trend',varargin{:});

% Obsolete options 'ttrend' has been replaced with 'addtrend'.
if ~isempty(options.ttrend)
    options.addtrend = options.ttrend;
end

%**************************************************************************

if isempty(range) || isnan(x.start)
    x = empty(x);
    t = x;
    return
end

tmpsize = size(x.data);
[xdata,range] = rangedata(x,range);
xdata = xdata(:,:);
start = range(1);

% Run the band-pass filter.
[xdata,tdata] = tseries.mybpass(xdata,start,band,options,trendoptions);

% Output data.
x.data = reshape(xdata,tmpsize);
x.start = range(1);
x = mytrim(x);

% Time trend data.
if nargout > 1
    t = replace(x,reshape(tdata,tmpsize));
    t = mytrim(t);
end

end
