function [] = plot_irf_reporting(irfs, var_list, varargin )
% This function generates the irf plots and irf benchmarking plots along
% with an optional .ps file containing the set of irfs saved under the same fname given as input. 
%
% Maximum 4 series can be plotted at the same time.
%
% REQUIRED INPUTS:
% irfs              [dseries]           Transformed impulse responses (the output of the irf_report function)
% var_list          [cell array]        Cell array of strings of variable names to be plotted
%
% OPTIONAL INPUTS: 
% (If these inputs are specified by the user, their order cannot change i.e.: shock cannot precede title_list)
% title_list        [cell array]        Cell array of strings of subplot titles eg. variable names
%                                       size has to equal to the size of var_list
% shock             [cell array]        Cell array of strings of plot titles eg. the name of the shock
%                                       size has to equal to the size of irfs
%
% PARAMETER INPUTS: 
% (These inputs must be called with their parameter tags in front  if the user wants to specify them, otherwise defualt values are imposed.)
% footnote          [cell array]        Cell array of footnotes as strings, 
%                                       size has to equal to the size of shock
% y_lim             [cell array]        Cell array of ylim specifications as strings eg: 'ylim([-1.5 0.5])', 
%                                       size has to equal to the size of var_list
% legend_%          [string]            Series legends - if one series is plotted, no legend will be displayed
% Series%           [dseries]           Transformed impulse responses of alternative series to be plotted
% var_list_%        [cell array]        Cell array of strings of variable names of alternative series to be plotted
%                                       size has to equal to the size of var_list
% dim1, dim2        [float]             Subplot dimensionality specifications
% disp_type         [string]            Choose if quarters ('Q') or years ('Y') are to be plotted
% disp_range        [float]             Number of period to be plotted. 
%                                       If disp_type is 'Y', the function multiplies disp_range by 4 
%                                       --> specify number of years when defining disp_range in this case
% save              [string]            yes / no                | default: no
% orient            [string]            landscape / portrait    | default: portrait
% format            [string]            fig / png / epsc        | default: fig    
% folder_to_save    [string]            location to save figures
% reporting         [string]            yes / no                | default: no    
% fname             [string]            user specified fname    | default: irfs

% Initializing input parser
p = inputParser;
% Declaring default values (If parameters are not specified by the user, these values act as defaults)
defaultDim1 = 3;
defaultDim2 = 3;
defaultDispType = 'Q';
defaultDisp = 20;
defaultSave = 'no';
defaultOrient = 'portrait';
defaultFormat = 'fig';
defaultReport = 'no';
default_Fname = 'irfs';

p.addRequired('irfs');
p.addRequired('var_list');
p.addParameter('legend_1', @(x)validateattributes(x,{'string'},{'nonempty'}));
% Optional inputs
p.addOptional('title_list', var_list, @iscell);
p.addOptional('shock', @(x)validateattributes(x,{'cell'},{'nonempty'}));
p.addOptional('shock_names', var_list, @iscell)
% Plot settings
p.addParameter('footnote', @(x)validateattributes(x,{'cell'},{'nonempty'}));
p.addParameter('y_lim', @(x)validateattributes(x,{'cell'},{'nonempty'}));
p.addParameter('dim1', defaultDim1, @isfloat);
p.addParameter('dim2', defaultDim2, @isfloat);
p.addParameter('disp_type', defaultDispType, @ischar);
p.addParameter('disp_range', defaultDisp, @isfloat);
% Alternative series
p.addParameter('Series2',@(x)validateattributes(x,{'dseries'},{'nonempty'}))
p.addParameter('var_list_2', @(x)validateattributes(x,{'cell'},{'nonempty'}));
p.addParameter('legend_2', @(x)validateattributes(x,{'string'},{'nonempty'}));
p.addParameter('Series3',@(x)validateattributes(x,{'dseries'},{'nonempty'}))
p.addParameter('var_list_3', @(x)validateattributes(x,{'cell'},{'nonempty'}));
p.addParameter('legend_3', @(x)validateattributes(x,{'string'},{'nonempty'}));
p.addParameter('Series4',@(x)validateattributes(x,{'dseries'},{'nonempty'}))
p.addParameter('var_list_4', @(x)validateattributes(x,{'cell'},{'nonempty'}));
p.addParameter('legend_4', @(x)validateattributes(x,{'string'},{'nonempty'}));
% Saving and reporting settings
p.addParameter('folder_to_save', @(x)validateattributes(x,{'char'}, {'nonempty'}));
p.addParameter('save', defaultSave, @ischar);
p.addParameter('orient', defaultOrient, @ischar);
p.addParameter('format', defaultFormat, @ischar);
p.addParameter('reporting', defaultReport, @ischar);
p.addParameter('fname', default_Fname, @ischar);

