% Plot and save impulse responses
clear;
clc;
close all;

ModelNames  = {'XMAS_comp_A2'};	
           
for q=1:length(ModelNames)
     
    DIR=['figs_' ModelNames{q}];
    LOC_final = [pwd '\' DIR];
    
    %                mat file          legend name
%     model_names = [{'BASE',           'BASE';
%                    ModelNames{q},     ModelNames{q};
%                   }];
%        model_names = {'BASE',      'BASE';
%                       'BASE_2',    'BASE alt2';
%                       'BASE_10',    'BASE alt10';
%                       'BASE_11',    'BASE alt11';
%                       };  
                  
       model_names = {
                      %'results_ipom_calvo_sep2018',          'IPoM Sep18 (Calvo)';
                    % 'results_ipom_search_dic2018',         'IPoM Dic18 (Search)';
                      %'results_search_DTBC',         'DTBC (Search)';
                     %'mh1',         'IPoM mh1 (Search)';
                     %'mhdelta',         'IPoM mhdelta (Search)';
                     'XMAS_base_results',         'base';
                     'XMAS_rhoeR0_results',         'rho eR 0';
                     'XMAS_alphaPI3_results',         'alpha PI 3';
                      };                 
    
    %                Name        Latex name        shock scale    long_name
    Impulse     = {	'a'          ,'a'               , 1           ,'Permanent Technology';
%                     'z'          ,'z'               , 1           ,'Transitory Technology';
%                    'zA'         ,'z^A'             , 1           ,'Agriculture Technology';
%                     'zCo'        ,'z^{Co}'          , 1           ,'Commodity Technology';
%                      'varomega'   ,'\varpi'           , 1            ,'Non-Commodity Investment';
%                      'varomegaCo' ,'\omega^{Co}'      , 1            ,'Commodity Investment';
%                      %'varomegaCo' ,'\omega^{Co}'     , 1           ,'Commodity Investment';
%                      %'varomegaCo2' ,'\omega^{Co2}'     , 1           ,'Commodity Investment 2';
%                      'kappa'      ,'\kappa'          , 1           ,'Labor Supply';
%                      'varrho'     ,'\upsilon'        , 1           ,'Preference';   
                     'eR'         ,'e^R'             , 1/0.4          ,'Monetary Policy Rule';
                     %'pibar'      ,'\bar{\pi}'       , 1           ,'Short-Run Inflation Target';
%                      'xiO'       ,'\xi_{p^{O}}'     , 1           ,'Domestic Oil Price';
%                     'zetao'      ,'\zeta^o'         , 1           ,'Observed Country Premium';
%                      'zetau'      ,'\zeta^u'         , 1           ,'Unobserved Country Premium';                 
%                      'zstar'      ,'z^*'             , 1           ,'Foreign GDP';
%                      'xistar'     ,'\pi^*'           , 1           ,'Foreign Inflation';
%                      'Rstar'      ,'R^*'             , 1           ,'Foreign Interest Rate';
%                      'xiCostar'  ,'\xi^{p^{Co*}}'   , 1           ,'International Commodity Price';
%                      'piFstar'   ,'\pi^{F*}'       , 1           ,'global price shock';
%                     'xiOstar'   ,'\xi^{p^{O*}}'    , 1           ,'International Oil Price';
%                     'xiMstar'   ,'\xi^{p^{M*}}'    , 1           ,'Foreign Import Price';
%                     
%                     'xiCG'       ,'\xi^{C^G}'       , 1           ,'Government Consumption';
% 
%                     'xiIG'       ,'\xi^{I^G}'       , 1           ,'Government Investment';
%                     'xiTR'       ,'\xi^{TR}'        , 1           ,'Transfer Payment';
                    
             
        };
      
    
    %                Name         Latex Name    Cusum      Factor    Div_ss
    Response    = {	%'gam_Y'      ,'Y'            ,1        ,1       ,0;
                    'gam4_Y'      ,'crec Y'            ,0        ,1       ,0;
                    'gam_YR'      ,'YR'           ,1        ,1       ,0;
                    %'gam_YCo'      ,'YCo'           ,1        ,1       ,0;
                    'gam_C'       ,'C'            ,1        ,1       ,0;
                    'cG'       ,'cG'            ,0        ,1       ,1;
                    
                    'stb'         ,'TB/Y'         ,0        ,1       ,0;                
                    'gam_I'       ,'I'            ,1        ,1       ,0;
                    %'gam_ICo'     ,'I^{Co}'       ,1        ,1       ,0;
                    %'pi'          ,'4\pi'         ,0        ,4       ,0;
                    'pi4'          ,'pi ann'         ,0        ,1       ,0;
                    'piZ'          ,'4\pi Z'         ,0        ,4       ,0;
                    %'piF'          ,'4\pi F'         ,0        ,4       ,0;
                    %'piH'          ,'4\pi H'         ,0        ,4       ,0;
                    
                    %'gam_HN_obs'   	,'htot'         ,1        ,0.01    ,0;
                   % 'u'             ,'u'       ,0        ,1       ,0;  
                    %'n'             ,'n'       ,0        ,1       ,1;  
                    %'h'             ,'h'       ,0        ,1       ,1;    
                    'gam_W'       ,'W'            ,1        ,1       ,0;
                    'rer'         ,'rer'          ,0        ,1       ,1;
                    'R'           ,'4R'           ,0        ,4       ,1;
                     };
    
    plot_options.n_col      = 4;
    plot_options.n_row      = 3;
    plot_options.marks      = {'-b','-.r','-.g','-.k'};
    plot_options.horizon    = 20;
    plot_options.grid       = 1;
    plot_options.latex      = 1;
    
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

plot_options.model_names= model_names(:,1)';
legend_names            = model_names(:,2)';

shocks                  = Impulse(:,1)';
shocks_latex            = Impulse(:,2)';
shocks_scale            = Impulse(:,3)';
shocks_long_name        = Impulse(:,4)';

v_sel                   = Response(:,1)';
v_name                  = Response(:,2)';
plot_options.v_do_cusum = cell2mat(Response(:,3)');
plot_options.v_adj      = cell2mat(Response(:,4)');
plot_options.v_div_ss   = cell2mat(Response(:,5)');

plot_options.v_do_cusum = [plot_options.v_do_cusum 	0];  	% shock doesn't sum over
plot_options.v_div_ss   = [plot_options.v_div_ss 	1];    	% shock divided by its ss
plot_options.v_adj_orig = [plot_options.v_adj  		1]*100;	% no adjustment for shock

if exist(LOC_final, 'file')==7
    rmdir(LOC_final,'s')
end
mkdir(LOC_final)

for ii=1:length(plot_options.model_names)
    %disp(['loading data for ' plot_options.model_names{ii} ' (' num2str(ii) '/'  num2str(length(plot_options.model_names)) ')']);
    
    %name_mat=[plot_options.model_names{ii} '.mat'];
    %copyfile(['..\' name_mat],name_mat)
    
    load([plot_options.model_names{ii} '.mat'])
    eval(['data.M_.' plot_options.model_names{ii} '=M_;'])
    eval(['data.oo_.' plot_options.model_names{ii} '=oo_;'])
end


for j=1:size(shocks,2)
    %disp(['plotting IRFs for ' shocks{j} ' (' num2str(j) '/'  num2str(size(shocks,2)) ')']);
    plot_options.u_sel=shocks(j);
    if size(plot_options.model_names,2)>1
        for i=2:size(plot_options.model_names,2)
            plot_options.u_sel=[plot_options.u_sel shocks(j)];
        end
    end
    plot_options.v_sel  = [v_sel shocks(j)];
    plot_options.u_name = shocks_latex(j);
    plot_options.v_name = [ v_name shocks_latex(j)];
    plot_options.v_adj  = shocks_scale{j} * plot_options.v_adj_orig;
    
    
    irf_full.(shocks{j})=ir2(plot_options,data)
   % plots_for_dynare(plot_options,data)
    h=legend(legend_names);
    set(h,'Position',[0.4 0 0.23 0.03],...
        'Orientation','Horizontal',...
        'Fontsize',8,...
        'Interpreter','Latex');
    legend('boxoff')
    
    
    fig_ratio=16/9;
    trim_hor=0.6;
    trim_top=0.05;
    saveplot(['irf_' shocks{j}],fig_ratio,trim_hor,trim_top,LOC_final)
    
end

% for ii=1:length(plot_options.model_names)
%     name_mat=[plot_options.model_names{ii} '.mat'];
%     delete(name_mat)
% end


% Generate pdf file with all the graphs
latex_filename = [DIR '.tex'];

LATEX_LINE = ['\\documentclass{article}', '\n\n'];
LATEX_LINE = [LATEX_LINE, '\\usepackage[utf8]{inputenc}', '\n'];
LATEX_LINE = [LATEX_LINE, '\\usepackage{geometry}', '\n'];
LATEX_LINE = [LATEX_LINE, '\\geometry{verbose,tmargin=2cm,bmargin=2cm,lmargin=2cm,rmargin=2cm}', '\n'];
LATEX_LINE = [LATEX_LINE, '\\usepackage{amsmath}', '\n'];
LATEX_LINE = [LATEX_LINE, '\\usepackage{amssymb}', '\n'];
LATEX_LINE = [LATEX_LINE, '\\usepackage{graphicx}', '\n'];
LATEX_LINE = [LATEX_LINE, '\\makeatletter', '\n\n'];
LATEX_LINE = [LATEX_LINE, '\\begin{document}'];

LATEX_LINE = [LATEX_LINE,	'\n\n'];

for ii=1:length(shocks(1,:))
    NAME_FIG   = ['irf_' shocks{1,ii}];
    TITLE_FIG  = shocks_long_name{1,ii};
    
    LATEX_LINE = [LATEX_LINE,	'\\begin{figure}'];
    LATEX_LINE = [LATEX_LINE,	'\n',       '\\caption{' TITLE_FIG ' Shock}'];
    LATEX_LINE = [LATEX_LINE,	'\n',       '\\begin{center}'];
    LATEX_LINE = [LATEX_LINE,	'\n',       '\\includegraphics{' NAME_FIG '.pdf}'];
    LATEX_LINE = [LATEX_LINE,	'\n',       '\\end{center}'];
    LATEX_LINE = [LATEX_LINE,	'\n',       '\\end{figure}'];
    
    LATEX_LINE = [LATEX_LINE,	'\n\n'];
end

LATEX_LINE = [LATEX_LINE, '\\end{document}'];

if exist(latex_filename,'file')==2
    delete(latex_filename);
end
fid = fopen(latex_filename,'at');    %%% open the file
fprintf(fid,LATEX_LINE);             %%% append the extra code
fclose(fid);                         %%% close the file (the new tex file is generated)
movefile(latex_filename,LOC_final)

%addpath('C:\Program Files\MiKTeX 2.9-1\miktex\bin')
%[status,cmdout] = system(['pdflatex ' latex_filename]); %%% compile the tex file into a pdf
%rmpath('C:\Program Files\MiKTeX 2.9-1\miktex\bin')
disp(['Done for ' ModelNames{q}])
end
