function [PHI_U,PHI_S,B_S,PHI_v] = REE_lin_solve(A,B,C,PI)

%REE_lin_solve    RE solution for 1st-order linear exp. diff. system
%                 VERSION 2
%     
%   REE_lin_solve(A,B,C,PI) calculates solution matrices using method 
%     described in posted notes, "RE Solutions of Linear Dynamic 
%     Stochastic Models."  
%
%   A = Cell array of coefficient matrices for intratemporal Euler equations
%   B = Cell array of coefficient matrices for intertemporal Euler equations
%   B = Cell array of coefficient matrices for constraints
%   PI = Matrix of autoregressive coefficients for exogenous variables

%Extract coefficient matrices from cell arrays
Av = A{1};  Alam = A{2};  Ak = A{3};  Az = A{4};
Bv = B{1};  Blam1 = B{2};  Bk = B{3};  Bz = B{4};  Blam0 = B{5};
Ck1 = C{1};  Cv = C{2};  Ck0 = C{3};  Cz = C{4};

l = size(Av,1);
s = size(Bv,1);
m = size(Ck1,1);
d = size(Az,2);

%Representation in terms of co-state, state and exogenous variables
D1 = [Blam1 Bk; zeros(m,m) Ck1]-[Bv; zeros(m,l)]*inv(Av)*[Alam Ak];
D0 = [Blam0 zeros(s,s); zeros(m,m) Ck0]-[zeros(s,l); Cv]*inv(Av)*[Alam Ak];
Dz1 = [-Bz; zeros(m,d)]+[Bv; zeros(m,l)]*inv(Av)*Az;
Dz0 = [zeros(s,d); Cz]-[zeros(s,l); Cv]*inv(Av)*Az;

A1 = [D1 zeros(m+s,d); zeros(d,m+s) eye(d)];
A0 = [D0 Dz0+Dz1*PI; zeros(d,m+s), PI];
B0 = [zeros(m+s,d); eye(d)];

%Reduced form system
A = A1\A0;
B = A1\B0;

%Calculate REE using Sims' method
[V,L] = eig(A);
[L_sort,I] = sort(diag(L),'descend');
V = V(:,I);
LAM = diag(L_sort);
V_US = V(1,2:end);
V_SS = V(2:end,2:end);
LAM_S = LAM(2:end,2:end);
PHI_U = V_US/V_SS;          %Solution for lam_t
PHI_S = V_SS*LAM_S/V_SS;    %Solution for k_t+1, z_t+1
B_S = B(2:end,:);
PHI_v = -Av\[Alam Ak Az];   %Solution for v_t
%Test by plugging into reduced form
LHS_Y = [PHI_U*PHI_S; PHI_S];
RHS_Y = A*[PHI_U; eye(size(V_SS,1))];
LHS_eps = [zeros(1,size(B,2)); B_S];
RHS_eps = B;
test_LHS = [LHS_Y LHS_eps];
test_RHS = [RHS_Y RHS_eps];
if max(abs(test_LHS(:)-test_RHS(:))) > 1.0e-12
    error('Not a solution')
end

%                                               G. Ramey - UCSD - 4/24/2019

