function oo_=perfect_foresight_with_expectation_errors_setup(M_, options_, oo_)
% INPUTS
%   M_                  [structure] describing the model
%   options_            [structure] describing the options
%   oo_                 [structure] storing the results
%
% OUTPUTS
%   oo_                 [structure] storing the results

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

if ~isempty(oo_.initval_series)
    error('perfect_foresight_with_expectation_errors_setup: cannot be used in conjunction with initval_file')
end

[periods, first_simulation_period] = get_simulation_periods(options_);

%% Initialize informational structures
oo_.pfwee.terminal_info = NaN(M_.exo_nbr, periods); % 2nd dimension is informational time
oo_.pfwee.shocks_info = NaN(M_.exo_nbr, periods, periods); % 2nd dimension is real time, 3rd dimension is informational time

if isfile(options_.datafile)
    if ~isempty(M_.det_shocks) || ~isempty(M_.learnt_shocks) || ~isempty(oo_.initial_steady_state) || ~isempty(M_.learnt_endval)
        warning('perfect_foresight_with_expectation_errors_setup: since you passed the datafile option, the contents of shocks and endval blocks will be ignored')
    end
    %% Read CSV file
    %% We can’t use readcell (only in MATLAB ≥ R2019a), so instead rely on csvread and manual hacks
    % Read numeric data, skipping first row and first column
    raw_csv = csvread(options_.datafile, 1, 1);
    if size(raw_csv, 1)-2 ~= periods
        error(['perfect_foresight_with_expectation_errors_setup: the number of rows in ' options_.datafile ' does not match the periods setting'])
    end
    % Read first line (exogenous variable names)
    fid = fopen(options_.datafile);
    csv_first_line = fgetl(fid);
    fclose(fid);
    exo_header_names = strsplit(csv_first_line, ',');
    exo_header_names = exo_header_names(2:end); % Remove first column
    if numel(exo_header_names) ~= size(raw_csv, 2)
        error(['perfect_foresight_with_expectation_errors_setup: first line malformed in ' options_.datafile])
    end

    %% Create and fill structures containing information sets
    for i = 1:size(raw_csv, 2)
        exo_id = strmatch(exo_header_names{i}, M_.exo_names, 'exact');
        period_id = raw_csv(1, i);
        % Ignore irrelevant periods when copying shocks information
        oo_.pfwee.shocks_info(exo_id, period_id:end, period_id) = raw_csv(1+period_id:end-1, i);
        oo_.pfwee.terminal_info(exo_id, period_id) = raw_csv(end, i);
    end
