function oo_ = PlotPosteriorDistributions(estim_params_, M_, options_, Prior, oo_)
% oo_ = PlotPosteriorDistributions(estim_params_, M_, options_, Prior, oo_)
% plots posterior distributions
%
% INPUTS
%    estim_params_    [structure]  information on estimated parameters
%    M_               [structure]  information on model
%    options_         [structure]  information on options
%    Prior            [@dprior]    prior information object
%    oo_              [structure]  results
%
% OUTPUTS
%    oo_             [structure]   updated results
%
% SPECIAL REQUIREMENTS
%    none

% Copyright © 2005-2026 Dynare Team
%
% This file is part of Dynare.
%
% Dynare is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Dynare is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Dynare.  If not, see <https://www.gnu.org/licenses/>.

latexDirectoryName = CheckPath('latex',M_.dname);
graphDirectoryName = CheckPath('graphs',M_.dname);

npar = estim_params_.nvx+estim_params_.nvn+estim_params_.ncx+estim_params_.ncn+estim_params_.nsx+estim_params_.nendoinit+estim_params_.np; % total number of estimated parameters
MaxNumberOfPlotPerFigure = 9;% The square root must be an integer!
nn = sqrt(MaxNumberOfPlotPerFigure);

figurename = 'Priors and posteriors';

if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
    fidTeX = fopen([latexDirectoryName filesep M_.fname '_PriorsAndPosteriors.tex'],'w');
    fprintf(fidTeX,'%% TeX eps-loader file generated by PlotPosteriorDistributions.m (Dynare).\n');
    fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
    fprintf(fidTeX,' \n');
end