p.KeepUnmatched = false;
p.parse(irfs, var_list, varargin{:});

irfs = p.Results.irfs;
var_list = p.Results.var_list;
title_list = p.Results.title_list;
disp_type = p.Results.disp_type;
disp_range = p.Results.disp_range;
fname = p.Results.fname;
orient = p.Results.orient;
irfs_2 = p.Results.Series2;
var_list_2 = p.Results.var_list_2;
irfs_3 = p.Results.Series3;
var_list_3 = p.Results.var_list_3;
irfs_4 = p.Results.Series4;
var_list_4 = p.Results.var_list_4;


% Fixing display (if 'Y' or years are chosen disp_range input is multiplied by 4!)
if strcmp(disp_type, 'Y')
    disp = disp_range * 4;
    date_range = irfs.dates(1:disp);
    zero = zeros(disp, 1);
else
    disp = disp_range;
    date_range = (1:disp);
    zero = zeros(disp, 1);
end

% Initializing figure and color map
figure_ = figure;
fig = gcf;
cmap = ecb_format_color_map;

% Plotting
for ivar = 1:length(var_list)
    varname = var_list{ivar};
    
    if ~isempty(varname)
        subplot(p.Results.dim1, p.Results.dim2, ivar);
        h(1) = plot(date_range, irfs.(varname).data(1:disp), 'Color', cmap(3,:), 'linewidth', 2, 'DisplayName',p.Results.legend_1);
        
        if isdseries(irfs_2)
            varname_2 = var_list_2{ivar};
            if ~isempty(varname_2)
                hold on
                h(2) = plot(date_range, irfs_2.(varname_2).data(1:disp), 'Color', cmap(1,:), 'linewidth', 2, 'DisplayName', p.Results.legend_2);
            end
        end
        
        if isdseries(irfs_3)
            varname_3 = var_list_3{ivar};
            if ~isempty(varname_3)
                hold on
                h(3) = plot(date_range, irfs_3.(varname_3).data(1:disp), '--', 'Color', cmap(1,:), 'linewidth', 2, 'DisplayName', p.Results.legend_3);
            end
        end
        
        if isdseries(irfs_4)
            varname_4 = var_list_4{ivar};
            if ~isempty(varname_4)
                hold on
                
                h(4) = plot(date_range, irfs_4.(varname_4).data(1:disp), '-.', 'Color', cmap(1,:), 'linewidth', 2, 'DisplayName', p.Results.legend_4);
            end
        end
        
        % Adding line to indicate 0 level
        hold on
        h(5) = plot(date_range, zero, ':', 'Color', 'black', 'linewidth', 1);
        
        % Adding subplot titles
        tt = title(strrep(title_list{ivar}, '_', '\_'));
        % ECB subplot title formatting
        tt.FontSize = 10;
        tt.FontName = 'arial';
        tt.Color = [0 50/255 153/255];
        
        % Fixing axes
        ax = gca;
        % ECB Formatting
        ax.FontSize = 8;
        ax.FontName = 'arial';
        ax.XColor = [83/255 83/255 83/255];
        ax.YColor = [83/255 83/255 83/255];
        % Set fontsize and grid
        set(gca,'FontSize', 9)
        set(gca,'YGrid','on')
        set(gca,'XGrid','on')
        
        if strcmp(disp_type, 'Y')
            end_date = irfs.(varname).dates(1) + disp;
            end_date = end_date.time(1);
            start_date = irfs.(varname).dates(1).time(1);
            xlim([start_date end_date]);
            
            % Fixing display range (only 5Y intervals are shown when disp_range > 10Y
            if disp_range < 10
                xticks(start_date:end_date);
                tmp2 = strtrim(cellstr(num2str((1:disp)'))');
                xticklabels(['0', strcat(tmp2,'Y')]);
            else
                xticks(start_date:5:end_date);
                tmp2 = strtrim(cellstr(num2str((5:5:disp)'))');
                xticklabels(['0', strcat(tmp2,'Y')]);
            end
        else
            xlim([1 disp])
        end
       
        % Adding y_lim argument if y axis are to be aligned 
        if iscell(p.Results.y_lim)
            eval(p.Results.y_lim{ivar});
        end
    end
end

% Adding legend when more than one series is plotted
if ischar(p.Results.legend_2) || ischar(p.Results.legend_3) || ischar(p.Results.legend_4) 
    for i=1:length(h)
        try legend_ = h(length(h)+1-i).DisplayName;
        catch
            continue
        end
        if ~isempty(legend_)
            tmp = length(h)+1-i;
            break
        end
    end
    
    if ~isequal(tmp,1)
        lgd = legend(h(1:tmp));
        % ECB legend formatting
        lgd.FontSize = 8;
        lgd.Position = [0.466992187040548 0.0213027591145009 0.102994792585572 0.0272606388051459];
        lgd.FontName    = 'arial';
        lgd.Orientation = 'horizontal';
        lgd.TextColor   = [83/255 83/255 83/255];
        lgd.Box   = 'off';
    end
end

% Adding plot title
if iscell(p.Results.shock)
    a = axes;
    a.Visible = 'off';
    t1 = title(p.Results.shock);
    t1.Visible = 'on';
    t1_pos = get( t1 , 'position');
    t1_pos(2) = 1.055;
        % ECB title formatting
        t1.FontSize = 12;
        t1.FontName = 'arial';
        t1.Color    = [0 50/255 153/255];
    set(t1 , 'position' , t1_pos);
end

% Adding footnote
if iscell(p.Results.footnote)
    an_pos = [0.1244375 0.0443925233644859 0.806291666666667 0.0432242990654204];
    an_ = annotation(figure_,'textbox', an_pos);
    an_.String = [p.Results.footnote 'All impulse responses are reported as percentage deviations from the steady state, except for the impulse responses of inflation and interest rates which are reported as annualised percentage-point deviations.'] ;
    an_.LineStyle = 'none';
    an_.FontSize = 8;
    an_.FontName = 'arial';
    an_.Color = [0 50/255 153/255];
    an_.FitBoxToText = 'off';
end

% Setting figures to screen size
% set(fig, 'Position', get(0, 'Screensize'));

%% Saving figures
% Universal settings
set(fig,'PaperPositionMode','auto','PaperUnits','centimeters');

% Settings for different orientations
if strcmp(orient, 'portrait')
    set(fig,'PaperOrientation', 'portrait','PaperPosition',[0.63 0.63 19.72 28.41]);
else
    set(fig,'PaperOrientation', 'landscape','PaperPosition',[0.63 0.63 29.5 20]);
end

% Generating the unique naming
date_ = char(datetime('now'));
name = [fname  '_' date_(4:6) '-' date_(1:2)];
name_fig = [name '_shock'  p.Results.shock{1,1}(8)];

% Specifying folder
if sum(strcmp(p.Results.folder_to_save, cellstr(ls()))) == 0
    if ~exist(p.Results.folder_to_save, 'dir')
        mkdir(p.Results.folder_to_save);
    end
end

path_main = which('europa_backward.mod');
path_main = path_main(1:end-19);
fpath = strcat(path_main,p.Results.folder_to_save);
    
    % Version control for figure file naming
    if strcmp(p.Results.save, 'yes')
        list_input = cellstr(ls([fpath]));
        s = sum(strncmp(name_fig, list_input, length(name_fig)));
        name_fig = [name_fig '_v' int2str(s+1)];
        saveas(fig,fullfile(fpath, name_fig), p.Results.format);
    end
    
    % Creat .ps file when reporting is turned on
    if strcmp(p.Results.reporting, 'yes')
        
        % Version control for .ps file naming
        dirpsfiles = dir([fpath filesep() '*.ps']);
        if isempty(dirpsfiles)
            s = 0;
        else
            list_input = {dirpsfiles.name};
            s = sum(strncmp(name, list_input, length(name)));
        end
        
        if  sum(strcmp(p.Results.shock{1,1}(8), '1')) == 1 && sum(strcmp(p.Results.shock{1,1}(9), ':')) == 1
            name_ps = [name '_v' int2str(s+1) '.ps'];
            print(fig, '-dpsc', fullfile(fpath, name_ps));
        else
            name_ps = [name '_v' int2str(s) '.ps'];
            print(fig, '-dpsc', '-append', fullfile(fpath, name_ps));
        end
        
        if ~isempty(p.Results.shock_names)
            name_pdf = [name '_' p.Results.shock_names{1} '.pdf'];
            print(fig, '-dpdf', fullfile(fpath, name_pdf));
        end
    end
end