function [x,tt,ts] = trend(x,range,varargin)
% trend  Estimate a time trend.
%
% Syntax
% =======
%
%     x = trend(x,range)
%
% Input arguments
% ================
%
% * `x` [ tseries ] - Input time series.
%
% * `range` [ tseries ] - Range for which the trend will be computed.
%
% Output arguments
% =================
%
% * `x` [ tseries ] - Output trend time series.
%
% Options
% ========
%
% * `'break='` [ numeric | *empty* ] - Vector of breaking points at which
% the trend may change its slope.
%
% * `'connect='` [ *`true`* | `false` ] - Works only with `'diff=' true`.
% Connect the first and last observations; otherwise the filtered series is
% centred on zero.
%
% * `'diff='` [ `true` | *`false`* ] - Estimate the trend on differenced data.
%
% * `'log='` [ `true` | *`false`* ] - Logarithmise the input data,
% de-logarithmise the output data.
%
% * `'season='` [ `true` | *`false`* | `2` | `4` | `6` | `12` ] - Include
% deterministic seasonal factors in the trend.
%
% Description
% ============
%
% Example
% ========
%

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

if nargin < 2
    range = Inf;
end

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

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

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

[xdata,range] = rangedata(x,range);
tmpsize = size(xdata);
xdata = xdata(:,:);

% Compute the trend.
[xdata,ttdata,tsdata] = tseries.mytrend(xdata,range(1),options);
xdata = reshape(xdata,tmpsize);

% Output data.
x = replace(x,xdata,range(1));
x = mytrim(x);
if nargout > 1
    tt = replace(x,reshape(ttdata,tmpsize));
    tt = mytrim(tt);
    if nargout > 2
        ts = replace(x,reshape(tsdata,tmpsize));
        ts = mytrim(ts);
    end
end

end