figunumber = 0;
subplotnum = 0;
for i=1:npar
    subplotnum = subplotnum+1;
    if subplotnum == 1
        figunumber = figunumber+1;
        hh_fig=dyn_figure(options_.nodisplay, 'Name', figurename);
    end
    [nam,texnam] = get_the_name(i, options_.TeX, M_, estim_params_, options_.varobs);
    [x2, f2, binf2, bsup2] = marginal_pdf(Prior, i);
    top2 = max(f2);
    if i <= estim_params_.nvx % estimated stderr parameters for structural shocks (ordered first in xparam1)
        name = M_.exo_names{estim_params_.var_exo(i,1)};
        x1 = oo_.posterior_density.shocks_std.(name)(:,1);
        f1 = oo_.posterior_density.shocks_std.(name)(:,2);
        oo_.prior_density.shocks_std.(name)(:,1) = x2;
        oo_.prior_density.shocks_std.(name)(:,2) = f2;
        if ~issmc(options_) && ~options_.mh_posterior_mode_estimation
            pmod = oo_.posterior_mode.shocks_std.(name);
        end
    elseif i <= estim_params_.nvx+estim_params_.nvn % estimated stderr parameters for measurement errors (ordered second in xparam1)
        name = options_.varobs{estim_params_.nvn_observable_correspondence(i-estim_params_.nvx,1)};
        x1 = oo_.posterior_density.measurement_errors_std.(name)(:,1);
        f1 = oo_.posterior_density.measurement_errors_std.(name)(:,2);
        oo_.prior_density.measurement_errors_std.(name)(:,1) = x2;
        oo_.prior_density.measurement_errors_std.(name)(:,2) = f2;
        if ~issmc(options_) && ~options_.mh_posterior_mode_estimation
            pmod = oo_.posterior_mode.measurement_errors_std.(name);
        end
    elseif i <= estim_params_.nvx+estim_params_.nvn+estim_params_.ncx % estimated corr parameters for structural shocks (ordered third in xparam1)
        j = i - (estim_params_.nvx+estim_params_.nvn);
        k1 = estim_params_.corrx(j,1);
        k2 = estim_params_.corrx(j,2);
        name = sprintf('%s_%s', M_.exo_names{k1}, M_.exo_names{k2});
        x1 = oo_.posterior_density.shocks_corr.(name)(:,1);
        f1 = oo_.posterior_density.shocks_corr.(name)(:,2);
        oo_.prior_density.shocks_corr.(name)(:,1) = x2;
        oo_.prior_density.shocks_corr.(name)(:,2) = f2;
        if ~issmc(options_) && ~options_.mh_posterior_mode_estimation
            pmod = oo_.posterior_mode.shocks_corr.(name);
        end
    elseif i <= estim_params_.nvx+estim_params_.nvn+estim_params_.ncx+estim_params_.ncn % estimated corr parameters for measurement errors (ordered fourth in xparam1)
        j = i - (estim_params_.nvx+estim_params_.nvn+estim_params_.ncx);
        k1 = estim_params_.corrn(j,1);
        k2 = estim_params_.corrn(j,2);
        name = sprintf('%s_%s', M_.endo_names{k1}, M_.endo_names{k2});
        x1 = oo_.posterior_density.measurement_errors_corr.(name)(:,1);
        f1 = oo_.posterior_density.measurement_errors_corr.(name)(:,2);
        oo_.prior_density.measurement_errors_corr.(name)(:,1) = x2;
        oo_.prior_density.measurement_errors_corr.(name)(:,2) = f2;
        if ~issmc(options_) && ~options_.mh_posterior_mode_estimation
            pmod = oo_.posterior_mode.measurement_errors_corr.(name);
        end
    elseif i <= estim_params_.nvx+estim_params_.nvn+estim_params_.ncx+estim_params_.ncn+estim_params_.nsx % estimated skew parameters for structural shocks (ordered fifth in xparam1)
        j = i - (estim_params_.nvx+estim_params_.nvn+estim_params_.ncx+estim_params_.ncn);
        k = estim_params_.skew_exo(j,1);
        name = sprintf('%s', M_.exo_names{k});
        x1 = oo_.posterior_density.shocks_skew.(name)(:,1);
        f1 = oo_.posterior_density.shocks_skew.(name)(:,2);
        oo_.prior_density.shocks_skew.(name)(:,1) = x2;
        oo_.prior_density.shocks_skew.(name)(:,2) = f2;
        if ~issmc(options_) && ~options_.mh_posterior_mode_estimation
            pmod = oo_.posterior_mode.shocks_skew.(name);
        end
    elseif i <= estim_params_.nvx+estim_params_.nvn+estim_params_.ncx+estim_params_.ncn+estim_params_.nsx+estim_params_.nendoinit % estimated init states (ordered sixth in xparam1)
        j = i - (estim_params_.nvx+estim_params_.nvn+estim_params_.ncx+estim_params_.ncn+estim_params_.nsx);
        k = estim_params_.endo_init_vals(j,1);
        name = sprintf('%s', M_.endo_names{k});
        x1 = oo_.posterior_density.init_state.(name)(:,1);
        f1 = oo_.posterior_density.init_state.(name)(:,2);
        oo_.prior_density.init_state.(name)(:,1) = x2;
        oo_.prior_density.init_state.(name)(:,2) = f2;
        if ~issmc(options_) && ~options_.mh_posterior_mode_estimation
            pmod = oo_.posterior_mode.init_state.(name);
        end
    else % estimated structural parameters (ordered last in xparam1)
        j = i - (estim_params_.nvx+estim_params_.nvn+estim_params_.ncx+estim_params_.ncn+estim_params_.nsx+estim_params_.nendoinit);
        name = M_.param_names{estim_params_.param_vals(j,1)};
        x1 = oo_.posterior_density.parameters.(name)(:,1);
        f1 = oo_.posterior_density.parameters.(name)(:,2);
        oo_.prior_density.parameters.(name)(:,1) = x2;
        oo_.prior_density.parameters.(name)(:,2) = f2;
        if ~issmc(options_) && ~options_.mh_posterior_mode_estimation
            pmod = oo_.posterior_mode.parameters.(name);
        end
    end
    top1 = max(f1);
    top0 = max([top1; top2]);
    binf1 = x1(1);
    bsup1 = x1(end);
    borneinf = min(binf1, binf2);
    bornesup = max(bsup1, bsup2);
    subplot(nn, nn, subplotnum)
    hh_plt = plot(x2, f2, '-k', 'linewidth', 2);
    set(hh_plt, 'color', [0.7 0.7 0.7]);
    hold on;
    plot(x1, f1, '-k', 'linewidth', 2);
    if ~issmc(options_) && ~options_.mh_posterior_mode_estimation
        plot([pmod pmod], [0.0 1.1*top0], '--g', 'linewidth', 2);
    end
    box on
    axis([borneinf bornesup 0 1.1*top0])
    if options_.TeX
        title(texnam, 'Interpreter', 'latex')
    else
        title(nam, 'Interpreter', 'none')
    end
    hold off
    drawnow
    if subplotnum == MaxNumberOfPlotPerFigure || i == npar
        dyn_saveas(hh_fig,[graphDirectoryName filesep M_.fname '_PriorsAndPosteriors' int2str(figunumber)], options_.nodisplay, options_.graph_format);
        if options_.TeX && any(strcmp('eps', cellstr(options_.graph_format)))
            fprintf(fidTeX, '\\begin{figure}[H]\n');
            fprintf(fidTeX, '\\centering\n');
            fprintf(fidTeX, '\\includegraphics[width=%2.2f\\textwidth]{%s/%s_PriorsAndPosteriors%s}\n', ...
                    options_.figures.textwidth*min(subplotnum/nn,1), graphDirectoryName, M_.fname, int2str(figunumber));
            fprintf(fidTeX,'\\caption{Priors and posteriors.}');
            fprintf(fidTeX,'\\label{Fig:PriorsAndPosteriors:%s}\n', int2str(figunumber));
            fprintf(fidTeX,'\\end{figure}\n');
            fprintf(fidTeX,' \n');
            if i == npar
                fprintf(fidTeX,'%% End of TeX file.\n');
                fclose(fidTeX);
            end
        end
        subplotnum = 0;
    end
end
