function computebaseline(periods, deflateobsindex)

% INPUTS
% - periods            [integer]    scalar, number of periods for the long run simulation.
% - deflateobsindex    [integer]    scalar, index period for the observation used to normalize the simulated data.
%
% OUTPUTS
% none

global M_

if nargin<1 || isempty(periods)
    % Maximum number of periods for long run simulation.
    periods = 12000;
    if nargin==1
        % Index period for the observation used to normalize the simulated data.
        deflateobsindex = 10000;
    end
end

if nargin<2 || isempty(deflateobsindex)
    % Index period for the observation used to normalize the simulated data.
    deflateobsindex = 10000;
end

% Load database (generated by the ecb-mc package).
db = dseries('../database/data-for-ecb-base.mat');

% Write the backward version of the model
dynare('hybrid', '-DBACKWARD=true', '-DEXOGENIZE_FOREIGN=false', 'savemacro=backward.mod', 'onlymacro', 'notime');

% Preprocess backward model
dynare('backward', 'stochastic', 'fast', 'nopreprocessoroutput', 'notime');

% Set options
options.solve_algo = 14;
options.maxiter = 500;
options.tolx = 1e-8;
options.tolf = 1e-8;
options.simulations_along_bgp = 4;

% Cleanup database (remove unnecessary variables from database).
listofvariables = getlistofvariables();
db = db{listofvariables{:}};

% Prepare exogenous variables projection.
info = data.projectionsetup({'U2'}, db, sprintf('%s/backward.mod', pwd()));

% Compute residuals.
listofvariables = getlistofvariables(M_);

db.U2_STN_ZLB = db.U2_STN;
db.U2_TP_10YEXO = dseries(zeros(db.nobs,1), db.dates(1));
db.U2_TP_10YENDO = db.U2_TP_10Y;
db.U2_GO_COR_EXO = db.U2_GO_COR;
db.U2_A_COD = 100*((db.U2_HH_COD/db.U2_HH_COD(-1))^4-1);

db = solvemodelforresiduals('backward.mod', db{listofvariables{:}}, true);

% Compute baseline (we set the residuals to zero and extend the observed exogenous variables)
[baseline, info] = simulatelongrun('backward.mod', db, periods, info, false, true, options);

% Deflate baseline (otherwise we will not be able to use the baseline for perfect foresight simulations).
baseline = deflate(baseline, info, deflateobsindex);

baseline = baseline(baseline.dates(deflateobsindex-1000:deflateobsindex+505+M_.orig_maximum_endo_lag+M_.maximum_endo_lead));

baseline.U2_US_10Y_EXO = baseline.U2_US_10Y;
baseline.U2_CMEDEX_EXO = baseline.U2_CMEDEX;
baseline.U2_CXEDEX_EXO = baseline.U2_CXEDEX;
baseline.U2_POU_EXO = baseline.U2_POU;
baseline.U2_PCU_EXO = baseline.U2_PCU;
baseline.U2_WDREX_EXO = baseline.U2_WDREX;
baseline.U2_US_EHIC_EXO = baseline.U2_US_EHIC;

% Save baseline on disk.
baseline.save('../database/baseline', 'mat');