function this = moving(this,varargin)
% moving  Apply function to moving window of observations.
%
% Syntax
% =======
%
%     X = moving(X)
%     X = moving(X,RANGE,...)
%
% Input arguments
% ================
%
% * `X` [ tseries ] - Tseries object on whose observations the function
% will be applied.
%
% * `RANGE` [ numeric | Inf ] - Range on which the moving function will be
% applied; `Inf` means the entire range on which the time series is
% defined.
%
% Output arguments
% =================
%
% * `X` [ tseries ] - Output time series.
%
% Options
% ========
%
% * `'function='` [ function_handle | `@mean` ] - Function to be applied to a
% moving window of observations.
%
% * `'window='` [ numeric | *`Inf`* ] - The window of observations where 0
% means the current date, -1 means one period lag, etc. Inf means that the
% last n observations (including the current one) are used, where n is the
% frequency of the input data.
%
% Description
% ============
%
% Example
% ========
%

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

if nargin == 1
    range = Inf;
elseif (nargin > 1 && ischar(varargin{1}))
    range = Inf;
else
    range = setrange(varargin{1});
    varargin(1) = [];
end

options = passvalopt('tseries.moving',varargin{1:end});

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

if isequal(options.window,Inf)
    freq = datfreq(this.start);
    if freq < 1
        options.window = 0;
    else
        options.window = -freq+1:0;
    end
end

if ~(length(range) == 1 && isinf(range))
    this = resize(this,range);
end
this = unop(@tseries.mymoving,this,0,options.window,options.function);

end
