%test
%addpath /Applications/Dynare/4.5.1/matlab/

clear all;
dynare FA_check noclearall;


posL=strmatch('L_level',M_.endo_names,'exact');
posC=strmatch('C_level',M_.endo_names,'exact');
posWelf=strmatch('Welf',M_.endo_names,'exact');
posutil=strmatch('util',M_.endo_names,'exact');
posLsq=strmatch('Lsq',M_.endo_names,'exact');
posCsq=strmatch('Csq',M_.endo_names,'exact');


%%% find conditional mean
condmeanC = oo_.dr.ys(posC)+0.5*oo_.dr.ghs2(oo_.dr.inv_order_var(posC)); 
condmeanL = oo_.dr.ys(posL)+0.5*oo_.dr.ghs2(oo_.dr.inv_order_var(posL));
condmeanCsq = oo_.dr.ys(posCsq)+0.5*oo_.dr.ghs2(oo_.dr.inv_order_var(posCsq)); 
condmeanLsq = oo_.dr.ys(posLsq)+0.5*oo_.dr.ghs2(oo_.dr.inv_order_var(posLsq));
condmeanWelf = oo_.dr.ys(posWelf)+0.5*oo_.dr.ghs2(oo_.dr.inv_order_var(posWelf));
%condmeanutil = oo_.dr.ys(posutil)+0.5*oo_.dr.ghs2(oo_.dr.inv_order_var(posWelf));

% deterministic steady state
detststC = (oo_.steady_state(posC));
detststL = (oo_.steady_state(posL));
detststWelf = (oo_.steady_state(posWelf));
detststutil = (oo_.steady_state(posutil));
%detststutil = nlma_theoretical_moments.first_order.mean(posutil);

% conditional variance of C and L
condvarC = condmeanCsq - detststC^2;
condvarL = condmeanLsq - detststL^2;

% calculate conditional welfare from components
condWelf_check = (1/(1-betta)) * (detststutil ...
    + 1/(detststC) * (condmeanC - detststC) ...
    - chi*detststL^varphi * (condmeanL - detststL) ...
    - 0.5/((1+hh)/(((1-hh)*detststC)^2)) * (condmeanC - detststC)^2 ...
    - 0.5*chi*varphi*detststL^(varphi-1) * (condmeanL - detststL)^2);
    %- 0.5/((1+h)/(((1-h)*detststC)^2)) * condvarC ...
    %- 0.5*chi*kappa*detststL^(kappa-1) * condvarL);


condWelf_check
condmeanWelf