function [y,X,X_prime,k,r,n,T,xx]=prep_data_TV_VAR(Y,p,b_const)

%X is kxnxT
%X_prime is nxkxt
% INPUTS:  Y is nxTp

if nargin < 3
  b_const=true;
end

[n,Tp]=size(Y);  T=Tp-p;
tstart=p+1;
if b_const
    kk=n*p+1; 
else
    kk=n*p;
end

k=n*kk;
r=0.5*n*(n-1);

%preparing matrix for the data
y=Y(:,tstart:end);   
xx=ones(kk,T);
for lag=1:p
    if b_const
        xx( 2+n*(lag-1):lag*n+1,:)=Y(:,tstart-lag:Tp-lag);
    else
         xx( (n*(lag-1)+1):lag*n,:)=Y(:,tstart-lag:Tp-lag);
    end
end
xx_paged=reshape(xx,kk,1,T);
cellxx=mat2cell(xx_paged, kk,1,ones(T,1)); 
X=cell2mat(cellfun(@(x) kron(eye(n),x), cellxx, 'UniformOutput', false));
X_prime=permute(X,[2 1 3]);
