function plot_simulation(M_, options_, data, var_list, config)
%PLOT_SIMULATION Plot time series simulation results using standard Dynare utilities
%
% SYNTAX:
%   heterogeneity.plot_simulation(M_, options_, data, var_list, config)
%
% INPUTS:
%   M_         [struct]  Dynare model structure
%   options_   [struct]  Dynare options structure
%   data       [matrix]  Simulation data [n_endo × T] (typically oo_.endo_simul)
%   var_list   [cell]    List of variable names to plot
%   config     [struct]  Configuration structure with fields:
%       .figure_title    [string]  Figure window title
%       .filename_suffix [string]  Suffix for saved files (e.g., '_simulation')
%       .tex_caption     [string]  Caption for LaTeX output
%       .tex_label       [string]  Label for LaTeX figure references
%
% OUTPUTS:
%   none (creates and saves figures, optionally generates TeX file)
%
% DESCRIPTION:
%   Plots time series simulation results using standard Dynare utilities:
%   - pltorg() for automatic subplot layout
%   - dyn_figure() for figure creation respecting nodisplay option
%   - dyn_saveas() for saving in multiple formats
%   - Supports TeX labels via options_.TeX
%   - Generates LaTeX figure loader when options_.TeX and EPS format requested

% Copyright © 2025 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/>.
%
% Original author: Normann Rion <normann@dynare.org>

%% Input validation
if isempty(data) || isempty(var_list)
    return;
end

TeX = options_.TeX;
T = size(data, 2);

%% Get variable indices
n_vars = length(var_list);
var_indices = zeros(n_vars, 1);
for i = 1:n_vars
    idx = find(strcmp(var_list{i}, M_.endo_names), 1);
    if isempty(idx)
        error('heterogeneity:plot_time_series:UnknownVariable', ...
              'Variable "%s" not found in M_.endo_names.', var_list{i});
    end
    var_indices(i) = idx;
end

%% Create graphs directory if needed (for graphs or TeX output)
if ~options_.nograph || (TeX && any(strcmp('eps', cellstr(options_.graph_format))))
    if ~isfolder([M_.dname '/graphs'])
        mkdir(M_.dname, 'graphs');
    end
end

%% Open TeX file if needed
if TeX && any(strcmp('eps', cellstr(options_.graph_format)))
    fidTeX = fopen([M_.dname, '/graphs/' M_.fname config.filename_suffix '.tex'], 'w');
    fprintf(fidTeX, '%% TeX eps-loader file generated by heterogeneity.plot_time_series (Dynare).\n');
    fprintf(fidTeX, ['%% ' datestr(now, 0) '\n']);
    fprintf(fidTeX, ' \n');
else
    fidTeX = -1;
end

%% Compute subplot layout
[nbplt, nr, nc, lr, lc, nstar] = pltorg(n_vars);

if nbplt == 0
    % Nothing to plot
    if fidTeX > 0
        fclose(fidTeX);
    end
    return;
end

