function [this,data] = demean(this,varargin)
% demean  Remove constant from VAR object and demean associated data.
%
% Syntax
% =======
%
%     V = demean(V,...)
%     [V,D] = demean(V,DATA,...)
%
% Input arguments
% ================
%
% * `V` [ VAR ] - VAR object in which the constant vector will be reset to
% zero.
%
% * `D` [ struct | tseries ] - Datase or tseries associated with the VAR
% object from which the uncondional mean will be removed.
%
% Output arguments
% =================
%
% * `V` [ VAR ] - VAR object with the constant vector reset to zero.
%
% * `D` [ struct | tseries ] - Demeaned data.
%
% Description
% ============
%
% Example
% ========
%

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

if ~isempty(varargin) && ~ischar(varargin{1})
    data = varargin{1};
    varargin(1) = [];
else
    data = [];
end

opt = passvalopt('VAR.demean',varargin{:});

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

nalt = size(this.A,3);
stable = isstationary(this);

% Detrend data.
if ~isempty(data) && nargout > 1
    [outputformat,range,y,e] = VAR.datarequest(this,data,Inf,opt);
    nper = numel(range);
    if size(e,3) == 1 && nalt > 1
        y = y(:,:,ones([1,nalt]));
        e = e(:,:,ones([1,nalt]));
    end
    repeat = ones([1,nper]);
    ymean = mean(this);
    for iloop = find(stable)
        y(:,:,iloop) = ...
            y(:,:,iloop) - ymean(:,iloop*repeat);
    end
    data = VAR.outputdata(this,outputformat,range,[y;e],[], ...
        [this.ynames,this.enames]);
end

% Remove constant from VAR.
this.K(:,stable) = 0;

if any(~stable)
    VAR.warning(8,sprintf(' #%g',find(~stable)));
end

end
