function oo_=save_display_classical_smoother_results(xparam1,M_,oo_,options_,bayestopt_,dataset_,dataset_info,estim_params_)
% oo_=save_display_classical_smoother_results(xparam1,M_,oo_,options_,bayestopt_,dataset_,dataset_info,estim_params_)
% Inputs:
%   xparam1         [double]        current values for the estimated parameters.
%   M_              [structure]     storing the model information
%   oo_             [structure]     storing the results
%   options_        [structure]     storing the options
%   bayestopt_      [structure]     storing information about priors
%   dataset_        [structure]     storing the dataset
%   dataset_info    [structure]     information about the dataset (descriptive statistics and missing observations)
%   estim_params_   [structure]     storing information about estimated parameters
%
% Outputs:
%   oo_             [structure]     storing the results

% Copyright © 2023 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/>.


gend= dataset_.nobs;
% Set the number of observed variables.
n_varobs = length(options_.varobs);

if options_.occbin.smoother.status && options_.occbin.smoother.inversion_filter
    [~, info, ~, ~, ~, ~, ~, ~, ~, ~, oo_.dr, atT, innov] = occbin.IVF_posterior(xparam1,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,prior_bounds(bayestopt_,options_.prior_trunc),oo_.dr, oo_.steady_state,oo_.exo_steady_state,oo_.exo_det_steady_state);
    if ismember(info(1),[303,304,306])
        fprintf('\nIVF: smoother did not succeed. No results will be written to oo_.\n')
    else
        updated_variables = atT*nan;
        measurement_error=[];
        ys = oo_.dr.ys;
        trend_coeff = zeros(length(options_.varobs_id),1);
        bayestopt_.mf = bayestopt_.smoother_var_list(bayestopt_.smoother_mf);
        options_nk=options_.nk;
        options_.nk=[]; %unset options_.nk and reset it later
        [oo_, yf]=store_smoother_results(M_,oo_,options_,bayestopt_,dataset_,dataset_info,atT,innov,measurement_error,updated_variables,ys,trend_coeff);
        options_.nk=options_nk;
    end
else
    if options_.occbin.smoother.status
        [atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,~,~,P,PK,decomp,Trend,state_uncertainty,oo_,bayestopt_] = occbin.DSGE_smoother(xparam1,dataset_.nobs,transpose(dataset_.data),dataset_info.missing.aindex,dataset_info.missing.state,M_,oo_,options_,bayestopt_,estim_params_,dataset_,dataset_info);
        if oo_.occbin.smoother.error_flag(1)==0
            oo_ = store_smoother_results(M_,oo_,options_,bayestopt_,dataset_,dataset_info,atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,P,PK,decomp,Trend,state_uncertainty);
        else
            fprintf('\nOccbin: smoother did not succeed. No results will be written to oo_.\n')
        end
    else
        [atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,~,~,P,PK,decomp,Trend,state_uncertainty,oo_,bayestopt_] = DsgeSmoother(xparam1,dataset_.nobs,transpose(dataset_.data),dataset_info.missing.aindex,dataset_info.missing.state,M_,oo_,options_,bayestopt_,estim_params_);
        oo_ = store_smoother_results(M_,oo_,options_,bayestopt_,dataset_,dataset_info,atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,P,PK,decomp,Trend,state_uncertainty);
    end
    [oo_,yf]=store_smoother_results(M_,oo_,options_,bayestopt_,dataset_,dataset_info,atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,P,PK,decomp,Trend,state_uncertainty);
end
if ~options_.nograph
    [nbplt,nr,nc,~,~,nstar] = pltorg(M_.exo_nbr);
    if ~exist([M_.dname '/graphs'],'dir')
        mkdir(M_.dname,'graphs');
    end
    if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
        fidTeX = fopen([M_.dname, '/graphs/' M_.fname '_SmoothedShocks.tex'],'w');
        fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation_1.m (Dynare).\n');
        fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
        fprintf(fidTeX,' \n');
    end
    for plt = 1:nbplt
        fh = dyn_figure(options_.nodisplay,'Name','Smoothed shocks');
        nstar0=min(nstar,M_.exo_nbr-(plt-1)*nstar);
        if gend==1
            marker_string{1,1}='-ro';
            marker_string{2,1}='-ko';
        else
            marker_string{1,1}='-r';
            marker_string{2,1}='-k';
        end
        for i=1:nstar0
            k = (plt-1)*nstar+i;
            subplot(nr,nc,i);
            plot([1 gend],[0 0],marker_string{1,1},'linewidth',.5)
            hold on
            plot(1:gend,innov(k,:),marker_string{2,1},'linewidth',1)
            hold off
            name = M_.exo_names{k};
            if ~isempty(options_.XTick)
                set(gca,'XTick',options_.XTick)
                set(gca,'XTickLabel',options_.XTickLabel)
            end
            if gend>1
                xlim([1 gend])
            end
            if options_.TeX
                title(['$' M_.exo_names_tex{k} '$'],'Interpreter','latex')
            else
                title(name,'Interpreter','none')
            end
        end
        dyn_saveas(fh,[M_.dname, '/graphs/' M_.fname '_SmoothedShocks' int2str(plt)],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_SmoothedShocks%s}\n',options_.figures.textwidth*min(i/nc,1),[M_.dname, '/graphs/' M_.fname],int2str(plt));
            fprintf(fidTeX,'\\caption{Smoothed shocks.}');
            fprintf(fidTeX,'\\label{Fig:SmoothedShocks:%s}\n',int2str(plt));
            fprintf(fidTeX,'\\end{figure}\n');
            fprintf(fidTeX,'\n');
        end
    end
    if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
        fprintf(fidTeX,'\n');
        fprintf(fidTeX,'%% End of TeX file.\n');
        fclose(fidTeX);
    end