%% Plot figures
if ~options_.nograph
    if nbplt == 1
        % Single figure
        hh_fig = dyn_figure(options_.nodisplay, 'Name', config.figure_title);
        for j = 1:n_vars
            subplot(nr, nc, j);
            plot(1:T, data(var_indices(j), :), '-k', 'LineWidth', 1);
            if TeX
                title(['$' M_.endo_names_tex{var_indices(j)} '$'], 'Interpreter', 'latex');
            else
                title(var_list{j}, 'Interpreter', 'none');
            end
            xlim([1 T]);
            remove_fractional_xticks;
        end
        dyn_saveas(hh_fig, [M_.dname '/graphs/' M_.fname config.filename_suffix], options_.nodisplay, options_.graph_format);

        if fidTeX > 0
            fprintf(fidTeX, '\\begin{figure}[H]\n');
            fprintf(fidTeX, '\\centering \n');
            fprintf(fidTeX, '\\includegraphics[width=%2.2f\\textwidth]{%s%s}\n', options_.figures.textwidth*min(n_vars/nc, 1), [M_.dname, '/graphs/' M_.fname], config.filename_suffix);
            fprintf(fidTeX, '\\caption{%s}\n', config.tex_caption);
            fprintf(fidTeX, '\\label{Fig:%s}\n', config.tex_label);
            fprintf(fidTeX, '\\end{figure}\n');
            fprintf(fidTeX, ' \n');
        end
    else
        % Multiple figures
        for fig = 1:nbplt-1
            hh_fig = dyn_figure(options_.nodisplay, 'Name', [config.figure_title ' figure ' int2str(fig)]);
            for plt = 1:nstar
                subplot(nr, nc, plt);
                idx = (fig-1)*nstar + plt;
                plot(1:T, data(var_indices(idx), :), '-k', 'LineWidth', 1);
                if TeX
                    title(['$' M_.endo_names_tex{var_indices(idx)} '$'], 'Interpreter', 'latex');
                else
                    title(var_list{idx}, 'Interpreter', 'none');
                end
                xlim([1 T]);
                remove_fractional_xticks;
            end
            dyn_saveas(hh_fig, [M_.dname '/graphs/' M_.fname config.filename_suffix int2str(fig)], options_.nodisplay, options_.graph_format);

            if fidTeX > 0
                fprintf(fidTeX, '\\begin{figure}[H]\n');
                fprintf(fidTeX, '\\centering \n');
                fprintf(fidTeX, '\\includegraphics[width=%2.2f\\textwidth]{%s%s%s}\n', options_.figures.textwidth*min(plt/nc, 1), [M_.dname, '/graphs/' M_.fname], config.filename_suffix, int2str(fig));
                fprintf(fidTeX, '\\caption{%s}\n', config.tex_caption);
                fprintf(fidTeX, '\\label{Fig:%s:%s}\n', config.tex_label, int2str(fig));
                fprintf(fidTeX, '\\end{figure}\n');
                fprintf(fidTeX, ' \n');
            end
        end

        % Last figure (may have fewer plots)
        hh_fig = dyn_figure(options_.nodisplay, 'Name', [config.figure_title ' figure ' int2str(nbplt)]);
        m = 0;
        for plt = 1:n_vars-(nbplt-1)*nstar
            m = m + 1;
            subplot(lr, lc, m);
            idx = (nbplt-1)*nstar + plt;
            plot(1:T, data(var_indices(idx), :), '-k', 'LineWidth', 1);
            if TeX
                title(['$' M_.endo_names_tex{var_indices(idx)} '$'], 'Interpreter', 'latex');
            else
                title(var_list{idx}, 'Interpreter', 'none');
            end
            xlim([1 T]);
            remove_fractional_xticks;
        end
        dyn_saveas(hh_fig, [M_.dname '/graphs/' M_.fname config.filename_suffix int2str(nbplt)], options_.nodisplay, options_.graph_format);

        if fidTeX > 0
            fprintf(fidTeX, '\\begin{figure}[H]\n');
            fprintf(fidTeX, '\\centering \n');
            fprintf(fidTeX, '\\includegraphics[width=%2.2f\\textwidth]{%s%s%s}\n', options_.figures.textwidth*min(m/lc, 1), [M_.dname, '/graphs/' M_.fname], config.filename_suffix, int2str(nbplt));
            fprintf(fidTeX, '\\caption{%s}\n', config.tex_caption);
            fprintf(fidTeX, '\\label{Fig:%s:%s}\n', config.tex_label, int2str(nbplt));
            fprintf(fidTeX, '\\end{figure}\n');
            fprintf(fidTeX, ' \n');
        end
    end
end

%% Close TeX file
if fidTeX > 0
    fprintf(fidTeX, ' \n');
    fprintf(fidTeX, '%% End Of TeX file. \n');
    fclose(fidTeX);
end

end
