%This code saves counterfactual scenarios from a DSGE model to Excel

close all; clear; clc;

NoMig=load('Results_nomig_correct');
Mig=load('Results_mig22Q4_correct');

%Name of Excel file
filename='XMAS_Search_Mig_NoMig_updated.xlsx';

%Variables to be saved
vars={'gam_YR_obs','gam_YCo_obs','gam_C_obs','gam_I_obs','gam_CG_obs','gam_W_obs',...
    'ystar_obs','gam_ICo_obs','gam_TRG_obs','gam_IG_obs','pi_obs','piZ_obs',...
    'piA_obs','piO_obs','pCostar_obs','pOstar_obs','pistar_obs','R_obs',...
    'Rstar_obs','xi_obs','stb_obs','rer_obs','gam_WN_obs',...
    'gam_H_obs','gam_N_obs','urate','gam_Y_obs','mig_share_obs'};

% vars={'gam_YR_obs','yCo_obs','gam_C_obs','gam_I_obs','gam_CG_obs','gam_W_obs',...
%     'ystar_obs','gam_ICo_obs','gam_TRG_obs','gam_IG_obs','pi_obs','piZ_obs',...
%     'piA_obs','piO_obs','pCostar_obs','pOstar_obs','pistar_obs','R_obs',...
%     'Rstar_obs','xi_obs','stb_obs','rer_obs','gam_WN_obs','gam_IR_obs',...
%     'gam_H_obs','gam_N_obs','urate','gam_Y_obs','mig_share_obs'};

%Find position of variables in simulations
idx=zeros(numel(vars),1);
for i=1:numel(idx)
%     idx(i) = find(~cellfun('isempty',strfind(cellstr(M_.endo_names),vars(i))));
    idx(i) = find(strcmp(NoMig.M_.endo_names,vars(i)));
end

%Create matrix with simulated data (original shocks)
NoMig_proy=zeros(86,numel(vars));
for i=1:numel(vars)
    NoMig_proy(:,i)=NoMig.oo_.SmoothedVariables.(deblank(NoMig.M_.endo_names(idx(i),:)));
end

%Create matrix with simulated data (counterfactual scenario)
Mig_proy=zeros(86,numel(vars));
for i=1:numel(vars)
    Mig_proy(:,i)=Mig.oo_.SmoothedVariables.(deblank(Mig.M_.endo_names(idx(i),:)));
end

%Save simulated variables in Excel
xlswrite(filename,NoMig_proy,'NoMig','B2');
xlswrite(filename,vars,'NoMig','B1');
xlswrite(filename,Mig_proy,'Mig','B2');
xlswrite(filename,vars,'Mig','B1');