else
    %% No datafile option given, use either the contents of shocks and endval blocks, or the contents of shock_paths block
    if isempty(M_.learnt_shocks) && isempty(M_.learnt_endval) ...
            && (isempty(M_.shock_paths) || all(cellfun(@(x) (isa(x, 'numeric') && x == 1), {M_.shock_paths.learnt_in}))) ...
            && (isempty(M_.perfect_foresight_controlled_paths) || all(cellfun(@(x) (isa(x, 'numeric') && x == 1), {M_.perfect_foresight_controlled_paths.learnt_in})))
        warning('perfect_foresight_with_expectation_errors_setup: there is no shocks(learnt_in=...), endval(learnt_in=...), shock_paths(learnt_in=...) or perfect_foresight_controlled_paths(learnt_in=...) block, and you did not pass the datafile option, so there is no point in using this command')
    end

    %% Check that dates can be processed, if any
    allperiods = {};
    if ~isempty(M_.det_shocks)
        allperiods = [allperiods, {M_.det_shocks.periods}];
    end
    if ~isempty(M_.learnt_shocks)
        allperiods = [allperiods, {M_.learnt_shocks.periods, M_.learnt_shocks.learnt_in }];
    end
    if ~isempty(M_.learnt_endval)
        allperiods = [allperiods, {M_.learnt_endval.learnt_in }];
    end
    if (any(cellfun(@(x) isa(x, 'dates'), allperiods)) ...
        || (~isempty(M_.shock_paths) && any([M_.shock_paths.contains_date]))) ...
        && isempty(first_simulation_period)
        error('perfect_foresight_with_expectations_error_setup: at least one periods statement, or learnt_in option, or learnt_in() namespace in shock_paths block is specified using a date but neither first_simulation_period nor last_simulation_period option was passed')
    end

    if isempty(M_.shock_paths)
        %% Initialize information set at period 1 using “bare” shocks and endval blocks (or initval if there is no endval)
        oo_.pfwee.terminal_info(:, 1) = oo_.exo_steady_state;
        oo_.pfwee.shocks_info(:, :, 1) = repmat(oo_.exo_steady_state, 1, periods);
        for i = 1:length(M_.det_shocks)
            if isa(M_.det_shocks(i).periods, 'numeric')
                prds = M_.det_shocks(i).periods;
            else % dates
                prds = M_.det_shocks(i).periods - first_simulation_period + 1;
            end
            exo_id = M_.det_shocks(i).exo_id;
            v = M_.det_shocks(i).value;
            if ~M_.det_shocks(i).exo_det
                switch M_.det_shocks(i).type
                  case 'level'
                    oo_.pfwee.shocks_info(exo_id, prds, 1) = v;
                  case 'multiply_steady_state'
                    oo_.pfwee.shocks_info(exo_id, prds, 1) = oo_.exo_steady_state(exo_id) * v;
                  case 'multiply_initial_steady_state'
                    if isempty(oo_.initial_exo_steady_state)
                        error('Option relative_to_initval of mshocks block cannot be used without an endval block')
                    end
                    oo_.pfwee.shocks_info(exo_id, prds, 1) = oo_.initial_exo_steady_state(exo_id) * v;
                end
            end
        end

        %% Construct information sets for subsequent informational periods using shocks(learnt_in=…) and endval(learnt_in=…) blocks
        % Since the learnt_in=… option with a dates object is never translated to a
        % “bare” shocks or endval block by the preprocessor (contrary to
        % learnt_in=1), the loop starts with p=1 to also handle dates objects
        % in learnt_in option corresponding to the first period.
        for p = 1:periods
            if p > 1
                oo_.pfwee.terminal_info(:, p) = oo_.pfwee.terminal_info(:, p-1);
                oo_.pfwee.shocks_info(:, :, p) = oo_.pfwee.shocks_info(:, :, p-1);
            end
            if ~isempty(M_.learnt_endval)
                idx = find(cellfun(@(x) (isa(x, 'numeric') && x == p) || (isa(x, 'dates') && x - first_simulation_period + 1 == p), {M_.learnt_endval.learnt_in}));
                for i = 1:length(idx)
                    j = idx(i);
                    exo_id = M_.learnt_endval(j).exo_id;
                    switch M_.learnt_endval(j).type
                      case 'level'
                        oo_.pfwee.terminal_info(exo_id, p) = M_.learnt_endval(j).value;
                      case 'add'
                        oo_.pfwee.terminal_info(exo_id, p) = oo_.pfwee.terminal_info(exo_id, p-1) + M_.learnt_endval(j).value;
                      case 'multiply'
                        oo_.pfwee.terminal_info(exo_id, p) = oo_.pfwee.terminal_info(exo_id, p-1) * M_.learnt_endval(j).value;
                      otherwise
                        error('Unknown type in M_.learnt_endval')
                    end
                    oo_.pfwee.shocks_info(exo_id, p:end, p) = oo_.pfwee.terminal_info(exo_id, p);
                end
            end
            if ~isempty(M_.learnt_shocks)
                idx = find(cellfun(@(x) (isa(x, 'numeric') && x == p) || (isa(x, 'dates') && x - first_simulation_period + 1 == p), {M_.learnt_shocks.learnt_in}));
                for i = 1:length(idx)
                    j = idx(i);
                    exo_id = M_.learnt_shocks(j).exo_id;
                    if isa(M_.learnt_shocks(j).periods, 'numeric')
                        prds = M_.learnt_shocks(j).periods;
                    else % dates
                        prds = M_.learnt_shocks(j).periods - first_simulation_period + 1;
                    end
                    switch M_.learnt_shocks(j).type
                      case 'level'
                        oo_.pfwee.shocks_info(exo_id, prds, p) = M_.learnt_shocks(j).value;
                      case 'add'
                        oo_.pfwee.shocks_info(exo_id, prds, p) = oo_.pfwee.shocks_info(exo_id, prds, p-1) + M_.learnt_shocks(j).value;
                      case 'multiply'
                        oo_.pfwee.shocks_info(exo_id, prds, p) = oo_.pfwee.shocks_info(exo_id, prds, p-1) .* M_.learnt_shocks(j).value;
                      case 'multiply_steady_state'
                        oo_.pfwee.shocks_info(exo_id, prds, p) = oo_.pfwee.terminal_info(exo_id, p) * M_.learnt_shocks(j).value;
                      otherwise
                        error('Unknown type in M_.learnt_shocks')
                    end
                end
            end
        end
    else
        %% Initialize information sets using the “shock_paths” blocks
        for i = 1:length(M_.database)
            if ~evalin('base', sprintf("exist('%s', 'var')", M_.database{i}))
                error('perfect_foresight_with_expectation_errors_setup: database %s does not exist in the base workspace', M_.database{i})
            end
        end

        shock_paths = NaN(M_.exo_nbr, periods+1, periods);
        for info_period = 1:periods
            if info_period == 1
                shock_paths(:,:,info_period) = repmat(oo_.exo_steady_state, 1, periods+1);
            else
                shock_paths(:,:,info_period) = shock_paths(:,:,info_period-1);
            end

            block_idx = find(cellfun(@(x) (isa(x, 'numeric') && x == info_period), {M_.shock_paths.learnt_in}));
            if ~isempty(first_simulation_period)
                block_idx = [block_idx; find(cellfun(@(x) (isa(x, 'dates') && x == first_simulation_period + info_period - 1), {M_.shock_paths.learnt_in}))];
            end
            for i = block_idx
                for p = info_period:(periods + M_.shock_paths(i).contains_endval)
                    shock_paths = feval(M_.shock_paths(i).evaluation_function, shock_paths, p, periods, first_simulation_period, M_, oo_);
                end
            end
        end
        oo_.pfwee.shocks_info = shock_paths(:,1:periods,:);
        oo_.pfwee.terminal_info = reshape(shock_paths(:,periods+1,:), [M_.exo_nbr, periods]);
    end
