
% VAR representation of Dynare output
% Variables are reordered (as in original M_.endo_names)
function [Adyn,Bdyn]=dynare_VAR_representation;
oo_=evalin('base','oo_');
M_=evalin('base','M_');
dr_=oo_.dr;
if ~isfield(oo_.dr,'ghx');
    error('No State Space Solution Found');
    Adyn=NaN;
    Bdyn=NaN;
elseif isempty(oo_.dr.ghx);
      error('No States Space Solution Found');
    Adyn=NaN;
    Bdyn=NaN;
end
lgy_=M_.endo_names;
nstat=M_.nstatic;
if isfield(M_,'nspred');% older verisions of Dynare (<4.3.3) had this 
npred=M_.nspred;
else
    npred=M_.npred+M_.nboth;
end;
    

listofvariables=str2cell(lgy_);
shocks=M_.exo_names;

% [i,j]=sort(dr_.order_var);
lgy2_=lgy_(dr_.order_var,:); % variables as appear in the canonical VAR rapresentation
[a,b,c]=intersect(deblank(listofvariables),str2cell(lgy2_));
c=c(:);
listofvariables=a;
%position in forecast vector and VMA representation
for jj=1:length(c);
    eval([deblank(listofvariables{jj}),'_pos=',num2str(length(nstat+[1:npred])+jj),';']);
end

%c is the order in the output; So lgy2_(c,:) should return listofvariables

% Rewrite the law of motion as a state space representation of a VAR
% The VAR matrix includes all the states plus list of variables,
% 
% 
% 
% reordering (from Dynare manual)
% % When reordered, the variables are stored in the following order: static variables, purely predetermined
% % variables (variables that appear only at the current and lagged periods in the model), variables that are
% % both predetermined and forward-looking (variables that appear at the current, future and lagged
% % periods in the model), purely forward-looking variables (variables that appear only at the current and
% % future periods in the model). In each category, the variables are arranged alphabetically.

% The dynamics is fully described by the predetermined variables only.
% so 
% A_var = [dr_.ghx([nstat+[1:npred],c'],:),zeros(size(dr_.ghx([nstat+[1:npred],c'],:),1),length(c))];%[[dr_.ghx(16:37,:);dr_.ghx(4,:);dr_.ghx(11,:);dr_.ghx(38,:)],zeros(size(dr_.ghx,2)+3,3)];
A_var =[zeros(size(lgy_,1),nstat),...
    dr_.ghx,zeros(size(lgy_,1),...
    size(lgy_,1)-npred-nstat)];
% Sigma matrix for VAR representation. 
% Sig_var = dr_.ghu([nstat+[1:npred],c'],:);%[dr_.ghu(16:37,:);dr_.ghu(4,:);dr_.ghu(11,:);dr_.ghu(38,:)] ;
Sig_var = dr_.ghu;%[dr_.ghu(16:37,:);dr_.ghu(4,:);dr_.ghu(11,:);dr_.ghu(38,:)] ;

%REORDER
Adyn=A_var(oo_.dr.inv_order_var,oo_.dr.inv_order_var);
Bdyn=Sig_var(oo_.dr.inv_order_var,:);



