function [y0,k0,y1,g1,ci] = stackdata(y,options)
% STACKDATA  [Not a public function] Re-arrange data for VAR estimation.
%
% Backend IRIS function.
% No help provided.

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

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

[ny,nper,nalt] = size(y);

% Only one set of cointegrating vectors allowed.
ci = options.cointeg;
if isempty(ci)
    ci = zeros(0,1+ny);
else
    if size(ci,2) == ny
        ci(:,end+1,:) = 1;
        ci = ci(:,[end,1:end-1]);
    end
end

if ~options.diff
    % Level VAR
    p = options.order;
    t = p+1 : nper;
    g1 = zeros(0,nper-p,nalt);
    y0 = y(:,t,:);
    y1 = zeros(0,nper-p,nalt);
    for i = 1 : p
        y1(end+(1:ny),:,:) = y(:,t-i,:);
    end
    k0 = ones(1,nper-p);
else
    % Difference VAR or VEC.
    % Difference VAR/VEC order is p-1.
    p = options.order - 1;
    t = p+1 : nper;
    % Difference data.
    dy = nan(size(y));
    dy(:,2:end,:) = y(:,2:end,:) - y(:,1:end-1,:);
    % Current dated and lagged differences of endogenous variables.
    % Add cointegrating vector and differentiate data.
    ng = size(ci,1);
    g1 = zeros([ng,nper-p,nalt]);
    kg = ones([1,nper-p]);
    if ~isempty(ci)
        for iloop = 1 : nalt
            % First lag.
            x = nan(size(y));
            x(:,2:end,iloop) = y(:,1:end-1,iloop);
            % Lagged co-integrating vector.
            g1(:,:,iloop) = ci*[kg;x(:,t,iloop)];
        end
    end
    y0 = dy(:,t,:);
    y1 = zeros(0,nper-p,nalt);
    for i = 1 : p
        y1(end+(1:ny),:,:) = dy(:,t-i,:);
    end
    k0 = ones([1,nper-p]);
    % Remove first period of observations. This is because the data are
    % expected to be consistent with VAR(order) not VAR(order-1).
    y0(:,1,:) = [];
    y1(:,1,:) = [];
    k0(:,1,:) = [];
    g1(:,1,:) = [];
end

% Constant vector.
if ~options.constant
    k0 = k0([],:,:);
end

end