end

% Handle controlled paths
oo_.pfwee.controlled_paths_by_period = struct('exogenize_id', cell(periods, periods), 'endogenize_id', cell(periods, periods), 'values', cell(periods, periods), 'learnt_in', cell(periods, periods)); % 1st dimension of cells is real time, 2nd is informational time
for p = 1:periods
    oo_.pfwee.controlled_paths_by_period(:, p) = controlled_paths_by_period(M_, options_, p);
end

% Build initial paths for endos and exos
if isempty(M_.endo_histval)
    if isempty(oo_.initial_steady_state)
        oo_.endo_simul = repmat(oo_.steady_state, 1, M_.maximum_lag+periods+M_.maximum_lead);
    else
        oo_.endo_simul = [repmat(oo_.initial_steady_state, 1, M_.maximum_lag) repmat(oo_.steady_state, 1, periods+M_.maximum_lead)];
    end
else % histval or histval_file present
    if ~isempty(oo_.initial_steady_state)
        error('histval and endval cannot be used simultaneously')
    end
    oo_.endo_simul = [M_.endo_histval repmat(oo_.steady_state, 1, periods+M_.maximum_lead)];
end
if isempty(oo_.initial_exo_steady_state)
    oo_.exo_simul = repmat(oo_.exo_steady_state', M_.maximum_lag+periods+M_.maximum_lead, 1);
else
    oo_.exo_simul = [repmat(oo_.initial_exo_steady_state', M_.maximum_lag, 1); repmat(oo_.exo_steady_state', periods+M_.maximum_lead, 1)];
end