end
if estim_params_.nvn
    number_of_plots_to_draw = 0;
    index = [];
    for obs_iter=1:n_varobs
        if max(abs(measurement_error(obs_iter,:))) > options_.ME_plot_tol
            number_of_plots_to_draw = number_of_plots_to_draw + 1;
            index = cat(1,index,obs_iter);
        end
    end
    if ~options_.nograph
        [nbplt,nr,nc,~,~,nstar] = pltorg(number_of_plots_to_draw);
        if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
            fidTeX = fopen([M_.dname, '/graphs/' M_.fname '_SmoothedObservationErrors.tex'],'w');
            fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation_1.m (Dynare).\n');
            fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
            fprintf(fidTeX,' \n');
        end
        for plt = 1:nbplt
            fh = dyn_figure(options_.nodisplay,'Name','Smoothed observation errors');
            nstar0=min(nstar,number_of_plots_to_draw-(plt-1)*nstar);
            if gend==1
                marker_string{1,1}='-ro';
                marker_string{2,1}='-ko';
            else
                marker_string{1,1}='-r';
                marker_string{2,1}='-k';
            end
            for i=1:nstar0
                k = (plt-1)*nstar+i;
                subplot(nr,nc,i);
                plot([1 gend],[0 0],marker_string{1,1},'linewidth',.5)
                hold on
                plot(1:gend,measurement_error(index(k),:),marker_string{2,1},'linewidth',1)
                hold off
                name = options_.varobs{index(k)};
                if gend>1
                    xlim([1 gend])
                end
                if ~isempty(options_.XTick)
                    set(gca,'XTick',options_.XTick)
                    set(gca,'XTickLabel',options_.XTickLabel)
                end
                if options_.TeX
                    idx = strmatch(options_.varobs{index(k)}, M_.endo_names, 'exact');
                    title(['$' M_.endo_names_tex{idx} '$'],'Interpreter','latex')
                else
                    title(name,'Interpreter','none')
                end
            end
            dyn_saveas(fh,[M_.dname, '/graphs/' M_.fname '_SmoothedObservationErrors' int2str(plt)],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_SmoothedObservationErrors%s}\n',options_.figures.textwidth*min(i/nc,1),[M_.dname, '/graphs/' M_.fname],int2str(plt));
                fprintf(fidTeX,'\\caption{Smoothed observation errors.}');
                fprintf(fidTeX,'\\label{Fig:SmoothedObservationErrors:%s}\n',int2str(plt));
                fprintf(fidTeX,'\\end{figure}\n');
                fprintf(fidTeX,'\n');
            end
        end
        if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
            fprintf(fidTeX,'\n');
            fprintf(fidTeX,'%% End of TeX file.\n');
            fclose(fidTeX);
        end
    end
end
%%
%%  Historical and smoothed variabes
%%
if ~options_.nograph
    [nbplt,nr,nc,~,~,nstar] = pltorg(n_varobs);
    if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
        fidTeX = fopen([M_.dname, '/graphs/' M_.fname '_HistoricalAndSmoothedVariables.tex'],'w');
        fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation_1.m (Dynare).\n');
        fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
        fprintf(fidTeX,' \n');
    end
    for plt = 1:nbplt
        fh = dyn_figure(options_.nodisplay,'Name','Historical and smoothed variables');
        nstar0=min(nstar,n_varobs-(plt-1)*nstar);
        if gend==1
            marker_string{1,1}='-ro';
            marker_string{2,1}='--ko';
        else
            marker_string{1,1}='-r';
            marker_string{2,1}='--k';
        end
        for i=1:nstar0
            k = (plt-1)*nstar+i;
            subplot(nr,nc,i);
            plot(1:gend,yf(k,:),marker_string{1,1},'linewidth',1)
            hold on
            plot(1:gend,dataset_info.rawdata(:,k),marker_string{2,1},'linewidth',1)
            hold off
            name = options_.varobs{k};
            if ~isempty(options_.XTick)
                set(gca,'XTick',options_.XTick)
                set(gca,'XTickLabel',options_.XTickLabel)
            end
            if gend>1
                xlim([1 gend])
            end
            if options_.TeX
                idx = strmatch(options_.varobs{k}, M_.endo_names,'exact');
                title(['$' M_.endo_names_tex{idx} '$'],'Interpreter','latex')
            else
                title(name,'Interpreter','none')
            end
        end
        dyn_saveas(fh,[M_.dname, '/graphs/' M_.fname '_HistoricalAndSmoothedVariables' int2str(plt)],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_HistoricalAndSmoothedVariables%s}\n',options_.figures.textwidth*min(i/nc,1),[M_.dname, '/graphs/' M_.fname],int2str(plt));
            fprintf(fidTeX,'\\caption{Historical and smoothed variables.}');
            fprintf(fidTeX,'\\label{Fig:HistoricalAndSmoothedVariables:%s}\n',int2str(plt));
            fprintf(fidTeX,'\\end{figure}\n');
            fprintf(fidTeX,'\n');
        end
    end
    if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
        fprintf(fidTeX,'\n');
        fprintf(fidTeX,'%% End of TeX file.\n');
        fclose(fidTeX);
    end
end
