diff --git a/doc/manual/source/the-model-file.rst b/doc/manual/source/the-model-file.rst
index 4e7b8a6c9dc15ecd9ff79a9cc132658c616ac00f..2bf420d4becd26343e7b32fb4d0bbe7bfc2c4fa0 100644
--- a/doc/manual/source/the-model-file.rst
+++ b/doc/manual/source/the-model-file.rst
@@ -8840,11 +8840,11 @@ observed variables.
             Relative numerical efficiency (RNE) under the assumption
             of iid draws.
 
-        ``nse_x``
+        ``nse_taper_x``
 
             Numerical standard error (NSE) when using an x% taper.
 
-        ``rne_x``
+        ``rne_taper_x``
 
             Relative numerical efficiency (RNE) when using an x% taper.
 
@@ -8875,6 +8875,13 @@ observed variables.
             autocorrelation in draws. In this case, the estimates using a
             higher tapering are usually more reliable.
 
+    .. matvar:: oo_.convergence.raftery_lewis
+
+        Variable set by the convergence diagnostics of the ``estimation``
+        command when used with ``raftery_lewis_diagnostics`` option (see
+        :opt:`raftery_lewis_diagnostics`). Contains the results of the test in individual fields.
+
+
 .. command:: unit_root_vars VARIABLE_NAME...;
 
     |br| This command is deprecated. Use ``estimation`` option
diff --git a/doc/parallel/parallel.tex b/doc/parallel/parallel.tex
index dd3ea6864dea17840d47c69015cd01629a1e888c..7fdd48db3a56d418aeb67e10397c6d5da8495c1a 100644
--- a/doc/parallel/parallel.tex
+++ b/doc/parallel/parallel.tex
@@ -1,1249 +1,1250 @@
-% ----------------------------------------------------------------
-% AMS-LaTeX Paper ************************************************
-% **** -----------------------------------------------------------
-\documentclass[12pt,a4paper,pdftex]{article}
-\usepackage[margin=2.5cm]{geometry}
-\usepackage[utf8]{inputenc}
-\usepackage{amssymb,amsmath}
-\usepackage{graphicx}
-\usepackage{epstopdf}
-\usepackage{natbib}
-\usepackage{verbatim}
-\usepackage{xcolor}
-\usepackage{psfrag}
-\usepackage{setspace}
-\usepackage{rotating}
-\usepackage{epsf}
-\usepackage{epsfig}
-
-\newcounter{exmpl}
-\def\etal{{\em et al}.}
-\def\bfp{{\bf p}}
-\def\bfz{{\bf z}}
-\def\bfU{{\bf U}}
-\def\hbfx{{\hat{\bf x}}}
-\def\be{{\begin{equation}}}
-\def\ee{{\end{equation}}}
-\def\bfF{{\bf F}}
-\def\bfP{{\bf P}}
-\def\hbfP{{\hat{\bf P}}}
-\def\bfH{{\bf H}}
-\def\bfG{{\bf G}}
-\def\bfQ{{\bf Q}}
-\def\bfL{{\bf L}}
-\def\bfI{{\bf I}}
-\def\vare{\varepsilon}
-\def\mbfx{{\bf x}}
-\def\mbfH{{\bf H}}
-\def\mbfP{{\bf P}}
-\def\mbfchi{{\mbox{\boldmath$\chi$}}}
-\def\mbfzeta{{\mbox{\boldmath$\zeta$}}}
-\def\mbfeta{{\mbox{\boldmath$\eta$}}}
-\def\ni{{\noindent}}
-\def\mbfx{{\mbox{\boldmath$x$}}}
-
-
-%\bibpunct{(}{)}{;}{a}{,}{,}
-\bibpunct[, ]{(}{)}{;}{a}{,}{,}
-%\pagestyle{headings}
-
-\def \supp{{\rm supp}}
-\def \var{{\rm var}}
-
-\usepackage[pdfpagelabels]{hyperref}
-\hypersetup{
-pdfproducer = {LaTeX},
-colorlinks,
-linkcolor=blue,
-filecolor=yellow,
-urlcolor=green,
-citecolor=green}
-
-% ----------------------------------------------------------------
-\begin{document}
-
-% ----------------------------------------------------------------
-\title{Parallel DYNARE Toolbox\\FP7 Funded \\ Project MONFISPOL Grant no.: 225149}
-
-\author{Marco Ratto\\
-European Commission, Joint Research Centre, Ispra, ITALY
-}
-%%% To have the current date inserted, use \date{\today}:
-%%% To insert a footnote, add thanks in the date/title/author fields:
-\date{\today}
-%\date{\today \thanks{Authors gratefully acknowledge the
-%contribution by ... for ...}}
-\newpage
-\singlespacing
-{\footnotesize
-\maketitle \tableofcontents
-}
-\newpage
-\doublespacing
-%-----------------------------------------------------------------------
-\begin{abstract}
-In this document, we describe the basic ideas and the methodology identified to realize the parallel package within the DYNARE project (called the ``Parallel DYNARE'' hereafter) and its algorithmic performance.
-The parallel methodology has been developed taking into account two different perspectives: the ``User perspective'' and the ``Developers perspective''. The fundamental requirement of the ``User perspective'' is to allow DYNARE users to use the parallel routines easily, quickly and appropriately. Under the ``Developers perspective'', on the other hand, we need to build a core of parallelizing routines that are sufficiently abstract and modular to allow DYNARE software developers to use them easily as a sort of `parallel paradigm', for application to any DYNARE routine or portion of code containing computational intensive loops suitable for parallelization.
-We will finally show tests showing the effectiveness of the parallel implementation.
-\end{abstract}
-% ----------------------------------------------------------------
-\newpage
-\section{The ideas implemented in Parallel DYNARE}
-The basic idea behind ``Parallel Dynare'' is to build a framework to parallelize portions of code that require a minimal (i.e. start-end communication) or no communications between different processes, denoted in the literature as ``embarrassingly parallel'' \citep{GoffeCreel_Grid_2008,Barney_2009}.  In more complicated cases there are different and more sophisticated solutions to write (or re-write) parallel codes using, for example, OpenMP or MPI.
-Within DYNARE, we can find many portions of code with the above features: loops of computational sequences with no interdependency that are coded sequentially. Clearly, this does not make optimal use of computers having 2-4-8, or more cores or CPUs.
-The basic idea is to assign the different and independent computational sequences to different cores, CPU's or computers and coordinating this new distributed computational environment with the following criteria:
-
-\begin{itemize}
-\item provide the necessary input data to any sequence, possibly including results obtained from previous DYNARE sessions (e.g. a first batch of Metropolis iterations);
-\item distribute the workload, automatically balancing between the computational resources;
-\item collect the output data;
-\item ensure the coherence of the results with the original sequential execution.
-\end{itemize}
-
-Generally, during a program execution, the largest computational time is spent to execute nested cycles. For simplicity and without loss in generality we can consider here only \verb"for" cycles (it is possible to demonstrate that any \verb"while" cycle admits an equivalent \verb"for" cycle).
-Then, after identifying the most computationally expensive \verb"for" cycles, we can split their execution (i.e. the number or iterations) between different cores, CPUs, computers. For example, consider the following simple MATLAB piece of code:
-
-\singlespacing
-
-%\begin{table}[!ht]
-%{\small
-{\footnotesize
-\hspace{3cm}
-\begin{tabular}[b]{| p{6cm} |}
-  \hline
-  % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ...
-\begin{verbatim}
-...
-n=2;
-m=10^6;
-Matrix= zeros(n,m);
-for i=1:n,
-    Matrix(i,:)=rand(1,m);
-end,
-Mse= Matrix;
-...
-\end{verbatim}
-\\
-Example \refstepcounter{exmpl} \label{ex:serial} \theexmpl
-\\  \hline
-\end{tabular}
-%\vspace*{\baselineskip}
-}
-%\end{table}
-
-%\hspace{2cm}{\begin{minipage}[c]{5cm}
-%\begin{tabular}{| p{6cm} |}
-%  \hline
-%%\begin{quote}
-%\begin{verbatim}
-%...
-%n=2;
-%m=10^6;
-%Matrix= zeros(n,m);
-%for i=1:n,
-%    Matrix(i,:)=rand(1,m);
-%end,
-%Mse= Matrix;
-%...
-%\end{verbatim}
-%\\  \hline
-%\end{tabular}
-%%\end{quote}
-%\end{minipage}}
-\doublespacing
-
-With one CPU this cycle is executed in sequence: first for \verb"i=1", and then for \verb"i=2". Nevertheless, these 2 iterations are completely independent. Then, from a theoretical point of view, if we have two CPUs (cores) we can rewrite the above code as:
-
-\singlespacing
-{\footnotesize
-\hspace{1cm}\begin{tabular}[b]{| p{10cm} |}
-  \hline
-\begin{verbatim}
-            ...
-            n=2;
-            m=10^6;
-            <provide to CPU1 and CPU2 input data m>
-
-<Execute on CPU1>            <Execute on CPU2>
-Matrix1 = zeros(1,m);         Matrix2 = zeros(1,m);
-Matrix1(1,:)=rand(1,m);       Matrix2(1,:)=rand(1,m);
-save Matrix1                  save Matrix2
-
-            retrieve Matrix1 and Matrix2
-            Mpe(1,:) = Matrix1;
-            Mpe(2,:) = Matrix2;
-\end{verbatim}
-\\
-Example \refstepcounter{exmpl} \label{ex:parallel} \theexmpl\\
-\hline
-\end{tabular}
-}
-\doublespacing
-
-The \verb"for" cycle has disappeared and it has been split into two separated sequences that can be executed in parallel on two CPUs. We have the same result (\verb"Mpa=Mse") but the computational time can be reduced up to 50\%.
-
-\section{The DYNARE environment}
-We have considered the following DYNARE components suitable to be parallelized using the above strategy:
-
-\begin{enumerate}
-\item the Random Walk- (and the analogous Independent-)-Metropolis-Hastings algorithm with multiple chains: the different chains are completely independent and do not require any communication between them, so it can be executed on different cores/CPUs/Computer Network easily;
-\item a number of procedures performed after the completion of Metropolis, that use the posterior MC sample:
-\begin{enumerate}
-\item the diagnostic tests for the convergence of the Markov Chain \\(\texttt{mcmc\_diagnostics.m});
-\item the function that computes posterior IRF's (\texttt{posteriorIRF.m}).
-\item the function that computes posterior statistics for filtered and smoothed variables, forecasts, smoothed shocks, etc.. \\ (\verb"prior_posterior_statistics.m").
-\item the utility function that loads matrices of results and produces plots for posterior statistics (\texttt{pm3.m}).
-\end{enumerate}
-\end{enumerate}
-
-Unfortunately, MATLAB does not provide commands to simply write parallel code as in Example \ref{ex:parallel} (i.e.  the pseudo-commands : \texttt{<provide inputs>}, \texttt{<execute on CPU>} and \texttt{<retrieve>}). In other words, MATLAB does not allow concurrent programming: it does not support multi-threads, without the use (and purchase) of MATLAB Distributed Computing Toolbox. Then, to obtain the behavior described in Example \ref{ex:parallel}, we had to find an alternative solution.
-
-The solution that we have found can be synthesized as follows:
-
-\begin{quote}
-\emph{When the execution of the code should start in parallel (as in Example \ref{ex:parallel}), instead of running it inside the active MATLAB session, the following steps are performed:
-\begin{enumerate}
-\item the control of the execution is passed to the operating system (Windows/Linux) that allows for multi-threading;
-\item concurrent threads (i.e. MATLAB instances) are launched on different processors/cores/machines;
-\item when the parallel computations are concluded the control is given back to the original MATLAB session that collects the result from all parallel `agents' involved and coherently continue along the sequential computation.
-\end{enumerate}
-}\end{quote}
-
-Three core functions have been developed implementing this behavior, namely \verb"MasterParallel.m", \verb"slaveParallel.m" and \verb"fParallel.m". The first function (\verb"MasterParallel.m") operates at the level of the `master' (original) thread and acts as a wrapper of the portion of code to be distributed in parallel, distributes the tasks and collects the results from the parallel computation. The other functions (\verb"slaveParallel.m" and \verb"fParallel.m") operate at the level of each individual `slave' thread and collect the jobs distributed by the `master', execute them and make the final results available to the master.
-The two different implementations of slave operation comes from the fact that, in a single DYNARE session, there may be a number parallelized sessions that are launched by the master thread. Therefore, those two routines reflect two different versions of the parallel package:
-\begin{enumerate}
-\item the `slave' MATLAB sessions are closed after completion of each single job, and new instances are called for any subsequent parallelized task (\verb"fParallel.m");
-\item once opened, the `slave' MATLAB sessions are kept open during the DYNARE session, waiting for the jobs to be executed, and are only closed upon completion of the DYNARE session on the `master' (\verb"slaveParallel.m").
-\end{enumerate}
-
-We will see that none of the two options is superior to the other, depending on the model size.
-
-
-\section{Installation and utilization}
-Here we describe how to run parallel sessions in DYNARE and, for the developers community, how to apply the package to parallelize any suitable piece of code that may be deemed necessary.
-
-\subsection{Requirements}
-
-\subsubsection{For a Windows grid}
-\begin{enumerate}
-\item a standard Windows network (SMB) must be in place;
-\item PsTools \citep{PsTools} must be installed in the path of the master Windows machine;
-\item the Windows user on the master machine has to be user of any other slave machine in the cluster, and that user will be used for the remote computations.
-\end{enumerate}
-
-\subsubsection{For a UNIX grid}
-\begin{enumerate}
-\item SSH must be installed on the master and on the slave machines;
-\item the UNIX user on the master machine has to be user of any other slave machine in the cluster, and that user will be used for the remote computations;
-\item SSH keys must be installed so that the SSH connection from the master to the slaves can be done without passwords, or using an SSH agent.
-\end{enumerate}
-
-\subsection{The user perspective}
-We assume here that the reader has some familiarity with DYNARE and its use. For the DYNARE users, the parallel routines are fully integrated and hidden inside the DYNARE environment.
-
-\subsubsection{The interface}
-The general idea is to put all the configuration of the cluster in a config file different from the MOD file, and to trigger the parallel computation with option(s) on the \verb"dynare" command line.
-The configuration file is designed as follows:
-\begin{itemize}
-  \item be in a standard location
-   \begin{itemize}
-   \item {\footnotesize\verb"$HOME/.dynare"} under Unix;
-   \item {\footnotesize\verb"c:\Documents and Setting\<username>\Application Data\dynare.ini"} on Windows;
-   \end{itemize}
-  \item have provisions for other Dynare configuration parameters unrelated to parallel computation
-  \item allow to specify several clusters, each one associated with a nickname;
-  \item For each cluster, specify a list of slaves with a list of options for each slave [if not explicitly specified by the configuration file, the preprocessor sets the options to default];
-\end{itemize}
-
-The list of slave options includes:
-\begin{description}
-\item[Name]: name of the node;
-\item[CPUnbr]:  this is the number of CPU's to be used on that computer; if \verb"CPUnbr" is a vector of integers, the syntax is \verb"[s:d]", with \verb"d>=s" (\verb"d, s" are integer); the first core has number 1 so that, on a quad-core, use \verb"4" to use all cores, but use \verb"[3:4]" to specify just the last two cores (this is particularly relevant for Windows where it is possible to assign jobs to specific processors);
-\item[ComputerName]: Computer name on the network or IP address; use the NETBIOS name under Windows\footnote{In Windows XP it is possible find this name in 'My Computer' $->$ mouse right click $->$ 'Property' $->$ 'Computer Name'.}, or the DNS name under Unix.;
-\item[UserName]: required for remote login; in order to assure proper communications between the master and the slave threads, it must be the same user name actually logged on the `master' machine. On a Windows network, this is in the form \verb"DOMAIN\username", like \verb"DEPT\JohnSmith", i.e. user JohnSmith in windows group DEPT;
-\item[Password]: required for remote login (only under Windows): it is the user password on \verb"DOMAIN" and \verb"ComputerName";
-\item[RemoteDrive]: Drive to be used on remote computer (only for Windows, for example the drive \verb"C" or drive \verb"D");
-\item[RemoteDirectory]: Directory to be used on remote computer, the parallel toolbox will create a new empty temporary subfolder which will act as remote working directory;
-\item[DynarePath]: path to matlab directory within the Dynare installation directory;
-\item[MatlabOctavePath]: path to MATLAB or Octave executable;
-\item[SingleCompThread]: disable MATLAB's native multithreading;
-\end{description}
-
-Those options have the following specifications:
-
-\singlespacing  \noindent
-{\footnotesize
-      \begin{tabular}{|l|l|l|l|l|l|l|}
-        \hline
-        % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ...
- Node Options & type & default & \multicolumn{2}{c|}{Win} & \multicolumn{2}{c|}{Unix} \\
- & &  & Local & Remote & Local & Remote \\ \hline
- Name & string & (stop) & *&*&*&*\\
- CPUnbr & integer & (stop) &*&*&*&*\\
-  & or array & & & & & \\
- ComputerName & string & (stop) & &*& &*\\
- UserName & string & empty & &*& &*\\
- Password & string & empty & &*& & \\
- RemoteDrive & string & empty & &*& & \\
- RemoteDirectory & string & empty & &*& &*\\
- DynarePath & string & empty & & & & \\
- MatlabOctavePath & string & empty & & & & \\
- SingleCompThread & boolean & true & & & & \\
-        \hline
-      \end{tabular}
-}
-\doublespacing
-
-\vspace{1cm}
-The cluster options are as follows
-
-\singlespacing \noindent
-{\footnotesize
-      \begin{tabular}{|l|l|l|l|l|}
-        \hline
- Cluster Options & type & default & Meaning & Required \\ \hline
- Name & string & empty & name of the node &*\\
- Members & string & empty & list of members in this cluster &*\\
-        \hline
-      \end{tabular}
-}
-\doublespacing
-
-\vspace{1cm}
-The syntax of the configuration file will take the following form (the order in which the clusters and nodes are listed is not significant):
-
-\singlespacing
-{\footnotesize
-\hspace{2cm}\begin{tabular}[b]{| p{8cm} |}
-  \hline
-\begin{verbatim}
-[cluster]
-Name = c1
-Members = n1 n2 n3
-
-[cluster]
-Name = c2
-Members = n2 n3
-
-[node]
-Name = n1
-ComputerName = localhost
-CPUnbr = 1
-
-[node]
-Name = n2
-ComputerName = karaba.cepremap.org
-CPUnbr = 5
-UserName = houtanb
-RemoteDirectory = /home/houtanb/Remote
-DynarePath = /home/houtanb/dynare/matlab
-MatlabOctavePath = matlab
-
-[node]
-Name = n3
-ComputerName = hal.cepremap.ens.fr
-CPUnbr = 3
-UserName = houtanb
-RemoteDirectory = /home/houtanb/Remote
-DynarePath = /home/houtanb/dynare/matlab
-MatlabOctavePath = matlab
- \end{verbatim}
-\\ \hline
-\end{tabular}
-}
-\doublespacing
-
-Finally, the DYNARE command line options are:
- \begin{itemize}
-  \item \verb"conffile=<path>": specify the location of the configuration file if it is not standard
-  \item \verb"parallel": trigger the parallel computation using the first cluster specified in config file
-  \item \verb"parallel=<clustername>": trigger the parallel computation, using the given cluster
-  \item \verb"parallel_slave_open_mode": use the leaveSlaveOpen mode in the cluster
-  \item \verb"parallel_test": just test the cluster, don't actually run the MOD file
-
- \end{itemize}
-
-
-
-\subsubsection{Preprocessing cluster settings}
-The DYNARE pre-processor treats user-defined configurations by filling a new sub-structure in the \verb"options_" structure, named \verb"parallel", with the following fields:
-
-\singlespacing
-{\footnotesize
-\hspace{3cm}\begin{tabular}[b]{| p{7cm} |}
-  \hline
-\begin{verbatim}
-options_.parallel=
-    struct('Local', Value,
-    'ComputerName', Value,
-    'CPUnbr', Value,
-    'UserName', Value,
-    'Password', Value,
-    'RemoteDrive', Value,
-    'RemoteFolder', Value,
-    'MatlabOctavePath', Value,
-    'DynarePath', Value);
-\end{verbatim}
-\\ \hline
-\end{tabular}
-}
-\doublespacing
-
-All these fields correspond to the slave options except \verb"Local", which is set by the pre-processor according to the value of \verb"ComputerName":	
-\begin{description}
-\item[Local:] the variable \verb"Local" is binary, so it can have only two values 0 and 1. If \verb"ComputerName" is set to \verb"localhost", the preprocessor sets \verb"Local = 1" and the parallel computation is executed on the local machine, i.e. on the same computer (and working directory) where the DYNARE project is placed. For any other value for \verb"ComputerName", we will have \verb"Local = 0";
-\end{description}
-
-In addition to the \verb"parallel" structure, which can be in a vector form, to allow specific entries for each slave machine in the cluster, there is another \verb"options_" field, called \verb"parallel_info", which stores all options that are common to all cluster. Namely, according to the \verb"parallel_slave_open_mode" in the command line, the \verb"leaveSlaveOpen" field takes values:
-\begin{description}
-\item[\texttt{leaveSlaveOpen=1}]: with \verb"parallel_slave_open_mode", i.e. the slaves operate `Always-Open'.
-\item[\texttt{leaveSlaveOpen=0}]: without \verb"parallel_slave_open_mode", i.e. the slaves operate `Open-Close';
-\end{description}
-
-
-\subsubsection{Example syntax for Windows and Unix, for local parallel runs (assuming quad-core)}
-In this case, the only slave options are \verb"ComputerName" and \verb"CPUnbr".
-
-\singlespacing
-{\footnotesize
-\hspace{2cm}\begin{tabular}[b]{| p{8cm} |}
-  \hline
-\begin{verbatim}
-[cluster]
-Name = local
-Members = n1
-
-[node]
-Name = n1
-ComputerName = localhost
-CPUnbr = 4
-\end{verbatim}
-\\ \hline
-\end{tabular}
-}
-\doublespacing
-
-\subsubsection{Examples of Windows syntax for remote runs}
-\begin{itemize}
-\item the Windows \verb"Password" has to be typed explicitly;
-\item \verb"RemoteDrive" has to be typed explicitly;
-\item for \verb"UserName", ALSO the group has to be specified, like \verb"DEPT\JohnSmith", i.e. user \verb"JohnSmith" in windows group \verb"DEPT";
-\item \verb"ComputerName" is the name of the computer in the windows network, i.e. the output of hostname, or the full IP address.
-\end{itemize}
-
-\begin{description}
-\item[Example 1] Parallel codes that are run on a remote computer named \verb"vonNeumann" with eight cores, using only the cores 4,5,6, working on the drive 'C' and folder '\verb"dynare_calcs\Remote"'. The computer \verb"vonNeumann" is in a net domain of the CompuTown university, with user \verb"John" logged with the password \verb"*****":
-
-\singlespacing
-{\footnotesize
-\hspace{2cm}\begin{tabular}[b]{| p{8cm} |}
-  \hline
-\begin{verbatim}
-[cluster]
-Name = vonNeumann
-Members = n2
-
-[node]
-Name = n2
-ComputerName = vonNeumann
-CPUnbr = [4:6]
-UserName = COMPUTOWN\John
-Password = *****
-RemoteDrive = C
-RemoteDirectory = dynare_calcs\Remote
-DynarePath = c:\dynare\matlab
-MatlabOctavePath = matlab
-\end{verbatim}
-\\ \hline
-\end{tabular}
-}
-\doublespacing
-
-\item[Example 2] We can build a cluster, combining local and remote runs. For example the following configuration file includes the two previous configurations but also gives the possibility (with cluster name \verb"c2") to build a grid with a total number of 7 CPU's :
-
-\singlespacing
-{\footnotesize
-\hspace{2cm}\begin{tabular}[b]{| p{8cm} |}
-  \hline
-\begin{verbatim}
-[cluster]
-Name = local
-Members = n1
-
-[cluster]
-Name = vonNeumann
-Members = n2
-
-[cluster]
-Name = c2
-Members = n1 n2
-
-[node]
-Name = n1
-ComputerName = localhost
-CPUnbr = 4
-
-[node]
-Name = n2
-ComputerName = vonNeumann
-CPUnbr = [4:6]
-UserName = COMPUTOWN\John
-Password = *****
-RemoteDrive = C
-RemoteDirectory = dynare_calcs\Remote
-DynarePath = c:\dynare\matlab
-MatlabOctavePath = matlab
-\end{verbatim}
-\\ \hline
-\end{tabular}
-}
-\doublespacing
-\item[Example 3] We can build a cluster, combining many remote machines. For example the following commands build a grid of four machines with a total number of 14 CPU's:
-
-\singlespacing
-{\footnotesize
-\hspace{2cm}\begin{tabular}[b]{| p{8cm} |}
-  \hline
-\begin{verbatim}
-[cluster]
-Name = c4
-Members = n1 n2 n3 n4
-
-[node]
-Name = n1
-ComputerName = vonNeumann1
-CPUnbr = 4
-UserName = COMPUTOWN\John
-Password = *****
-RemoteDrive = C
-RemoteDirectory = dynare_calcs\Remote
-DynarePath = c:\dynare\matlab
-MatlabOctavePath = matlab
-
-[node]
-Name = n2
-ComputerName = vonNeumann2
-CPUnbr = 4
-UserName = COMPUTOWN\John
-Password = *****
-RemoteDrive = C
-RemoteDirectory = dynare_calcs\Remote
-DynarePath = c:\dynare\matlab
-MatlabOctavePath = matlab
-
-[node]
-Name = n3
-ComputerName = vonNeumann3
-CPUnbr = 2
-UserName = COMPUTOWN\John
-Password = *****
-RemoteDrive = D
-RemoteDirectory = dynare_calcs\Remote
-DynarePath = c:\dynare\matlab
-MatlabOctavePath = matlab
-
-[node]
-Name = n4
-ComputerName = vonNeumann4
-CPUnbr = 4
-UserName = COMPUTOWN\John
-Password = *****
-RemoteDrive = C
-RemoteDirectory = John\dynare_calcs\Remote
-DynarePath = c:\dynare\matlab
-MatlabOctavePath = matlab
-
-\end{verbatim}
-\\ \hline
-\end{tabular}
-}
-\doublespacing
-\end{description}
-
-
-
-\subsubsection{Example Unix syntax for remote runs}
-\begin{itemize}
-\item no \verb"Password" and \verb"RemoteDrive" fields are needed;
-\item \verb"ComputerName" is the full IP address or the DNS address.
-\end{itemize}
-
-\begin{description}
-\item[One remote slave:] the following command defines remote runs on the machine \verb"name.domain.org".\\
-\singlespacing
-{\footnotesize
-\hspace{2cm}\begin{tabular}[b]{| p{8cm} |}
-  \hline
-\begin{verbatim}
-[cluster]
-Name = unix1
-Members = n2
-
-[node]
-Name = n2
-ComputerName = name.domain.org
-CPUnbr = 4
-UserName = JohnSmith
-RemoteDirectory = /home/john/Remote
-DynarePath = /home/john/dynare/matlab
-MatlabOctavePath = matlab
-\end{verbatim}
-\\ \hline
-\end{tabular}
-}
-\doublespacing
-\item[Combining local and remote runs:] the following commands define a cluster of local an remote CPU's.
-\singlespacing
-{\footnotesize
-\hspace{2cm}\begin{tabular}[b]{| p{8cm} |}
-  \hline
-\begin{verbatim}
-[cluster]
-Name = unix2
-Members = n1 n2
-
-[node]
-Name = n1
-ComputerName = localhost
-CPUnbr = 4
-
-[node]
-Name = n2
-ComputerName = name.domain.org
-CPUnbr = 4
-UserName = JohnSmith
-RemoteDirectory = /home/john/Remote
-DynarePath = /home/john/dynare/matlab
-MatlabOctavePath = matlab
-\end{verbatim}
-\\ \hline
-\end{tabular}
-}
-\doublespacing
-\end{description}
-
-\subsubsection{Testing the cluster}
-
-In this section we describe what happens when the user omits a mandatory entry or provides bad values for them and how DYNARE reacts in these cases. In the parallel package there is a utility (\verb"AnalyseComputationalEnvironment.m") devoted to this task (this is triggered by the command line option \verb"parallel_test"). When necessary during the discussion, we use the \verb"parallel" entries used in the previous examples.
-
-%Le parti in rosa sono una possibile reazione ad un errore che pu� accadere � vanno concordate e quindi magari riviste.
-
-\begin{description}
-%\item[Local:] if no value is given for this variable the execution is stopped when DYNARE starts. More serious if we give a bad value (i.e. for example -1, 3), DYNARE will be stopped after some time with no error message! In these cases the Dynare �
-\item[ComputerName:] If \verb"Local=0", DYNARE checks if the computer \verb"vonNeumann" exists and if it is possible communicate with it. If this is not the case, an error message is generated and the computation is stopped.
-\item[CPUnbr:] a value for this variable must be in the form \verb"[s:d]" with \verb"d>=s". If the user types  values \verb"s>d", their order is flipped and a warning message is sent. When the user provides a correct value for this field, DYNARE checks if \verb"d" CPUs (or cores) are available on the computer. Suppose that this check returns an integer \verb"nC". We can have three possibilities:
-    \begin{enumerate}
-    \item \verb"nC= d;" all the CPU's available are used, no warning message are generated by DYNARE;
-    \item \verb"nC> d;" some CPU's will not be used;
-    \item \verb"nC< d;" DYNARE alerts the user that there are less CPU's than those declared. The parallel tasks would run in any case, but some CPU's will have multiple instances assigned, with no gain in computational time.
-    \end{enumerate}
-\item[UserName \& Password:] if \verb"Local = 1", no information about user name and password is necessary: ``I am working on this computer''. When remote computations on a Windows network are required, DYNARE checks if the user name and password are correct, otherwise execution is stopped with an error; for a Unix network, the user and the proper operation of SSH is checked;
-\item[RemoteDrive \& RemoteDirectory:] if \verb"Local = 1", these fields are not required since the working directory of the `slaves' will be the same of the `master'. If \verb"Local = 0", DYNARE tries to copy a file (\verb"Tracing.txt") in this remote location. If this operation fails, the DYNARE execution is stopped with an error;
-\item[MatlabOctavePath \& DynarePath:] MATLAB instances are tried on slaves and the DYNARE path is checked.
-\end{description}
-
-
-\subsection{The Developers perspective}
-%L'esposizione nel seguito (e anche in alcuni punti su) dipende molto da come il pacchetto parallelo viene rilasciato in Dynare, e quindi se PsTools viene installato durante l'installazione di Dynare oppure no, se le directory necessarie alla computazione vengono create durante l'installazione di Dynare oppure no. E cose cos� ...
-
-In this section we describe with some accuracy the DYNARE parallel routines.
-\begin{description}
-\item[Windows:]
-With Windows operating system, the parallel package requires the installation of a free software package called PsTools \citep{PsTools}. PsTools suite is a resource kit with a number of command line tools that mimics administrative features available under the Unix environment. PsTools can be downloaded from \cite{PsTools} and extracted in a Windows directory on your computer: to make PsTools working properly, it is mandatory to add this directory to the Windows path. After this step it is possible to invoke and use the PsTools commands from any location in the Windows file system. PsTools, MATLAB and DYNARE have to be installed and work properly on all the machines in the grid for parallel computation.
-\item[Unix:]
-With Unix operating system, SSH must be installed on the master and on the slave machines. Moreover, SSH keys must be installed so that the SSH connections from the master to the slaves can be done without passwords.
-\end{description}
-
-% NO DEFAULT REMOTE FOLDER !!!!!!
-%\item the creation of a directory devoted to the local/remote computation and data exchanges. %We usually create this directory on local drive 'C' within a directory '\verb"dynare_calcs"' and call it 'Remote', i.e. '\verb"C:\dynare_calcs\Remote"'. In this way the default value for RemoteDrive \& RemoteDirectory will be 'C' \& '\verb"C:\dynare_calcs\Remote"'.
-
-As soon as the computational environment is set-up for working on a grid of CPU's, the parallel package allows to parallelize any loop that is computationally expensive, following the step by step procedure showed in Table \ref{tab:devpar}. This is done using five basic functions: \verb"masterParallel.m", \verb"fParallel.m" or \verb"slaveParallel.m", \verb"fMessageStatus.m", \verb"closeSlave.m".
-
-\begin{description}
- \item[\texttt{masterParallel}] is the entry point to the parallelization system:
- \begin{itemize}
-  \item It is called from the master computer, at the point where the parallelization system should be activated. Its main arguments are the name of the function containing the task to be run on every slave computer, inputs to that function stored in two structures (one for local and the other for global variables), and the configuration of the cluster; this function exits when the task has finished on all computers of the cluster, and returns the output in a structure vector (one entry per slave);
-  \item all file exchange through the filesystem is concentrated in this \verb"masterParallel" routine: so it prepares and send the input information for slaves, it retrieves from slaves the info about the status of remote computations stored on remote slaves by the remote processes; finally it retrieves outputs stored on remote machines by slave processes;
-  \item there are two modes of parallel execution, triggered by option \verb"parallel_slave_open_mode":
-   \begin{itemize}
-   \item when \verb"parallel_slave_open_mode=0", the slave processes are closed after the completion of each task, and new instances are initiated when a new job is required; this mode is managed by \verb"fParallel.m" [`Open-Close'];
-   \item when \verb"parallel_slave_open_mode=1", the slave processes are kept running after the completion of each task, and wait for new jobs to be performed; this mode is managed by \texttt{slaveParallel.m} [`Always-Open'];
-   \end{itemize}
-  \end{itemize}
- \item[\texttt{slaveParallel.m/fParallel.m}:] are the top-level functions to be run on every slave; their main arguments are the name of the function to be run (containing the computing task), and some information identifying the slave; the functions use the input information that has been previously prepared and sent by \verb"masterParallel" through the filesystem, call the computing task, finally the routines store locally on remote machines the  outputs such that \verb"masterParallel" retrieves back the outputs to the master computer;
- \item[\texttt{fMessageStatus.m}:] provides the core for simple message passing during slave execution: using this routine, slave processes can store locally on remote machine basic info on the progress of computations; such information is retrieved by the master process (i.e. \verb"masterParallel.m") allowing to echo progress of remote computations on the master; the routine \verb"fMessageStatus.m" is also the entry-point where a signal of interruption sent by the master can be checked and executed; this routine typically replaces calls to \verb"waitbar.m";
- \item[\texttt{closeSlave.m}] is the utility that sends a signal to remote slaves to close themselves. In the standard operation, this is only needed with the `Always-Open' mode and it is called when DYNARE computations are completed. At that point, \texttt{slaveParallel.m} will get a signal to terminate and no longer wait for new jobs. However, this utility is also useful in any parallel mode if, for any reason, the master needs to interrupt the remote computations which are running;
- \end{description}
-
-The parallel toolbox also includes a number of utilities:
-\begin{itemize}
- \item \verb"AnalyseComputationalEnviroment.m": this a testing utility that checks that the cluster works properly and echoes error messages when problems are detected;
- \item \verb"InitializeComputationalEnviroment.m" : initializes some internal variables and remote directories;
- \item \verb"distributeJobs.m": uses a simple algorithm to distribute evenly jobs across the available CPU's;
- \item a number of generalized routines that properly perform \verb"delete", \verb"copy", \verb"mkdir", \verb"rmdir" commands through the network file-system (i.e. used from the master to operate on slave machines); the routines are adaptive to the actual environment (Windows or Unix);
- \begin{description}
-  \item[\texttt{dynareParallelDelete.m}]: generalized \verb"delete";
-  \item[\texttt{dynareParallelDir.m}]: generalized \verb"dir";
-  \item[\texttt{dynareParallelGetFiles.m}]: generalized \verb"copy" FROM slaves TO master machine;
-  \item[\texttt{dynareParallelMkDir.m}]: generalized \verb"mkdir" on remote machines;
-  \item[\texttt{dynareParallelRmDir.m}]: generalized \verb"rmdir" on remote machined;
-  \item[\texttt{dynareParallelSendFiles.m}]: generalized \verb"copy" TO slaves FROM master machine;
- \end{description}
-\end{itemize}
-
-In Table \ref{tab:devpar} we have synthesized the main steps for parallelizing MATLAB codes.
-
-{\small
-\begin{table}
-\begin{tabular}{|p{\linewidth}|}
-\hline
-\begin{enumerate}
-\item locate within DYNARE the portion of code suitable to be parallelized, i.e. an expensive cycle \verb"for";
-\item suppose that the function \verb"tuna.m" contains a cycle \verb"for" that is suitable for parallelization: this cycle has to be extracted from \verb"tuna.m" and put it in a new MATLAB function named \verb"tuna_core.m";
-\item at the point where the expensive cycle should start, the function \verb"tuna.m" invokes the utility \verb"masterParallel.m", passing to it the \verb"options_.parallel" structure, the name of the of the function to be run in parallel (\verb"tuna_core.m"), the local and global variables needed and all the information about the files (MATLAB functions \verb"*.m"; data files \verb"*.mat") that will be handled by \verb"tuna_core.m";
-\item the function \verb"masterParallel.m" reads the input arguments provided by \verb"tuna.m" and:
-\begin{itemize}
-\item decides how to distribute the task evenly across the available CPU's (using the utility routine \verb"distributeJobs.m"); prepares and initializes the computational environment (i.e. copy files/data) for each slave machine;
-\item uses the PsTools and the Operating System commands to launch new MATLAB instances, synchronize the computations, monitor the progress of slave tasks through a simple message passing system (see later) and collect results upon completion of the slave threads;
-\end{itemize}
-\item the slave threads are executed using the MATLAB functions \verb"fParallel.m"/\verb"slaveParallel.m" as wrappers for implementing the tasks sent by the master (i.e. to run the \verb"tuna_core.m" routine);
-\item the utility \verb"fMessageStatus.m" can be used within the core routine \verb"tuna_core.m" to send information to the master regarding the progress of the slave thread;
-\item when all DYNARE computations are completed, \verb"closeSlave.m" closes all open remote MATLAB/OCTAVE instances waiting for new jobs to be run.
-\end{enumerate}
-\\ \hline
-\end{tabular}
-\caption{Procedure for parallelizing portions of codes.}\label{tab:devpar}
-\end{table}
-}
-
-So far, we have parallelized the following functions, by selecting the most computationally intensive loops:
-\begin{enumerate}
-\item the cycle looping for multiple chain random walk Metropolis:\\
-\verb"random_walk_metropolis_hastings", \\
-\verb"random_walk_metropolis_hastings_core";
-\item the cycle looping for multiple chain independent Metropolis:\\
-\verb"independent_metropolis_hastings.m", \\
-\verb"independent_metropolis_hastings_core.m";
-\item the cycle looping over estimated parameters computing univariate diagnostics:\\
-\verb"mcmc_diagnostics.m", \\
-\verb"mcmc_diagnostics_core.m";
-\item the Monte Carlo cycle looping over posterior parameter subdraws performing the IRF simulations (\verb"<*>_core1") and the cycle looping over exogenous shocks plotting IRF's charts (\verb"<*>_core2"):\\
-\verb"posteriorIRF.m", \\\verb"posteriorIRF_core1.m", \verb"posteriorIRF_core2.m";
-\item the Monte Carlo cycle looping over posterior parameter subdraws, that computes filtered, smoothed, forecasted variables and shocks:\\
-\verb"prior_posterior_statistics.m", \\
-\verb"prior_posterior_statistics_core.m";
-\item the cycle looping over endogenous variables making posterior plots of filter, smoother, forecasts:
-\verb"pm3.m", \verb"pm3_core.m".
-\end{enumerate}
-%A developer can use the existent functions \verb"masterParalle.m" and \verb"fParalell.m"  a couple of functions already parallelized as example and then to add new parallel routine in Dynare.
-%Remember that, from the user side to use the parallel routines it is only required to insert in the .mod file the commands the \verb"options_.parallel" structure as described above (see also [2, 5]). If the file \verb".mod" do not contain this structure (or it is commented) Dynare is executed in a traditional way.
-
-\subsubsection{Write a parallel code: an example}
-%Per questo paragrafo ci sono secondo me due soluzioni possibili:
-%
-%1.
-%
-Using a MATLAB pseudo (but very realistic) code, we now describe in detail how to use the above step by step procedure to parallelize the random walk Metropolis Hastings algorithm. Any other function can be parallelized in the same way.
-
-It is obvious that most of the computational time spent by the \\ \verb"random_walk_metropolis_hastings.m" function is given by the cycle looping over the parallel chains performing the Metropolis:
-
-\singlespacing
-{\footnotesize
-\hspace{2cm}\begin{tabular}[b]{| p{9cm} |}
-  \hline
-\begin{verbatim}
-function random_walk_metropolis_hastings
-       (TargetFun, ProposalFun, ..., varargin)
-[...]
-for b = fblck:nblck,
-...
-end
-[...]
-\end{verbatim}
-\\ \hline
-\end{tabular}
-}
-\doublespacing
-
-Since those chains are totally independent, the obvious way to reduce the computational time is to parallelize this loop, executing the \verb"(nblck-fblck)" chains on different computers/CPUs/cores.
-
-%\singlespacing
-%{\footnotesize
-%\hspace{2cm}\begin{tabular}[b]{| p{9cm} |}
-%  \hline
-%\begin{verbatim}
-%...
-%if (nblck>fblck) & (number of available CPUs >1)
-%execute
-%the	nblck - nblck branch on CPU 1
-%	    	(nblck+1) - (nblck+1) on CPU 2
-%		[...]
-%		Fblck - fblck on CPU F
-%else
-%	for b = fblck:nblck,
-%...
-%end
-%end
-%...
-%\end{verbatim}
-%\\ \hline
-%\end{tabular}
-%}
-%\doublespacing
-
-To do so, we remove the \verb"for" cycle and put it in a new function named \verb"<*>_core.m":
-
-\singlespacing
-{\footnotesize
-\noindent\begin{tabular}[b]{| p{\linewidth} |}
-\hline
-\begin{verbatim}
-function myoutput =
-    random_walk_metropolis_hastings_core(myinputs,fblck,nblck, ...)
-[...]
-\end{verbatim}
-just list global variables needed (they are set-up properly by \verb"fParallel" or \verb"slaveParallel")
-\begin{verbatim}
-global bayestopt_ estim_params_ options_  M_ oo_
-\end{verbatim}
-here we collect all local variables stored in \verb"myinputs"
-\begin{verbatim}
-TargetFun=myinputs.TargetFun;
-ProposalFun=myinputs.ProposalFun;
-xparam1=myinputs.xparam1;
-[...]
-\end{verbatim}
-here we run the loop
-\begin{verbatim}
-for b = fblck:nblck,
-...
-end
-[...]
-\end{verbatim}
-here we wrap all output arguments needed by the `master' routine
-\begin{verbatim}
-myoutput.record = record;
-[...]
-\end{verbatim}
-\\ \hline
-\end{tabular}
-}
-\doublespacing
-The split of the \verb"for" cycle has to be performed in such a way that the new \verb"<*>_core" function can work in both serial and parallel mode. In the latter case, such a function will be invoked by the slave threads and executed for the number of iterations assigned by \verb"masterParallel.m".
-
-The modified \verb"random_walk_metropolis_hastings.m" is therefore:
-
-\singlespacing
-{\footnotesize
-\noindent\begin{tabular}[b]{| p{\linewidth} |}
-\hline
-\begin{verbatim}
-function random_walk_metropolis_hastings(TargetFun,ProposalFun,\ldots,varargin)
-[...]
-% here we wrap all local variables needed by the <*>_core function
-localVars = struct('TargetFun', TargetFun, ...
-[...]
-    'd', d);
-[...]
-% here we put the switch between serial and parallel computation:
-if isnumeric(options_.parallel) || (nblck-fblck)==0,
-% serial computation
-    fout = random_walk_metropolis_hastings_core(localVars, fblck,nblck, 0);
-    record = fout.record;
-
-else
-% parallel computation
-
-    % global variables for parallel routines
-    globalVars = struct('M_',M_, ...
-                       [...]
-                       'oo_', oo_);
-
-    % which files have to be copied to run remotely
-    NamFileInput(1,:) = {'',[ModelName '_static.m']};
-    NamFileInput(2,:) = {'',[ModelName '_dynamic.m']};
-    [ ...]
-
-    % call the master parallelizing utility
-    [fout, nBlockPerCPU, totCPU] = masterParallel(options_.parallel, ...
-    fblck, nblck, NamFileInput, 'random_walk_metropolis_hastings_core',
-    localVars, globalVars, options_.parallel_info);
-
-    % collect output info from parallel tasks provided in fout
-    [ ...]
-end
-
-% collect output info from either serial or parallel tasks
-irun = fout(1).irun;
-NewFile = fout(1).NewFile;
-[...]
-\end{verbatim}
-\\ \hline
-\end{tabular}
-}
-\doublespacing
-
-Finally, in order to allow the master thread to monitor the progress of the slave threads, some message passing elements have to be introduced in the \verb"<*>_core.m" file. The utility function \verb"fMessageStatus.m" has been  designed as an interface for this task, and can be seen as a generalized form of the MATLAB utility \verb"waitbar.m".
-
-In the following example, we show a typical use of this utility, again from the random walk Metropolis routine:
-\singlespacing
-{\footnotesize
-\noindent\begin{tabular}[b]{| p{\linewidth} |}
-\hline
-\begin{verbatim}
-for  j = 1:nruns
-[...]
-% define the progress of the loop:
-prtfrc = j/nruns;
-
-% define a running message:
-% first indicate which chain is running on the current CPU [b]
-% out of the chains [mh_nblock] requested by the DYNARE user
-waitbarString = [ '(' int2str(b) '/' int2str(mh_nblck) ') ...
-
-% then add possible further information, like the acceptation rate
-    ' sprintf('%f done, acceptation rate %f',prtfrc,isux/j)]
-
-    if mod(j, 3)==0 & ~whoiam
-        % serial computation
-        waitbar(prtfrc,hh,waitbarString);
-
-    elseif mod(j,50)==0 & whoiam,
-        % parallel computation
-        fMessageStatus(prtfrc, ...
-            whoiam, ...
-            waitbarString, ...
-            waitbarTitle, ...
-            options_.parallel(ThisMatlab))
-
-    end
-    [...]
-end
-\end{verbatim}
-\\ \hline
-\end{tabular}
-}
-\doublespacing
-In the previous example, a number of arguments are used to identify which CPU and which computer in the claster is sending the message, namely:
-\singlespacing
-{\footnotesize
-\noindent\begin{tabular}[b]{| p{\linewidth} |}
-\hline
-\begin{verbatim}
-%  whoiam [int]         index number of this CPU among all CPUs in the
-%                       cluster
-%  ThisMatlab [int]     index number of this slave machine in the cluster
-%                       (entry in options_.parallel)
-\end{verbatim}
-\\ \hline
-\end{tabular}
-}
-\doublespacing
-The message is stored as a MATLAB data file \verb"*.mat" saved on the working directory of remote slave computer. The master will will check periodically for those messages and retrieve the files from remote computers and produce an advanced monitoring plot.
-
-So, assuming to run two Metropolis chains, under the standard serial implementation there will be a first \verb"waitbar" popping up on matlab, corresponding to the first chain:
-
-\hspace{2cm}\epsfxsize=200pt \epsfbox{waitbars1.pdf}
-
-\ni followed by a second \texttt{waitbar}, when the first chain is completed.
-
-\hspace{2cm}\epsfxsize=200pt \epsfbox{waitbars2.pdf}
-
-On the other hand, under the parallel implementation, a parallel monitoring plot will be produced by \texttt{masterParallel.m}:
-
-\hspace{2cm}\epsfxsize=200pt \epsfbox{waitbarsP.pdf}
-
-
-
-%Finally we describe the masterParallel.m and fParallel.m functions:
-%
-%\begin{verbatim}
-%function Results= masterParallel (DATA, functionName)
-%
-%[...]
-%
-%read  options_.parallel;
-%call the function rACE=AnalyseComputationalEnviroment (options_.parallel);
-%
-%switch rACE
-%	[...]
-%end
-%[...]
-%\end{verbatim}
-
-%Non so se pu� andare bene impostata in questo modo � se va bene la concludo.
-%
-%2.
-%Prendiamo il tutto il lavoro fatto per arrivare a parallellizzare la PosteriorIRF,
-%Traacianti, anlisi computazionale � commentiamo bene tutte le funzioni coinvolte e le usiamo qui �
-	
-
-\section{Parallel DYNARE: testing}
-We checked the new parallel platform for DYNARE performing a number of tests, using different models and computer architectures. We present here all tests performed with Windows XP/MATLAB. However, similar tests were performed successfully under Linux/Ubuntu environment.
-In the Bayesian estimation of DSGE models with DYNARE, most of the computing time is devoted to the posterior parameter estimation with the Metropolis algorithm. The first and second tests are therefore focused on the parallelization of the Random Walking Metropolis Hastings algorithm (Sections \ref{s:test1}-\ref{s:test2}). In addition, further tests (Sections \ref{s:test3}-\ref{s:test4}) are devoted to test all the parallelized functions in DYNARE. %Finally, we compare the two parallel implementations of the Metropolis Hastings algorithms, available in DYNARE: the Independent and the Random Walk (Section \ref{s:test5}).
-
-\subsection{Test 1.}\label{s:test1}
-The main goal here was to evaluate the parallel package on a \emph{fixed hardware platform} and using chains of \emph{variable length}. The model used for testing is a modification of \cite{Hradisky_etal_2006}. This is a small scale open economy DSGE model with 6 observed variables, 6 endogenous variables and 19 parameters to be estimated.
-We estimated the model on a bi-processor machine (Fujitsu Siemens, Celsius R630) powered with an Intel\textsuperscript{\textregistered} Xeon\texttrademark CPU 2.80GHz Hyper Treading Technology; first with the original serial Metropolis and subsequently using the parallel solution, to take advantage of the two processors technology. We ran chains of increasing length: 2500, 5000, 10,000, 50,000, 100,000, 250,000, 1,000,000.
-
-\begin{figure}[!ht]
-\begin{centering}
-  % Requires \usepackage{graphicx}
-  \epsfxsize=300pt \epsfbox{iVaNo_time_comp.pdf}
-  \caption{Computational time (in minutes) versus chain length for the serial and parallel implementation (Metropolis with two chains).}\label{fig:test_time_comp}
-\end{centering}
-\end{figure}
-\begin{figure}[!ht]
-\begin{centering}
-  % Requires \usepackage{graphicx}
-  \epsfxsize=300pt \epsfbox{iVaNo_gain.pdf}
-  \caption{Reduction of computational time (i.e. the `time gain') using the parallel coding versus chain length. The time gain is computed as $(T_s-T_p)/T_p$, where $T_s$ and $T_p$ denote the computing time of the serial and parallel implementations respectively.}\label{fig:test_gain}
-\end{centering}
-\end{figure}
-
-Overall results are given in Figure \ref{fig:test_time_comp}, showing the computational time versus chain length, and Figure \ref{fig:test_gain}, showing the reduction of computational time (or the time gain) with respect to the serial implementation provided by the parallel coding. The gain in computing time of the exercise is of about 45\% on this test case, so reducing from 11.40 hours to about 6 hours the cost of running 1,000,000 Metropolis iterations (the ideal gain would be of 50\% in this case).
-
-\subsection{Test 2.}\label{s:test2}	
-The scope of the second test was to verify if results were robust over different hardware platforms.
-We estimated the model with chain lengths of 1,000,000 runs on the following hardware platforms:
-\begin{itemize}
-\item Single processor machine: Intel\textsuperscript{\textregistered} Pentium4\textsuperscript{\textregistered} CPU 3.40GHz with Hyper Treading Technology (Fujitsu-Siemens Scenic Esprimo);
-\item Bi-processor machine: two CPU's Intel\textsuperscript{\textregistered} Xeon\texttrademark 2.80GHz Hyper Treading Technology (Fujitsu-Siemens, Celsius R630);
-\item Dual core machine: Intel Centrino T2500 2.00GHz Dual Core  (Fujitsu-Siemens, LifeBook S Series).
-\end{itemize}
-
-We first run the tests with normal configuration. However, since (i) dissimilar software environment on the machine can influence the computation; (ii) Windows service (Network, Hard Disk writing, Demon, Software Updating, Antivirus, etc.) can start during the simulation; we also run the tests not allowing for any other process to start during the estimation. Table \ref{tab:trail} gives results for the ordinary software environment and process priority is set as low/normal.
-
-\begin{table}
-\begin{centering}
-\begin{tabular}{l|l|l|l}
-  % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ...
-Machine	& Single-processor	& Bi-processor	& Dual core \\ \hline
-Parallel & 8:01:21 & 7:02:19 & 5:39:38 \\
-Serial & 10:12:22 & 13:38:30 & 11:02:14 \\
-Speed-Up rate & 1.2722 & 1.9381 & 1.9498\\
-Ideal Speed-UP rate &  $\sim$1.5 & 2 & 2 \\
-  \hline
-\end{tabular}
-\caption{Trail results with normal PC operation. Computing time expressed in h:m:s. Speed-up rate is computed as $T_s/T_p$, where $T_s$ and $T_p$ are the computing times for the serial and parallel implementations.}\label{tab:trail}
-\end{centering}
-\end{table}
-
-Results showed that Dual-core technology provides a similar gain if compared with bi-processor results, again about 45\%. The striking results was that the Dual-core processor clocked at 2.0GHz was about 30\% faster than the Bi-processor clocked at 2.8GHz. Interesting gains were also obtained via multi-threading on the Single-processor machine, with speed-up being about 1.27 (i.e. time gain of about 21\%). However, beware that we burned a number of processors performing tests on single processors with hyper-threading and using very long chains (1,000,000 runs)!
-We re-run the tests on the Dual-core machine, by cleaning the PC operation from any interference by other programs and show results in Table \ref{tab:trail2}.
-A speed-up rate of 1.06 (i.e. 5.6\% time gain) can be obtained simply hiding the MATLAB waitbar. The speed-up rate can be pushed to 1.22 (i.e. 18\% time gain) by disconnecting the network and setting the priority of the process to real time. It can be noted that from the original configuration, taking 11:02 hours to run the two parallel chains, the computational time can be reduced to 4:40 hours (i.e. for a total time gain of over 60\% with respect to the serial computation) by parallelizing and optimally configuring the operating environment.
-These results are somehow surprising and show how it is possible to reduce dramatically the computational time with slight modification in the software configuration.
-\begin{table}[t]
-\begin{centering}
-\begin{tabular}{p{5cm}|l|l}
-  % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ...
-Environment	& Computing time & Speed-up rate \\
-& & w.r.t. Table \ref{tab:trail}\\ \hline
-Parallel Waitbar Not Visible & 5:06:00 & 1.06 \\ \hline
-Parallel waitbar Not Visible, Real-time Process priority,
-Unplugged network cable. &
-	4:40:49 & 1.22\\
-  \hline
-\end{tabular}
-\caption{Trail results with different software configurations (optimized operating environment for computational requirements).}\label{tab:trail2}
-\end{centering}
-\end{table}
-
-Given the excellent results reported above, we have parallelized many other DYNARE functions. This implies that parallel instances can be invoked many times during a single DYNARE session. Under the basic parallel toolbox implementation, that we call the `Open/Close' strategy, this implies that MATLAB instances are opened and closed many times by system calls, possibly slowing down the computation, specially for `entry-level' computer resources. As mentioned before, this suggested to implement an alternative strategy for the parallel toolbox, that we call the `Always-Open' strategy, where the slave MATLAB threads, once opened, stay alive and wait for new tasks assigned by the master until the full DYNARE procedure is completed. We show next the tests of these latest implementations.
-
-\subsection{Test 3}\label{s:test3}
-In this Section we use the \cite{Lubik2003} model as test function\footnote{The \cite{Lubik2003} model is also selected as the `official' test model for the parallel toolbox in DYNARE.} and a very simple computer class, quite diffuse nowadays: Netbook personal Computer. In particular we used the Dell Mini 10 with Processor Intel\textsuperscript{\textregistered} Atom\texttrademark Z520 (1,33 GHz, 533 MHz), 1 GB di RAM (with Hyper-trading). First, we tested the computational gain of running a full Bayesian estimation: Metropolis (two parallel chains), MCMC diagnostics, posterior IRF's and filtered, smoothed, forecasts, etc. In other words, we designed DYNARE sessions that invoke all parallelized functions. Results are shown in Figures \ref{fig:netbook_complete_openclose}-\ref{fig:netbook_partial_openclose}.
-\begin{figure}[p]
-\begin{centering}
-  % Requires \usepackage{graphicx}
-  \epsfxsize=300pt \epsfbox{netbook_complete_openclose.pdf}
-  \caption{Computational Time (s) versus Metropolis length, running all the parallelized functions in DYNARE and the basic parallel implementation (the `Open/Close' strategy). \citep{Lubik2003}.}\label{fig:netbook_complete_openclose}
-\end{centering}
-\end{figure}
-\begin{figure}[p]
-\begin{centering}
-  % Requires \usepackage{graphicx}
-  \epsfxsize=300pt \epsfbox{netbook_partial_openclose.pdf}
-  \caption{Computational Time (s) versus Metropolis length, loading previously performed MH runs and running \emph{only} the parallelized functions after Metropolis \citep{Lubik2003}. Basic parallel implementation (the `Open/Close' strategy).}\label{fig:netbook_partial_openclose}
-\end{centering}
-\end{figure}
-In Figure \ref{fig:netbook_complete_openclose} we show the computational time versus the length of the Metropolis chains in the serial and parallel setting (`Open/Close' strategy). With very short chain length, parallel setting obviously slows down performances of the computations (due to delays in open/close MATLAB sessions and in synchronization), while increasing the chain length, we can get speed-up rates up to 1.41 on this `entry-level' portable computer (single processor and Hyper-threading).
-In order to appreciate the gain of parallelizing all functions invoked after Metropolis, in Figure \ref{fig:netbook_partial_openclose} we show the results of the experiment, but without running Metropolis, i.e. we use the options \verb"load_mh_files = 1" and \verb"mh_replic = 0" DYNARE options (i.e. Metropolis and MCMC diagnostics are not invoked). The parallelization of the functions invoked after Metropolis allows to attain speed-up rates of 1.14 (i.e. time gain of about 12\%). Note that the computational cost of these functions is proportional to the chain length only when the latter is relatively small. In fact, the number of sub-draws taken by \verb"posteriorIRF.m" or \verb"prior_posterior_statistics.m" is proportional to the total number of MH draws up to a maximum threshold of 500 sub-draws (for IRF's) and 1,200 sub-draws (for smoother). This is reflected in the shape of the plots, which attain a plateau when these thresholds are reached.
-%\begin{table}
-%\begin{centering}
-%\begin{tabular}{l|l|l}
-%  % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ...
-%Chain Length & Time Serial (s) & Time Parallel (s) \\ \hline					
-%105 & 85 & 151 \\
-%1005 & 246 & 287 \\
-%5005 & 755 & 599 \\
-%10005 & 1246 & 948 \\
-%15005 & 1647 & 1250 \\
-%20005 & 2068 & 1502 \\
-%25005 & 2366 & 1675 \\
-% \hline
-%\end{tabular}
-%\caption{Trail results for the \cite{Lubik2003} model. Computational Time running all the parallelized functions in DYNARE and the basic parallel implementation (the `Open/Close' strategy).}\label{tab:trail_ls2003}
-%\end{centering}
-%\end{table}
-\begin{figure}
-\begin{centering}
-  % Requires \usepackage{graphicx}
-  \epsfxsize=300pt \epsfbox{netbook_complete_comp.pdf}
-  \caption{Comparison of the `Open/Close' strategy and the `Always-open' strategy. Computational Time (s) versus Metropolis length, running all the parallelized functions in DYNARE \citep{Lubik2003}.}\label{fig:netbook_complete_comp}
-\end{centering}
-\end{figure}
-\begin{figure}
-\begin{centering}
-  % Requires \usepackage{graphicx}
-  \epsfxsize=300pt \epsfbox{netbook_partial_comp.pdf}
-  \caption{Comparison of the `Open/Close' strategy and the `Always-open' strategy. Computational Time (s) versus Metropolis length, running only the parallelized functions after Metropolis \citep{Lubik2003}.}\label{fig:netbook_partial_comp}
-\end{centering}
-\end{figure}
-In Figures \ref{fig:netbook_complete_comp}-\ref{fig:netbook_partial_comp} we plot results of the same type of tests just described, but comparing the `Open/Close' and the `Always-open' strategies. We can see in both graphs that the more sophisticated approach 'Always-open' provides some reduction in computational time. When the entire Bayesian analysis is performed (including Metropolis and MCMC diagnostics, Figure \ref{fig:netbook_complete_comp}) the gain is on average of 5\%, but it can be more than 10\% for short chains. When the Metropolis is not performed, the gain rises on average at about 10\%. As expectable, the gain of the `Always-open' strategy is specially visible when the computational time spent in a single parallel session is not too long if compared to the cost of opening and closing new MATLAB sessions under the `Open/Close' approach.
-
-
-\subsection{Test 4}\label{s:test4}
-Here we increase the dimension of the test model, using the QUEST III model \citep{Ratto_et_al_EconModel2009}, using a more powerful Notebook Samsung Q 45 with an Dual core Processor Intel Centrino. In Figures \ref{fig:quest_complete_openclose}-\ref{fig:quest_partial_openclose} we show the computational gain of the parallel coding with the `Open/Close' strategy. When the Metropolis is included in the analysis (Figure \ref{fig:quest_complete_openclose}), the computational gain increases with the chain length. For 50,000 MH iterations, the speed-up rate is about 1.42 (i.e. a 30\% time gain), but pushing the computation up to 1,000,000 runs provides an almost ideal speed-up of 1.9 (i.e. a gain of about 50\% similar to Figure \ref{fig:test_time_comp}).
-It is also interesting to note that for this medium/large size model, even at very short chain length, the parallel coding is always winning over the serial. Excluding the Metropolis from DYNARE execution (Figure \ref{fig:quest_partial_openclose}), we can see that the speed-up rate of running the posterior analysis in parallel on two cores reaches 1.6 (i.e. 38\% of time gain).
-\begin{figure}[!ht]
-\begin{centering}
-  % Requires \usepackage{graphicx}
-  \epsfxsize=300pt \epsfbox{quest_complete_openclose.pdf}
-  \caption{Computational Time (s) versus Metropolis length, running all the parallelized functions in DYNARE and the basic parallel implementation (the `Open/Close' strategy). \citep{Ratto_et_al_EconModel2009}.}\label{fig:quest_complete_openclose}
-\end{centering}
-\end{figure}
-\begin{figure}[!hb]
-\begin{centering}
-  % Requires \usepackage{graphicx}
-  \epsfxsize=300pt \epsfbox{quest_partial_openclose.pdf}
-  \caption{Computational Time (s) versus Metropolis length, loading previously performed MH runs and running \emph{only} the parallelized functions after Metropolis \citep{Ratto_et_al_EconModel2009}. Basic parallel implementation (the `Open/Close' strategy).}\label{fig:quest_partial_openclose}
-\end{centering}
-\end{figure}
-
-We also checked the efficacy of the `Always-open' approach with respect to the `Open/Close' (Figures \ref{fig:quest_complete_comp} and \ref{fig:quest_partial_comp}). We can see in Figure \ref{fig:quest_complete_comp} that, running the entire Bayesian analysis, no advantage can be appreciated from the more sophisticated `Always-open' approach.
-\begin{figure}[t]
-\begin{centering}
-  % Requires \usepackage{graphicx}
-  \epsfxsize=300pt \epsfbox{quest_complete_comp.pdf}
-  \caption{Comparison of the `Open/Close' strategy and the `Always-open' strategy. Computational Time (s) versus Metropolis length, running all the parallelized functions in DYNARE \citep{Ratto_et_al_EconModel2009}.}\label{fig:quest_complete_comp}
-\end{centering}
-\end{figure}
-\begin{figure}[!ht]
-\begin{centering}
-  % Requires \usepackage{graphicx}
-  \epsfxsize=300pt \epsfbox{quest_partial_comp.pdf}
-  \caption{Comparison of the `Open/Close' strategy and the `Always-open' strategy. Computational Time (s) versus Metropolis length, running only the parallelized functions after Metropolis \citep[QUEST III model][]{Ratto_et_al_EconModel2009}.}\label{fig:quest_partial_comp}
-\end{centering}
-\end{figure}
-
-On the other hand, in Figure \ref{fig:quest_partial_comp}, we can see that the `Always-open' approach still provides a small speed-up rate of about 1.03. These results confirm the previous comment that the gain of the `Always-open' strategy is specially visible when the computational time spent in a single parallel session is not too long, and therefore, the bigger the model size, the less the advantage of this strategy.
-
-
-\section{Conclusions}
-The methodology identified for parallelizing MATLAB codes within DYNARE proved to be effective in reducing the computational time of the most extensive loops. This methodology is suitable for `embarrassingly parallel' codes, requiring only a minimal communication flow between slave and master threads. The parallel DYNARE is built around a few `core' routines, that act as a sort of `parallel paradigm'. Based on those routines, parallelization of expensive loops is made quite simple for DYNARE developers. A basic message passing system is also provided, that allows the master thread to monitor the progress of slave threads. The test model \verb"ls2003.mod" is available in the folder \verb"\tests\parallel" of the DYNARE distribution, that allows running parallel examples.
-
-% ----------------------------------------------------------------
-\bibliographystyle{plainnat}
-%\bibliographystyle{amsplain}
-%\bibliographystyle{alpha}
-\bibliography{marco}
-
-\newpage
-\begin{figure}
-\begin{centering}
-  % Requires \usepackage{graphicx}
-  \epsfxsize=300pt \epsfbox{RWMH_quest1_PriorsAndPosteriors1Comp.pdf}
-  \caption{Prior (grey lines) and posterior density of estimated parameters (black = 100,000 runs; red = 1,000,000 runs) using the RWMH algorithm \citep[QUEST III model][]{Ratto_et_al_EconModel2009}.}\label{fig:quest_RWMH_comp1}
-\end{centering}
-\end{figure}
-\begin{figure}
-\begin{centering}
-  % Requires \usepackage{graphicx}
-  \epsfxsize=300pt \epsfbox{RWMH_quest1_PriorsAndPosteriors2Comp.pdf}
-  \caption{Prior (grey lines) and posterior density of estimated parameters (black = 100,000 runs; red = 1,000,000 runs) using the RWMH algorithm \citep[QUEST III model][]{Ratto_et_al_EconModel2009}.}\label{fig:quest_RWMH_comp2}
-\end{centering}
-\end{figure}
-\begin{figure}
-\begin{centering}
-  % Requires \usepackage{graphicx}
-  \epsfxsize=300pt \epsfbox{RWMH_quest1_PriorsAndPosteriors3Comp.pdf}
-  \caption{Prior (grey lines) and posterior density of estimated parameters (black = 100,000 runs; red = 1,000,000 runs) using the RWMH algorithm \citep[QUEST III model][]{Ratto_et_al_EconModel2009}.}\label{fig:quest_RWMH_comp3}
-\end{centering}
-\end{figure}
-\begin{figure}
-\begin{centering}
-  % Requires \usepackage{graphicx}
-  \epsfxsize=300pt \epsfbox{RWMH_quest1_PriorsAndPosteriors4Comp.pdf}
-  \caption{Prior (grey lines) and posterior density of estimated parameters (black = 100,000 runs; red = 1,000,000 runs) using the RWMH algorithm \citep[QUEST III model][]{Ratto_et_al_EconModel2009}.}\label{fig:quest_RWMH_comp4}
-\end{centering}
-\end{figure}
-\begin{figure}
-\begin{centering}
-  % Requires \usepackage{graphicx}
-  \epsfxsize=300pt \epsfbox{RWMH_quest1_PriorsAndPosteriors5Comp.pdf}
-  \caption{Prior (grey lines) and posterior density of estimated parameters (black = 100,000 runs; red = 1,000,000 runs) using the RWMH algorithm \citep[QUEST III model][]{Ratto_et_al_EconModel2009}.}\label{fig:quest_RWMH_comp5}
-\end{centering}
-\end{figure}
-\begin{figure}
-\begin{centering}
-  % Requires \usepackage{graphicx}
-  \epsfxsize=300pt \epsfbox{RWMH_quest1_PriorsAndPosteriors6Comp.pdf}
-  \caption{Prior (grey lines) and posterior density of estimated parameters (black = 100,000 runs; red = 1,000,000 runs) using the RWMH algorithm \citep[QUEST III model][]{Ratto_et_al_EconModel2009}.}\label{fig:quest_RWMH_comp6}
-\end{centering}
-\end{figure}
-\begin{figure}
-\begin{centering}
-  % Requires \usepackage{graphicx}
-  \epsfxsize=300pt \epsfbox{RWMH_quest1_PriorsAndPosteriors7Comp.pdf}
-  \caption{Prior (grey lines) and posterior density of estimated parameters (black = 100,000 runs; red = 1,000,000 runs) using the RWMH algorithm \citep[QUEST III model][]{Ratto_et_al_EconModel2009}.}\label{fig:quest_RWMH_comp7}
-\end{centering}
-\end{figure}
-
-\clearpage
-\newpage
-
-\appendix
-\section{A tale on parallel computing}
-This is a general introduction to Parallel Computing. Readers can skip it, provided they have a basic knowledge of DYNARE and Computer Programming \citep{GoffeCreel_Grid_2008,Azzini_etal_DYNARE_2007,ParallelDYNARE}.
-There exists an ample scientific literature as well as an enormous quantity of information on the Web, about parallel computing. Sometimes, this amount of information may result ambiguous and confusing in the notation adopted and the description of technologies.  Then main the goal here is therefore to provide a very simple introduction to this subject, leaving the reader to \cite{Brookshear} for a more extensive and clear introduction to computer science.
-
-Modern computer systems (hardware and software) is conceptually identical to the first computer developed by J. Von Neumann. Nevertheless, over time, hardware, software, but most importantly \emph{hardware \& software together} have acquired an ever increasing ability to perform incredibly complex and intensive tasks. Given this complexity, we use to explain the modern computer systems as the ``avenue paradigm'', that we summarize in the next tale.
-
-Nowadays there is a small but lovely town called ``CompuTown''. In CompuTown there are many roads, which are all very similar to each other, and also many gardens. The most important road in CompuTown is the Von Neumann Avenue. The first building in Von Neumann Avenue has three floors (this is a \emph{computer system}: PC, workstation, etc.; see Figure \ref{fig:building} and \cite{Brookshear}). Floors communicate between them only with a single stair. In each floor there are people coming from the same country, with the same language, culture and uses. People living, moving and interacting with each other in the first and second floor are  the \emph{programs} or software agents or, more generally speaking, \emph{algorithms} (see chapters 3, 5, 6 and 7 in \cite{Brookshear}). Examples of the latter are the softwares MATLAB, Octave, and a particular program called the \emph{operating system} (Windows, Linux, Mac OS, etc.).
-
-\begin{figure}
-  % Requires \usepackage{graphicx}
-  \hspace{-15pt}
-  \epsfxsize=400pt \epsfbox{AvenueParadigm.pdf}
-  \caption{The first building in Von Neumann Avenue: a \emph{Computer System}}\label{fig:building}
-\end{figure}
-
-
-People at the \emph{ground floor} are the transistors, the RAM, the CPU, the hard disk, etc. (i.e. the \emph{Computer Architecture}, see chapters 1 and 2 in \citeauthor{Brookshear}).
-People at the \emph{second floor} communicate with people at the \emph{first floor} using the only existing scale (the \emph{pipe}). In these communications, people talk two different languages, and therefore do not understand each other. To remove this problem people define a set of words, fixed and understood by everybody: the \emph{Programming Languages}. More specifically, these languages are called \emph{high-level programming languages} (Java, C/C++, FORTRAN,MATLAB, etc.), because they are related to people living on the upper floors of the building! Sometimes people in the building use also pictures to communicate: \emph{the icons} and  \emph{graphical user interface}.
-
-In a similar way, people at the first floor communicate with people at the ground floor. Not surprisingly, in this case, people use \emph{low-level programming languages} to communicate to each other (assembler, binary code, machine language, etc.). More importantly, however, people at the first floor must also manage and coordinate the requests from people on the second floor to people at the ground floor, since there is no direct communication between ground and second floor. For example they need to translate high-level programming languages into binary code\footnote{The process to transform an high-level programming languages into binary code is called compilation process.}: the \emph{Operating System } performs this task.
-
-Sometimes, people at the second floor try to talk directly with people at the ground floor, via the \emph{system calls}. In the parallelizing software presented in this document, we will use frequently these system calls, to distribute the jobs between the available hardware resources, and to coordinate the overall parallel computational process.
-If only a single person without family lives on the ground floor, such as the porter, we have a CPU single core.
-In this case, the porter can only do one task at a time for the people in first or second floor (the main characteristic of the Von Neumann architecture). For example, in the morning he first collects and sorts the mail for the people in the building, and only after completing this task he can take care of the garden.
-If the porter has to do many jobs, he needs to write in a paper the list of things to do: the \emph{memory} and the \emph{CPU load}. Furthermore, to properly perform its tasks, sometimes the porter has to move some objects trough the passageways at the ground floor (the \emph{System Bus}). If the passageways have standard width, we will have a 32 bits CPU architecture (or bus). If the passageways are very large we will have, for example, a 64 bits CPU architecture (or bus).
-In this scenario, there will be very busy days where many tasks have to be done and many things have to be moved around: the porter will be very tired, although he will be able to `survive'. The most afflicted are always the people at the first floor. Every day they have a lot of new, complex requests from the people at the second floor. These requests must be translated in a correct way and passed to the porter.
-The people at the second floor (the highest floor) ``live in cloud cuckoo land''. These people want everything to be done easily and promptly: the artificial intelligence, robotics, etc.
-The activity in the building increases over time, so the porter decides to get helped in order to reduce the execution time for a single job. There are two ways to do this:
-\begin{itemize}
-\item the municipality of CompuTown interconnects all the buildings in the city using roads, so that the porter can share and distribute the jobs (the \emph{Computer Networks}): if the porters involved have the same nationality and language we have a \emph{Computer Cluster}, otherwise we have a \emph{Grid}. Nevertheless, in both cases, it is necessary to define a correct way in which porters can manage, share and complete a shared job: the \emph{communication protocol} (TCP/IP, internet protocol, etc.);
-\item the building administrator employs an additional porter, producing a \emph{Bi-Processor Computer}. In other case, the porter may get married, producing a \emph{dual-core CPU}. In this case, the wife can help the porter to perform his tasks or even take entirely some jobs for her (for example do the accounting, take care of the apartment, etc.). If the couple has a children, they can have a further little help: the \emph{thread} and then the \emph{Hyper-threading} technology.
-\end{itemize}
-
-Now a problem arises: who should coordinate the activities between the porters (and their family) and between the other buildings? Or, in other words, should we refurbish the first and second floors to take advantage of the innovations on the ground floor and of the new roads in CompuTown?
-First we can lodge new persons at the first floor: the operating systems with a set of network tools and multi-processors support, as well as new people at the second floor with new programming paradigms (MPI, OpenMP, Parrallel DYNARE, etc.). Second, a more complex communication scheme between first and ground floor is necessary, building a new set of stairs. So, for example, if we have two stairs between ground and first floor and two porters, using multi-processors and a new parallel programming paradigm, we can assign jobs to each porter directly and independently, and then coordinate the overall work. In parallel DYNARE we use this kind of `refurbishing' to reduce the computational time and to meet the request of people at the second floor.
-
-Unfortunately, this is only an idealized  scenario, where all the citizens in CompuTown live in peace and cooperate between them. In reality, some building occupants argue with each other and this can cause stopping their job: these kinds of conflicts may be linked to \emph{software and hardware compatibility} (between ground and first floor), or to different \emph{software versions} (between second and first floor). The  building administration or the municipality of CompuTown have to take care of these problems an fix them, to make the computer system operate properly.
-
-This tale (that can be also called \emph{The Programs's Society}) covered in a few pages the fundamental ideas of computer science.
-
-
-\end{document}
-% ----------------------------------------------------------------
+% ----------------------------------------------------------------
+% AMS-LaTeX Paper ************************************************
+% **** -----------------------------------------------------------
+\documentclass[12pt,a4paper,pdftex]{article}
+\usepackage[margin=2.5cm]{geometry}
+\usepackage[utf8]{inputenc}
+\usepackage{amssymb,amsmath}
+\usepackage{graphicx}
+\usepackage{epstopdf}
+\usepackage{natbib}
+\usepackage{verbatim}
+\usepackage{xcolor}
+\usepackage{psfrag}
+\usepackage{setspace}
+\usepackage{rotating}
+\usepackage{epsf}
+\usepackage{epsfig}
+
+\newcounter{exmpl}
+\def\etal{{\em et al}.}
+\def\bfp{{\bf p}}
+\def\bfz{{\bf z}}
+\def\bfU{{\bf U}}
+\def\hbfx{{\hat{\bf x}}}
+\def\be{{\begin{equation}}}
+\def\ee{{\end{equation}}}
+\def\bfF{{\bf F}}
+\def\bfP{{\bf P}}
+\def\hbfP{{\hat{\bf P}}}
+\def\bfH{{\bf H}}
+\def\bfG{{\bf G}}
+\def\bfQ{{\bf Q}}
+\def\bfL{{\bf L}}
+\def\bfI{{\bf I}}
+\def\vare{\varepsilon}
+\def\mbfx{{\bf x}}
+\def\mbfH{{\bf H}}
+\def\mbfP{{\bf P}}
+\def\mbfchi{{\mbox{\boldmath$\chi$}}}
+\def\mbfzeta{{\mbox{\boldmath$\zeta$}}}
+\def\mbfeta{{\mbox{\boldmath$\eta$}}}
+\def\ni{{\noindent}}
+\def\mbfx{{\mbox{\boldmath$x$}}}
+
+
+%\bibpunct{(}{)}{;}{a}{,}{,}
+\bibpunct[, ]{(}{)}{;}{a}{,}{,}
+%\pagestyle{headings}
+
+\def \supp{{\rm supp}}
+\def \var{{\rm var}}
+
+\usepackage[pdfpagelabels]{hyperref}
+\hypersetup{
+pdfproducer = {LaTeX},
+colorlinks,
+linkcolor=blue,
+filecolor=yellow,
+urlcolor=green,
+citecolor=green}
+
+% ----------------------------------------------------------------
+\begin{document}
+
+% ----------------------------------------------------------------
+\title{Parallel DYNARE Toolbox\\FP7 Funded \\ Project MONFISPOL Grant no.: 225149}
+
+\author{Marco Ratto\\
+European Commission, Joint Research Centre, Ispra, ITALY
+}
+%%% To have the current date inserted, use \date{\today}:
+%%% To insert a footnote, add thanks in the date/title/author fields:
+\date{\today}
+%\date{\today \thanks{Authors gratefully acknowledge the
+%contribution by ... for ...}}
+\newpage
+\singlespacing
+{\footnotesize
+\maketitle \tableofcontents
+}
+\newpage
+\doublespacing
+%-----------------------------------------------------------------------
+\begin{abstract}
+In this document, we describe the basic ideas and the methodology identified to realize the parallel package within the DYNARE project (called the ``Parallel DYNARE'' hereafter) and its algorithmic performance.
+The parallel methodology has been developed taking into account two different perspectives: the ``User perspective'' and the ``Developers perspective''. The fundamental requirement of the ``User perspective'' is to allow DYNARE users to use the parallel routines easily, quickly and appropriately. Under the ``Developers perspective'', on the other hand, we need to build a core of parallelizing routines that are sufficiently abstract and modular to allow DYNARE software developers to use them easily as a sort of `parallel paradigm', for application to any DYNARE routine or portion of code containing computational intensive loops suitable for parallelization.
+We will finally show tests showing the effectiveness of the parallel implementation.
+\end{abstract}
+% ----------------------------------------------------------------
+\newpage
+\section{The ideas implemented in Parallel DYNARE}
+The basic idea behind ``Parallel Dynare'' is to build a framework to parallelize portions of code that require a minimal (i.e. start-end communication) or no communications between different processes, denoted in the literature as ``embarrassingly parallel'' \citep{GoffeCreel_Grid_2008,Barney_2009}.  In more complicated cases there are different and more sophisticated solutions to write (or re-write) parallel codes using, for example, OpenMP or MPI.
+Within DYNARE, we can find many portions of code with the above features: loops of computational sequences with no interdependency that are coded sequentially. Clearly, this does not make optimal use of computers having 2-4-8, or more cores or CPUs.
+The basic idea is to assign the different and independent computational sequences to different cores, CPU's or computers and coordinating this new distributed computational environment with the following criteria:
+
+\begin{itemize}
+\item provide the necessary input data to any sequence, possibly including results obtained from previous DYNARE sessions (e.g. a first batch of Metropolis iterations);
+\item distribute the workload, automatically balancing between the computational resources;
+\item collect the output data;
+\item ensure the coherence of the results with the original sequential execution.
+\end{itemize}
+
+Generally, during a program execution, the largest computational time is spent to execute nested cycles. For simplicity and without loss in generality we can consider here only \verb"for" cycles (it is possible to demonstrate that any \verb"while" cycle admits an equivalent \verb"for" cycle).
+Then, after identifying the most computationally expensive \verb"for" cycles, we can split their execution (i.e. the number or iterations) between different cores, CPUs, computers. For example, consider the following simple MATLAB piece of code:
+
+\singlespacing
+
+%\begin{table}[!ht]
+%{\small
+{\footnotesize
+\hspace{3cm}
+\begin{tabular}[b]{| p{6cm} |}
+  \hline
+  % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ...
+\begin{verbatim}
+...
+n=2;
+m=10^6;
+Matrix= zeros(n,m);
+for i=1:n,
+    Matrix(i,:)=rand(1,m);
+end,
+Mse= Matrix;
+...
+\end{verbatim}
+\\
+Example \refstepcounter{exmpl} \label{ex:serial} \theexmpl
+\\  \hline
+\end{tabular}
+%\vspace*{\baselineskip}
+}
+%\end{table}
+
+%\hspace{2cm}{\begin{minipage}[c]{5cm}
+%\begin{tabular}{| p{6cm} |}
+%  \hline
+%%\begin{quote}
+%\begin{verbatim}
+%...
+%n=2;
+%m=10^6;
+%Matrix= zeros(n,m);
+%for i=1:n,
+%    Matrix(i,:)=rand(1,m);
+%end,
+%Mse= Matrix;
+%...
+%\end{verbatim}
+%\\  \hline
+%\end{tabular}
+%%\end{quote}
+%\end{minipage}}
+\doublespacing
+
+With one CPU this cycle is executed in sequence: first for \verb"i=1", and then for \verb"i=2". Nevertheless, these 2 iterations are completely independent. Then, from a theoretical point of view, if we have two CPUs (cores) we can rewrite the above code as:
+
+\singlespacing
+{\footnotesize
+\hspace{1cm}\begin{tabular}[b]{| p{10cm} |}
+  \hline
+\begin{verbatim}
+            ...
+            n=2;
+            m=10^6;
+            <provide to CPU1 and CPU2 input data m>
+
+<Execute on CPU1>            <Execute on CPU2>
+Matrix1 = zeros(1,m);         Matrix2 = zeros(1,m);
+Matrix1(1,:)=rand(1,m);       Matrix2(1,:)=rand(1,m);
+save Matrix1                  save Matrix2
+
+            retrieve Matrix1 and Matrix2
+            Mpe(1,:) = Matrix1;
+            Mpe(2,:) = Matrix2;
+\end{verbatim}
+\\
+Example \refstepcounter{exmpl} \label{ex:parallel} \theexmpl\\
+\hline
+\end{tabular}
+}
+\doublespacing
+
+The \verb"for" cycle has disappeared and it has been split into two separated sequences that can be executed in parallel on two CPUs. We have the same result (\verb"Mpa=Mse") but the computational time can be reduced up to 50\%.
+
+\section{The DYNARE environment}
+We have considered the following DYNARE components suitable to be parallelized using the above strategy:
+
+\begin{enumerate}
+\item the Random Walk- (and the analogous Independent-)-Metropolis-Hastings algorithm with multiple chains: the different chains are completely independent and do not require any communication between them, so it can be executed on different cores/CPUs/Computer Network easily;
+\item a number of procedures performed after the completion of Metropolis, that use the posterior MC sample:
+\begin{enumerate}
+\item the diagnostic tests for the convergence of the Markov Chain \\(\texttt{mcmc\_diagnostics.m});
+\item the function that computes posterior IRF's (\texttt{posteriorIRF.m}).
+\item the function that computes posterior statistics for filtered and smoothed variables, forecasts, smoothed shocks, etc.. \\ (\verb"prior_posterior_statistics.m").
+\item the utility function that loads matrices of results and produces plots for posterior statistics (\texttt{pm3.m}).
+\end{enumerate}
+\end{enumerate}
+
+Unfortunately, MATLAB does not provide commands to simply write parallel code as in Example \ref{ex:parallel} (i.e.  the pseudo-commands : \texttt{<provide inputs>}, \texttt{<execute on CPU>} and \texttt{<retrieve>}). In other words, MATLAB does not allow concurrent programming: it does not support multi-threads, without the use (and purchase) of MATLAB Distributed Computing Toolbox. Then, to obtain the behavior described in Example \ref{ex:parallel}, we had to find an alternative solution.
+
+The solution that we have found can be synthesized as follows:
+
+\begin{quote}
+\emph{When the execution of the code should start in parallel (as in Example \ref{ex:parallel}), instead of running it inside the active MATLAB session, the following steps are performed:
+\begin{enumerate}
+\item the control of the execution is passed to the operating system (Windows/Linux) that allows for multi-threading;
+\item concurrent threads (i.e. MATLAB instances) are launched on different processors/cores/machines;
+\item when the parallel computations are concluded the control is given back to the original MATLAB session that collects the result from all parallel `agents' involved and coherently continue along the sequential computation.
+\end{enumerate}
+}\end{quote}
+
+Three core functions have been developed implementing this behavior, namely \verb"MasterParallel.m", \verb"slaveParallel.m" and \verb"fParallel.m". The first function (\verb"MasterParallel.m") operates at the level of the `master' (original) thread and acts as a wrapper of the portion of code to be distributed in parallel, distributes the tasks and collects the results from the parallel computation. The other functions (\verb"slaveParallel.m" and \verb"fParallel.m") operate at the level of each individual `slave' thread and collect the jobs distributed by the `master', execute them and make the final results available to the master.
+The two different implementations of slave operation comes from the fact that, in a single DYNARE session, there may be a number parallelized sessions that are launched by the master thread. Therefore, those two routines reflect two different versions of the parallel package:
+\begin{enumerate}
+\item the `slave' MATLAB sessions are closed after completion of each single job, and new instances are called for any subsequent parallelized task (\verb"fParallel.m");
+\item once opened, the `slave' MATLAB sessions are kept open during the DYNARE session, waiting for the jobs to be executed, and are only closed upon completion of the DYNARE session on the `master' (\verb"slaveParallel.m").
+\end{enumerate}
+
+We will see that none of the two options is superior to the other, depending on the model size.
+
+
+\section{Installation and utilization}
+Here we describe how to run parallel sessions in DYNARE and, for the developers community, how to apply the package to parallelize any suitable piece of code that may be deemed necessary.
+
+\subsection{Requirements}
+
+\subsubsection{For a Windows grid}
+\begin{enumerate}
+\item a standard Windows network (SMB) must be in place;
+\item PsTools \citep{PsTools} must be installed in the path of the master Windows machine;
+\item the Windows user on the master machine has to be user of any other slave machine in the cluster, and that user will be used for the remote computations.
+\end{enumerate}
+
+\subsubsection{For a UNIX grid}
+\begin{enumerate}
+\item SSH must be installed on the master and on the slave machines;
+\item the UNIX user on the master machine has to be user of any other slave machine in the cluster, and that user will be used for the remote computations;
+\item SSH keys must be installed so that the SSH connection from the master to the slaves can be done without passwords, or using an SSH agent.
+\end{enumerate}
+
+\subsection{The user perspective}
+We assume here that the reader has some familiarity with DYNARE and its use. For the DYNARE users, the parallel routines are fully integrated and hidden inside the DYNARE environment.
+
+\subsubsection{The interface}
+The general idea is to put all the configuration of the cluster in a config file different from the MOD file, and to trigger the parallel computation with option(s) on the \verb"dynare" command line.
+The configuration file is designed as follows:
+\begin{itemize}
+  \item be in a standard location
+   \begin{itemize}
+   \item {\footnotesize\verb"$HOME/.dynare"} under Unix;
+   \item {\footnotesize\verb"c:\Documents and Setting\<username>\Application Data\dynare.ini"} on Windows;
+   \end{itemize}
+  \item have provisions for other Dynare configuration parameters unrelated to parallel computation
+  \item allow to specify several clusters, each one associated with a nickname;
+  \item For each cluster, specify a list of slaves with a list of options for each slave [if not explicitly specified by the configuration file, the preprocessor sets the options to default];
+\end{itemize}
+
+The list of slave options includes:
+\begin{description}
+\item[Name]: name of the node;
+\item[CPUnbr]:  this is the number of CPU's to be used on that computer; if \verb"CPUnbr" is a vector of integers, the syntax is \verb"[s:d]", with \verb"d>=s" (\verb"d, s" are integer); the first core has number 1 so that, on a quad-core, use \verb"4" to use all cores, but use \verb"[3:4]" to specify just the last two cores (this is particularly relevant for Windows where it is possible to assign jobs to specific processors);
+\item[ComputerName]: Computer name on the network or IP address; use the NETBIOS name under Windows\footnote{In Windows XP it is possible find this name in 'My Computer' $->$ mouse right click $->$ 'Property' $->$ 'Computer Name'.}, or the DNS name under Unix.;
+\item[UserName]: required for remote login; in order to assure proper communications between the master and the slave threads, it must be the same user name actually logged on the `master' machine. On a Windows network, this is in the form \verb"DOMAIN\username", like \verb"DEPT\JohnSmith", i.e. user JohnSmith in windows group DEPT;
+\item[Password]: required for remote login (only under Windows): it is the user password on \verb"DOMAIN" and \verb"ComputerName";
+\item[RemoteDrive]: Drive to be used on remote computer (only for Windows, for example the drive \verb"C" or drive \verb"D");
+\item[RemoteDirectory]: Directory to be used on remote computer, the parallel toolbox will create a new empty temporary subfolder which will act as remote working directory;
+\item[DynarePath]: path to matlab directory within the Dynare installation directory;
+\item[MatlabOctavePath]: path to MATLAB or Octave executable;
+\item[SingleCompThread]: disable MATLAB's native multithreading;
+\end{description}
+
+Those options have the following specifications:
+
+\singlespacing  \noindent
+{\footnotesize
+      \begin{tabular}{|l|l|l|l|l|l|l|}
+        \hline
+        % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ...
+ Node Options & type & default & \multicolumn{2}{c|}{Win} & \multicolumn{2}{c|}{Unix} \\
+ & &  & Local & Remote & Local & Remote \\ \hline
+ Name & string & (stop) & *&*&*&*\\
+ CPUnbr & integer & (stop) &*&*&*&*\\
+  & or array & & & & & \\
+ ComputerName & string & (stop) & &*& &*\\
+ UserName & string & empty & &*& &*\\
+ Password & string & empty & &*& & \\
+ RemoteDrive & string & empty & &*& & \\
+ RemoteDirectory & string & empty & &*& &*\\
+ DynarePath & string & empty & & & & \\
+ MatlabOctavePath & string & empty & & & & \\
+ SingleCompThread & boolean & true & & & & \\
+        \hline
+      \end{tabular}
+}
+\doublespacing
+
+\vspace{1cm}
+The cluster options are as follows
+
+\singlespacing \noindent
+{\footnotesize
+      \begin{tabular}{|l|l|l|l|l|}
+        \hline
+ Cluster Options & type & default & Meaning & Required \\ \hline
+ Name & string & empty & name of the node &*\\
+ Members & string & empty & list of members in this cluster &*\\
+        \hline
+      \end{tabular}
+}
+\doublespacing
+
+\vspace{1cm}
+The syntax of the configuration file will take the following form (the order in which the clusters and nodes are listed is not significant):
+
+\singlespacing
+{\footnotesize
+\hspace{2cm}\begin{tabular}[b]{| p{8cm} |}
+  \hline
+\begin{verbatim}
+[cluster]
+Name = c1
+Members = n1 n2 n3
+
+[cluster]
+Name = c2
+Members = n2 n3
+
+[node]
+Name = n1
+ComputerName = localhost
+CPUnbr = 1
+
+[node]
+Name = n2
+ComputerName = karaba.cepremap.org
+CPUnbr = 5
+UserName = houtanb
+RemoteDirectory = /home/houtanb/Remote
+DynarePath = /home/houtanb/dynare/matlab
+MatlabOctavePath = matlab
+
+[node]
+Name = n3
+ComputerName = hal.cepremap.ens.fr
+CPUnbr = 3
+UserName = houtanb
+RemoteDirectory = /home/houtanb/Remote
+DynarePath = /home/houtanb/dynare/matlab
+MatlabOctavePath = matlab
+ \end{verbatim}
+\\ \hline
+\end{tabular}
+}
+\doublespacing
+
+Finally, the DYNARE command line options are:
+ \begin{itemize}
+  \item \verb"conffile=<path>": specify the location of the configuration file if it is not standard
+  \item \verb"parallel": trigger the parallel computation using the first cluster specified in config file
+  \item \verb"parallel=<clustername>": trigger the parallel computation, using the given cluster
+  \item \verb"parallel_slave_open_mode": use the leaveSlaveOpen mode in the cluster
+  \item \verb"parallel_test": just test the cluster, don't actually run the MOD file
+
+ \end{itemize}
+
+
+
+\subsubsection{Preprocessing cluster settings}
+The DYNARE pre-processor treats user-defined configurations by filling a new sub-structure in the \verb"options_" structure, named \verb"parallel", with the following fields:
+
+\singlespacing
+{\footnotesize
+\hspace{3cm}\begin{tabular}[b]{| p{7cm} |}
+  \hline
+\begin{verbatim}
+options_.parallel=
+    struct('Local', Value,
+    'ComputerName', Value,
+    'CPUnbr', Value,
+    'UserName', Value,
+    'Password', Value,
+    'RemoteDrive', Value,
+    'RemoteFolder', Value,
+    'MatlabOctavePath', Value,
+    'DynarePath', Value);
+\end{verbatim}
+\\ \hline
+\end{tabular}
+}
+\doublespacing
+
+All these fields correspond to the slave options except \verb"Local", which is set by the pre-processor according to the value of \verb"ComputerName":	
+\begin{description}
+\item[Local:] the variable \verb"Local" is binary, so it can have only two values 0 and 1. If \verb"ComputerName" is set to \verb"localhost", the preprocessor sets \verb"Local = 1" and the parallel computation is executed on the local machine, i.e. on the same computer (and working directory) where the DYNARE project is placed. For any other value for \verb"ComputerName", we will have \verb"Local = 0";
+\end{description}
+
+In addition to the \verb"parallel" structure, which can be in a vector form, to allow specific entries for each slave machine in the cluster, there is another \verb"options_" field, called \verb"parallel_info", which stores all options that are common to all cluster. Namely, according to the \verb"parallel_slave_open_mode" in the command line, the \verb"leaveSlaveOpen" field takes values:
+\begin{description}
+\item[\texttt{leaveSlaveOpen=1}]: with \verb"parallel_slave_open_mode", i.e. the slaves operate `Always-Open'.
+\item[\texttt{leaveSlaveOpen=0}]: without \verb"parallel_slave_open_mode", i.e. the slaves operate `Open-Close';
+\end{description}
+
+
+\subsubsection{Example syntax for Windows and Unix, for local parallel runs (assuming quad-core)}
+In this case, the only slave options are \verb"ComputerName" and \verb"CPUnbr".
+
+\singlespacing
+{\footnotesize
+\hspace{2cm}\begin{tabular}[b]{| p{8cm} |}
+  \hline
+\begin{verbatim}
+[cluster]
+Name = local
+Members = n1
+
+[node]
+Name = n1
+ComputerName = localhost
+CPUnbr = 4
+\end{verbatim}
+\\ \hline
+\end{tabular}
+}
+\doublespacing
+
+\subsubsection{Examples of Windows syntax for remote runs}
+\begin{itemize}
+\item the Windows \verb"Password" has to be typed explicitly;
+\item \verb"RemoteDrive" has to be typed explicitly;
+\item for \verb"UserName", ALSO the group has to be specified, like \verb"DEPT\JohnSmith", i.e. user \verb"JohnSmith" in windows group \verb"DEPT";
+\item \verb"ComputerName" is the name of the computer in the windows network, i.e. the output of hostname, or the full IP address.
+\end{itemize}
+
+\begin{description}
+\item[Example 1] Parallel codes that are run on a remote computer named \verb"vonNeumann" with eight cores, using only the cores 4,5,6, working on the drive 'C' and folder '\verb"dynare_calcs\Remote"'. The computer \verb"vonNeumann" is in a net domain of the CompuTown university, with user \verb"John" logged with the password \verb"*****":
+
+\singlespacing
+{\footnotesize
+\hspace{2cm}\begin{tabular}[b]{| p{8cm} |}
+  \hline
+\begin{verbatim}
+[cluster]
+Name = vonNeumann
+Members = n2
+
+[node]
+Name = n2
+ComputerName = vonNeumann
+CPUnbr = [4:6]
+UserName = COMPUTOWN\John
+Password = *****
+RemoteDrive = C
+RemoteDirectory = dynare_calcs\Remote
+DynarePath = c:\dynare\matlab
+MatlabOctavePath = matlab
+\end{verbatim}
+\\ \hline
+\end{tabular}
+}
+\doublespacing
+
+\item[Example 2] We can build a cluster, combining local and remote runs. For example the following configuration file includes the two previous configurations but also gives the possibility (with cluster name \verb"c2") to build a grid with a total number of 7 CPU's :
+
+\singlespacing
+{\footnotesize
+\hspace{2cm}\begin{tabular}[b]{| p{8cm} |}
+  \hline
+\begin{verbatim}
+[cluster]
+Name = local
+Members = n1
+
+[cluster]
+Name = vonNeumann
+Members = n2
+
+[cluster]
+Name = c2
+Members = n1 n2
+
+[node]
+Name = n1
+ComputerName = localhost
+CPUnbr = 4
+
+[node]
+Name = n2
+ComputerName = vonNeumann
+CPUnbr = [4:6]
+UserName = COMPUTOWN\John
+Password = *****
+RemoteDrive = C
+RemoteDirectory = dynare_calcs\Remote
+DynarePath = c:\dynare\matlab
+MatlabOctavePath = matlab
+\end{verbatim}
+\\ \hline
+\end{tabular}
+}
+\doublespacing
+\item[Example 3] We can build a cluster, combining many remote machines. For example the following commands build a grid of four machines with a total number of 14 CPU's:
+
+\singlespacing
+{\footnotesize
+\hspace{2cm}\begin{tabular}[b]{| p{8cm} |}
+  \hline
+\begin{verbatim}
+[cluster]
+Name = c4
+Members = n1 n2 n3 n4
+
+[node]
+Name = n1
+ComputerName = vonNeumann1
+CPUnbr = 4
+UserName = COMPUTOWN\John
+Password = *****
+RemoteDrive = C
+RemoteDirectory = dynare_calcs\Remote
+DynarePath = c:\dynare\matlab
+MatlabOctavePath = matlab
+
+[node]
+Name = n2
+ComputerName = vonNeumann2
+CPUnbr = 4
+UserName = COMPUTOWN\John
+Password = *****
+RemoteDrive = C
+RemoteDirectory = dynare_calcs\Remote
+DynarePath = c:\dynare\matlab
+MatlabOctavePath = matlab
+
+[node]
+Name = n3
+ComputerName = vonNeumann3
+CPUnbr = 2
+UserName = COMPUTOWN\John
+Password = *****
+RemoteDrive = D
+RemoteDirectory = dynare_calcs\Remote
+DynarePath = c:\dynare\matlab
+MatlabOctavePath = matlab
+
+[node]
+Name = n4
+ComputerName = vonNeumann4
+CPUnbr = 4
+UserName = COMPUTOWN\John
+Password = *****
+RemoteDrive = C
+RemoteDirectory = John\dynare_calcs\Remote
+DynarePath = c:\dynare\matlab
+MatlabOctavePath = matlab
+
+\end{verbatim}
+\\ \hline
+\end{tabular}
+}
+\doublespacing
+\end{description}
+
+
+
+\subsubsection{Example Unix syntax for remote runs}
+\begin{itemize}
+\item no \verb"Password" and \verb"RemoteDrive" fields are needed;
+\item \verb"ComputerName" is the full IP address or the DNS address.
+\end{itemize}
+
+\begin{description}
+\item[One remote slave:] the following command defines remote runs on the machine \verb"name.domain.org".\\
+\singlespacing
+{\footnotesize
+\hspace{2cm}\begin{tabular}[b]{| p{8cm} |}
+  \hline
+\begin{verbatim}
+[cluster]
+Name = unix1
+Members = n2
+
+[node]
+Name = n2
+ComputerName = name.domain.org
+CPUnbr = 4
+UserName = JohnSmith
+RemoteDirectory = /home/john/Remote
+DynarePath = /home/john/dynare/matlab
+MatlabOctavePath = matlab
+\end{verbatim}
+\\ \hline
+\end{tabular}
+}
+\doublespacing
+\item[Combining local and remote runs:] the following commands define a cluster of local an remote CPU's.
+\singlespacing
+{\footnotesize
+\hspace{2cm}\begin{tabular}[b]{| p{8cm} |}
+  \hline
+\begin{verbatim}
+[cluster]
+Name = unix2
+Members = n1 n2
+
+[node]
+Name = n1
+ComputerName = localhost
+CPUnbr = 4
+
+[node]
+Name = n2
+ComputerName = name.domain.org
+CPUnbr = 4
+UserName = JohnSmith
+RemoteDirectory = /home/john/Remote
+DynarePath = /home/john/dynare/matlab
+MatlabOctavePath = matlab
+\end{verbatim}
+\\ \hline
+\end{tabular}
+}
+\doublespacing
+\end{description}
+
+\subsubsection{Testing the cluster}
+
+In this section we describe what happens when the user omits a mandatory entry or provides bad values for them and how DYNARE reacts in these cases. In the parallel package there is a utility (\verb"AnalyseComputationalEnvironment.m") devoted to this task (this is triggered by the command line option \verb"parallel_test"). When necessary during the discussion, we use the \verb"parallel" entries used in the previous examples.
+
+%Le parti in rosa sono una possibile reazione ad un errore che può accadere vanno concordate e quindi magari riviste.
+
+\begin{description}
+%\item[Local:] if no value is given for this variable the execution is stopped when DYNARE starts. More serious if we give a bad value (i.e. for example -1, 3), DYNARE will be stopped after some time with no error message!
+\item[ComputerName:] If \verb"Local=0", DYNARE checks if the computer \verb"vonNeumann" exists and if it is possible communicate with it. If this is not the case, an error message is generated and the computation is stopped.
+\item[CPUnbr:] a value for this variable must be in the form \verb"[s:d]" with \verb"d>=s". If the user types  values \verb"s>d", their order is flipped and a warning message is sent. When the user provides a correct value for this field, DYNARE checks if \verb"d" CPUs (or cores) are available on the computer. Suppose that this check returns an integer \verb"nC". We can have three possibilities:
+    \begin{enumerate}
+    \item \verb"nC= d;" all the CPU's available are used, no warning message are generated by DYNARE;
+    \item \verb"nC> d;" some CPU's will not be used;
+    \item \verb"nC< d;" DYNARE alerts the user that there are less CPU's than those declared. The parallel tasks would run in any case, but some CPU's will have multiple instances assigned, with no gain in computational time.
+    \end{enumerate}
+\item[UserName \& Password:] if \verb"Local = 1", no information about user name and password is necessary: ``I am working on this computer''. When remote computations on a Windows network are required, DYNARE checks if the user name and password are correct, otherwise execution is stopped with an error; for a Unix network, the user and the proper operation of SSH is checked;
+\item[RemoteDrive \& RemoteDirectory:] if \verb"Local = 1", these fields are not required since the working directory of the `slaves' will be the same of the `master'. If \verb"Local = 0", DYNARE tries to copy a file (\verb"Tracing.txt") in this remote location. If this operation fails, the DYNARE execution is stopped with an error;
+\item[MatlabOctavePath \& DynarePath:] MATLAB instances are tried on slaves and the DYNARE path is checked.
+\end{description}
+
+
+\subsection{The Developers perspective}
+%L'esposizione nel seguito (e anche in alcuni punti su) dipende molto da come il pacchetto parallelo viene rilasciato in Dynare, e quindi se PsTools viene installato durante l'installazione di Dynare oppure no, se le directory necessarie alla computazione vengono create durante l'installazione di Dynare oppure no. E cose così ...
+
+
+In this section we describe with some accuracy the DYNARE parallel routines.
+\begin{description}
+\item[Windows:]
+With Windows operating system, the parallel package requires the installation of a free software package called PsTools \citep{PsTools}. PsTools suite is a resource kit with a number of command line tools that mimics administrative features available under the Unix environment. PsTools can be downloaded from \cite{PsTools} and extracted in a Windows directory on your computer: to make PsTools working properly, it is mandatory to add this directory to the Windows path. After this step it is possible to invoke and use the PsTools commands from any location in the Windows file system. PsTools, MATLAB and DYNARE have to be installed and work properly on all the machines in the grid for parallel computation.
+\item[Unix:]
+With Unix operating system, SSH must be installed on the master and on the slave machines. Moreover, SSH keys must be installed so that the SSH connections from the master to the slaves can be done without passwords.
+\end{description}
+
+% NO DEFAULT REMOTE FOLDER !!!!!!
+%\item the creation of a directory devoted to the local/remote computation and data exchanges. %We usually create this directory on local drive 'C' within a directory '\verb"dynare_calcs"' and call it 'Remote', i.e. '\verb"C:\dynare_calcs\Remote"'. In this way the default value for RemoteDrive \& RemoteDirectory will be 'C' \& '\verb"C:\dynare_calcs\Remote"'.
+
+As soon as the computational environment is set-up for working on a grid of CPU's, the parallel package allows to parallelize any loop that is computationally expensive, following the step by step procedure showed in Table \ref{tab:devpar}. This is done using five basic functions: \verb"masterParallel.m", \verb"fParallel.m" or \verb"slaveParallel.m", \verb"fMessageStatus.m", \verb"closeSlave.m".
+
+\begin{description}
+ \item[\texttt{masterParallel}] is the entry point to the parallelization system:
+ \begin{itemize}
+  \item It is called from the master computer, at the point where the parallelization system should be activated. Its main arguments are the name of the function containing the task to be run on every slave computer, inputs to that function stored in two structures (one for local and the other for global variables), and the configuration of the cluster; this function exits when the task has finished on all computers of the cluster, and returns the output in a structure vector (one entry per slave);
+  \item all file exchange through the filesystem is concentrated in this \verb"masterParallel" routine: so it prepares and send the input information for slaves, it retrieves from slaves the info about the status of remote computations stored on remote slaves by the remote processes; finally it retrieves outputs stored on remote machines by slave processes;
+  \item there are two modes of parallel execution, triggered by option \verb"parallel_slave_open_mode":
+   \begin{itemize}
+   \item when \verb"parallel_slave_open_mode=0", the slave processes are closed after the completion of each task, and new instances are initiated when a new job is required; this mode is managed by \verb"fParallel.m" [`Open-Close'];
+   \item when \verb"parallel_slave_open_mode=1", the slave processes are kept running after the completion of each task, and wait for new jobs to be performed; this mode is managed by \texttt{slaveParallel.m} [`Always-Open'];
+   \end{itemize}
+  \end{itemize}
+ \item[\texttt{slaveParallel.m/fParallel.m}:] are the top-level functions to be run on every slave; their main arguments are the name of the function to be run (containing the computing task), and some information identifying the slave; the functions use the input information that has been previously prepared and sent by \verb"masterParallel" through the filesystem, call the computing task, finally the routines store locally on remote machines the  outputs such that \verb"masterParallel" retrieves back the outputs to the master computer;
+ \item[\texttt{fMessageStatus.m}:] provides the core for simple message passing during slave execution: using this routine, slave processes can store locally on remote machine basic info on the progress of computations; such information is retrieved by the master process (i.e. \verb"masterParallel.m") allowing to echo progress of remote computations on the master; the routine \verb"fMessageStatus.m" is also the entry-point where a signal of interruption sent by the master can be checked and executed; this routine typically replaces calls to \verb"waitbar.m";
+ \item[\texttt{closeSlave.m}] is the utility that sends a signal to remote slaves to close themselves. In the standard operation, this is only needed with the `Always-Open' mode and it is called when DYNARE computations are completed. At that point, \texttt{slaveParallel.m} will get a signal to terminate and no longer wait for new jobs. However, this utility is also useful in any parallel mode if, for any reason, the master needs to interrupt the remote computations which are running;
+ \end{description}
+
+The parallel toolbox also includes a number of utilities:
+\begin{itemize}
+ \item \verb"AnalyseComputationalEnviroment.m": this a testing utility that checks that the cluster works properly and echoes error messages when problems are detected;
+ \item \verb"InitializeComputationalEnviroment.m" : initializes some internal variables and remote directories;
+ \item \verb"distributeJobs.m": uses a simple algorithm to distribute evenly jobs across the available CPU's;
+ \item a number of generalized routines that properly perform \verb"delete", \verb"copy", \verb"mkdir", \verb"rmdir" commands through the network file-system (i.e. used from the master to operate on slave machines); the routines are adaptive to the actual environment (Windows or Unix);
+ \begin{description}
+  \item[\texttt{dynareParallelDelete.m}]: generalized \verb"delete";
+  \item[\texttt{dynareParallelDir.m}]: generalized \verb"dir";
+  \item[\texttt{dynareParallelGetFiles.m}]: generalized \verb"copy" FROM slaves TO master machine;
+  \item[\texttt{dynareParallelMkDir.m}]: generalized \verb"mkdir" on remote machines;
+  \item[\texttt{dynareParallelRmDir.m}]: generalized \verb"rmdir" on remote machined;
+  \item[\texttt{dynareParallelSendFiles.m}]: generalized \verb"copy" TO slaves FROM master machine;
+ \end{description}
+\end{itemize}
+
+In Table \ref{tab:devpar} we have synthesized the main steps for parallelizing MATLAB codes.
+
+{\small
+\begin{table}
+\begin{tabular}{|p{\linewidth}|}
+\hline
+\begin{enumerate}
+\item locate within DYNARE the portion of code suitable to be parallelized, i.e. an expensive cycle \verb"for";
+\item suppose that the function \verb"tuna.m" contains a cycle \verb"for" that is suitable for parallelization: this cycle has to be extracted from \verb"tuna.m" and put it in a new MATLAB function named \verb"tuna_core.m";
+\item at the point where the expensive cycle should start, the function \verb"tuna.m" invokes the utility \verb"masterParallel.m", passing to it the \verb"options_.parallel" structure, the name of the of the function to be run in parallel (\verb"tuna_core.m"), the local and global variables needed and all the information about the files (MATLAB functions \verb"*.m"; data files \verb"*.mat") that will be handled by \verb"tuna_core.m";
+\item the function \verb"masterParallel.m" reads the input arguments provided by \verb"tuna.m" and:
+\begin{itemize}
+\item decides how to distribute the task evenly across the available CPU's (using the utility routine \verb"distributeJobs.m"); prepares and initializes the computational environment (i.e. copy files/data) for each slave machine;
+\item uses the PsTools and the Operating System commands to launch new MATLAB instances, synchronize the computations, monitor the progress of slave tasks through a simple message passing system (see later) and collect results upon completion of the slave threads;
+\end{itemize}
+\item the slave threads are executed using the MATLAB functions \verb"fParallel.m"/\verb"slaveParallel.m" as wrappers for implementing the tasks sent by the master (i.e. to run the \verb"tuna_core.m" routine);
+\item the utility \verb"fMessageStatus.m" can be used within the core routine \verb"tuna_core.m" to send information to the master regarding the progress of the slave thread;
+\item when all DYNARE computations are completed, \verb"closeSlave.m" closes all open remote MATLAB/OCTAVE instances waiting for new jobs to be run.
+\end{enumerate}
+\\ \hline
+\end{tabular}
+\caption{Procedure for parallelizing portions of codes.}\label{tab:devpar}
+\end{table}
+}
+
+So far, we have parallelized the following functions, by selecting the most computationally intensive loops:
+\begin{enumerate}
+\item the cycle looping for multiple chain random walk Metropolis:\\
+\verb"random_walk_metropolis_hastings", \\
+\verb"random_walk_metropolis_hastings_core";
+\item the cycle looping for multiple chain independent Metropolis:\\
+\verb"independent_metropolis_hastings.m", \\
+\verb"independent_metropolis_hastings_core.m";
+\item the cycle looping over estimated parameters computing univariate diagnostics:\\
+\verb"mcmc_diagnostics.m", \\
+\verb"mcmc_diagnostics_core.m";
+\item the Monte Carlo cycle looping over posterior parameter subdraws performing the IRF simulations (\verb"<*>_core1") and the cycle looping over exogenous shocks plotting IRF's charts (\verb"<*>_core2"):\\
+\verb"posteriorIRF.m", \\\verb"posteriorIRF_core1.m", \verb"posteriorIRF_core2.m";
+\item the Monte Carlo cycle looping over posterior parameter subdraws, that computes filtered, smoothed, forecasted variables and shocks:\\
+\verb"prior_posterior_statistics.m", \\
+\verb"prior_posterior_statistics_core.m";
+\item the cycle looping over endogenous variables making posterior plots of filter, smoother, forecasts:
+\verb"pm3.m", \verb"pm3_core.m".
+\end{enumerate}
+%A developer can use the existent functions \verb"masterParalle.m" and \verb"fParalell.m"  a couple of functions already parallelized as example and then to add new parallel routine in Dynare.
+%Remember that, from the user side to use the parallel routines it is only required to insert in the .mod file the commands the \verb"options_.parallel" structure as described above (see also [2, 5]). If the file \verb".mod" do not contain this structure (or it is commented) Dynare is executed in a traditional way.
+
+\subsubsection{Write a parallel code: an example}
+%Per questo paragrafo ci sono secondo me due soluzioni possibili:
+%
+%1.
+%
+Using a MATLAB pseudo (but very realistic) code, we now describe in detail how to use the above step by step procedure to parallelize the random walk Metropolis Hastings algorithm. Any other function can be parallelized in the same way.
+
+It is obvious that most of the computational time spent by the \\ \verb"random_walk_metropolis_hastings.m" function is given by the cycle looping over the parallel chains performing the Metropolis:
+
+\singlespacing
+{\footnotesize
+\hspace{2cm}\begin{tabular}[b]{| p{9cm} |}
+  \hline
+\begin{verbatim}
+function random_walk_metropolis_hastings
+       (TargetFun, ProposalFun, ..., varargin)
+[...]
+for b = fblck:nblck,
+...
+end
+[...]
+\end{verbatim}
+\\ \hline
+\end{tabular}
+}
+\doublespacing
+
+Since those chains are totally independent, the obvious way to reduce the computational time is to parallelize this loop, executing the \verb"(nblck-fblck)" chains on different computers/CPUs/cores.
+
+%\singlespacing
+%{\footnotesize
+%\hspace{2cm}\begin{tabular}[b]{| p{9cm} |}
+%  \hline
+%\begin{verbatim}
+%...
+%if (nblck>fblck) & (number of available CPUs >1)
+%execute
+%the	nblck - nblck branch on CPU 1
+%	    	(nblck+1) - (nblck+1) on CPU 2
+%		[...]
+%		Fblck - fblck on CPU F
+%else
+%	for b = fblck:nblck,
+%...
+%end
+%end
+%...
+%\end{verbatim}
+%\\ \hline
+%\end{tabular}
+%}
+%\doublespacing
+
+To do so, we remove the \verb"for" cycle and put it in a new function named \verb"<*>_core.m":
+
+\singlespacing
+{\footnotesize
+\noindent\begin{tabular}[b]{| p{\linewidth} |}
+\hline
+\begin{verbatim}
+function myoutput =
+    random_walk_metropolis_hastings_core(myinputs,fblck,nblck, ...)
+[...]
+\end{verbatim}
+just list global variables needed (they are set-up properly by \verb"fParallel" or \verb"slaveParallel")
+\begin{verbatim}
+global bayestopt_ estim_params_ options_  M_ oo_
+\end{verbatim}
+here we collect all local variables stored in \verb"myinputs"
+\begin{verbatim}
+TargetFun=myinputs.TargetFun;
+ProposalFun=myinputs.ProposalFun;
+xparam1=myinputs.xparam1;
+[...]
+\end{verbatim}
+here we run the loop
+\begin{verbatim}
+for b = fblck:nblck,
+...
+end
+[...]
+\end{verbatim}
+here we wrap all output arguments needed by the `master' routine
+\begin{verbatim}
+myoutput.record = record;
+[...]
+\end{verbatim}
+\\ \hline
+\end{tabular}
+}
+\doublespacing
+The split of the \verb"for" cycle has to be performed in such a way that the new \verb"<*>_core" function can work in both serial and parallel mode. In the latter case, such a function will be invoked by the slave threads and executed for the number of iterations assigned by \verb"masterParallel.m".
+
+The modified \verb"random_walk_metropolis_hastings.m" is therefore:
+
+\singlespacing
+{\footnotesize
+\noindent\begin{tabular}[b]{| p{\linewidth} |}
+\hline
+\begin{verbatim}
+function random_walk_metropolis_hastings(TargetFun,ProposalFun,\ldots,varargin)
+[...]
+% here we wrap all local variables needed by the <*>_core function
+localVars = struct('TargetFun', TargetFun, ...
+[...]
+    'd', d);
+[...]
+% here we put the switch between serial and parallel computation:
+if isnumeric(options_.parallel) || (nblck-fblck)==0,
+% serial computation
+    fout = random_walk_metropolis_hastings_core(localVars, fblck,nblck, 0);
+    record = fout.record;
+
+else
+% parallel computation
+
+    % global variables for parallel routines
+    globalVars = struct('M_',M_, ...
+                       [...]
+                       'oo_', oo_);
+
+    % which files have to be copied to run remotely
+    NamFileInput(1,:) = {'',[ModelName '_static.m']};
+    NamFileInput(2,:) = {'',[ModelName '_dynamic.m']};
+    [ ...]
+
+    % call the master parallelizing utility
+    [fout, nBlockPerCPU, totCPU] = masterParallel(options_.parallel, ...
+    fblck, nblck, NamFileInput, 'random_walk_metropolis_hastings_core',
+    localVars, globalVars, options_.parallel_info);
+
+    % collect output info from parallel tasks provided in fout
+    [ ...]
+end
+
+% collect output info from either serial or parallel tasks
+irun = fout(1).irun;
+NewFile = fout(1).NewFile;
+[...]
+\end{verbatim}
+\\ \hline
+\end{tabular}
+}
+\doublespacing
+
+Finally, in order to allow the master thread to monitor the progress of the slave threads, some message passing elements have to be introduced in the \verb"<*>_core.m" file. The utility function \verb"fMessageStatus.m" has been  designed as an interface for this task, and can be seen as a generalized form of the MATLAB utility \verb"waitbar.m".
+
+In the following example, we show a typical use of this utility, again from the random walk Metropolis routine:
+\singlespacing
+{\footnotesize
+\noindent\begin{tabular}[b]{| p{\linewidth} |}
+\hline
+\begin{verbatim}
+for  j = 1:nruns
+[...]
+% define the progress of the loop:
+prtfrc = j/nruns;
+
+% define a running message:
+% first indicate which chain is running on the current CPU [b]
+% out of the chains [mh_nblock] requested by the DYNARE user
+waitbarString = [ '(' int2str(b) '/' int2str(mh_nblck) ') ...
+
+% then add possible further information, like the acceptation rate
+    ' sprintf('%f done, acceptation rate %f',prtfrc,isux/j)]
+
+    if mod(j, 3)==0 & ~whoiam
+        % serial computation
+        waitbar(prtfrc,hh_fig,waitbarString);
+
+    elseif mod(j,50)==0 & whoiam,
+        % parallel computation
+        fMessageStatus(prtfrc, ...
+            whoiam, ...
+            waitbarString, ...
+            waitbarTitle, ...
+            options_.parallel(ThisMatlab))
+
+    end
+    [...]
+end
+\end{verbatim}
+\\ \hline
+\end{tabular}
+}
+\doublespacing
+In the previous example, a number of arguments are used to identify which CPU and which computer in the claster is sending the message, namely:
+\singlespacing
+{\footnotesize
+\noindent\begin{tabular}[b]{| p{\linewidth} |}
+\hline
+\begin{verbatim}
+%  whoiam [int]         index number of this CPU among all CPUs in the
+%                       cluster
+%  ThisMatlab [int]     index number of this slave machine in the cluster
+%                       (entry in options_.parallel)
+\end{verbatim}
+\\ \hline
+\end{tabular}
+}
+\doublespacing
+The message is stored as a MATLAB data file \verb"*.mat" saved on the working directory of remote slave computer. The master will will check periodically for those messages and retrieve the files from remote computers and produce an advanced monitoring plot.
+
+So, assuming to run two Metropolis chains, under the standard serial implementation there will be a first \verb"waitbar" popping up on matlab, corresponding to the first chain:
+
+\hspace{2cm}\epsfxsize=200pt \epsfbox{waitbars1.pdf}
+
+\ni followed by a second \texttt{waitbar}, when the first chain is completed.
+
+\hspace{2cm}\epsfxsize=200pt \epsfbox{waitbars2.pdf}
+
+On the other hand, under the parallel implementation, a parallel monitoring plot will be produced by \texttt{masterParallel.m}:
+
+\hspace{2cm}\epsfxsize=200pt \epsfbox{waitbarsP.pdf}
+
+
+
+%Finally we describe the masterParallel.m and fParallel.m functions:
+%
+%\begin{verbatim}
+%function Results= masterParallel (DATA, functionName)
+%
+%[...]
+%
+%read  options_.parallel;
+%call the function rACE=AnalyseComputationalEnviroment (options_.parallel);
+%
+%switch rACE
+%	[...]
+%end
+%[...]
+%\end{verbatim}
+
+%Non so se può andare bene impostata in questo modo se va bene la concludo.
+%
+%2.
+%Prendiamo il tutto il lavoro fatto per arrivare a parallellizzare la PosteriorIRF,
+%Traacianti, anlisi computazionale commentiamo bene tutte le funzioni coinvolte e le usiamo qui
+
+
+\section{Parallel DYNARE: testing}
+We checked the new parallel platform for DYNARE performing a number of tests, using different models and computer architectures. We present here all tests performed with Windows XP/MATLAB. However, similar tests were performed successfully under Linux/Ubuntu environment.
+In the Bayesian estimation of DSGE models with DYNARE, most of the computing time is devoted to the posterior parameter estimation with the Metropolis algorithm. The first and second tests are therefore focused on the parallelization of the Random Walking Metropolis Hastings algorithm (Sections \ref{s:test1}-\ref{s:test2}). In addition, further tests (Sections \ref{s:test3}-\ref{s:test4}) are devoted to test all the parallelized functions in DYNARE. %Finally, we compare the two parallel implementations of the Metropolis Hastings algorithms, available in DYNARE: the Independent and the Random Walk (Section \ref{s:test5}).
+
+\subsection{Test 1.}\label{s:test1}
+The main goal here was to evaluate the parallel package on a \emph{fixed hardware platform} and using chains of \emph{variable length}. The model used for testing is a modification of \cite{Hradisky_etal_2006}. This is a small scale open economy DSGE model with 6 observed variables, 6 endogenous variables and 19 parameters to be estimated.
+We estimated the model on a bi-processor machine (Fujitsu Siemens, Celsius R630) powered with an Intel\textsuperscript{\textregistered} Xeon\texttrademark CPU 2.80GHz Hyper Treading Technology; first with the original serial Metropolis and subsequently using the parallel solution, to take advantage of the two processors technology. We ran chains of increasing length: 2500, 5000, 10,000, 50,000, 100,000, 250,000, 1,000,000.
+
+\begin{figure}[!ht]
+\begin{centering}
+  % Requires \usepackage{graphicx}
+  \epsfxsize=300pt \epsfbox{iVaNo_time_comp.pdf}
+  \caption{Computational time (in minutes) versus chain length for the serial and parallel implementation (Metropolis with two chains).}\label{fig:test_time_comp}
+\end{centering}
+\end{figure}
+\begin{figure}[!ht]
+\begin{centering}
+  % Requires \usepackage{graphicx}
+  \epsfxsize=300pt \epsfbox{iVaNo_gain.pdf}
+  \caption{Reduction of computational time (i.e. the `time gain') using the parallel coding versus chain length. The time gain is computed as $(T_s-T_p)/T_p$, where $T_s$ and $T_p$ denote the computing time of the serial and parallel implementations respectively.}\label{fig:test_gain}
+\end{centering}
+\end{figure}
+
+Overall results are given in Figure \ref{fig:test_time_comp}, showing the computational time versus chain length, and Figure \ref{fig:test_gain}, showing the reduction of computational time (or the time gain) with respect to the serial implementation provided by the parallel coding. The gain in computing time of the exercise is of about 45\% on this test case, so reducing from 11.40 hours to about 6 hours the cost of running 1,000,000 Metropolis iterations (the ideal gain would be of 50\% in this case).
+
+\subsection{Test 2.}\label{s:test2}	
+The scope of the second test was to verify if results were robust over different hardware platforms.
+We estimated the model with chain lengths of 1,000,000 runs on the following hardware platforms:
+\begin{itemize}
+\item Single processor machine: Intel\textsuperscript{\textregistered} Pentium4\textsuperscript{\textregistered} CPU 3.40GHz with Hyper Treading Technology (Fujitsu-Siemens Scenic Esprimo);
+\item Bi-processor machine: two CPU's Intel\textsuperscript{\textregistered} Xeon\texttrademark 2.80GHz Hyper Treading Technology (Fujitsu-Siemens, Celsius R630);
+\item Dual core machine: Intel Centrino T2500 2.00GHz Dual Core  (Fujitsu-Siemens, LifeBook S Series).
+\end{itemize}
+
+We first run the tests with normal configuration. However, since (i) dissimilar software environment on the machine can influence the computation; (ii) Windows service (Network, Hard Disk writing, Demon, Software Updating, Antivirus, etc.) can start during the simulation; we also run the tests not allowing for any other process to start during the estimation. Table \ref{tab:trail} gives results for the ordinary software environment and process priority is set as low/normal.
+
+\begin{table}
+\begin{centering}
+\begin{tabular}{l|l|l|l}
+  % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ...
+Machine	& Single-processor	& Bi-processor	& Dual core \\ \hline
+Parallel & 8:01:21 & 7:02:19 & 5:39:38 \\
+Serial & 10:12:22 & 13:38:30 & 11:02:14 \\
+Speed-Up rate & 1.2722 & 1.9381 & 1.9498\\
+Ideal Speed-UP rate &  $\sim$1.5 & 2 & 2 \\
+  \hline
+\end{tabular}
+\caption{Trail results with normal PC operation. Computing time expressed in h:m:s. Speed-up rate is computed as $T_s/T_p$, where $T_s$ and $T_p$ are the computing times for the serial and parallel implementations.}\label{tab:trail}
+\end{centering}
+\end{table}
+
+Results showed that Dual-core technology provides a similar gain if compared with bi-processor results, again about 45\%. The striking results was that the Dual-core processor clocked at 2.0GHz was about 30\% faster than the Bi-processor clocked at 2.8GHz. Interesting gains were also obtained via multi-threading on the Single-processor machine, with speed-up being about 1.27 (i.e. time gain of about 21\%). However, beware that we burned a number of processors performing tests on single processors with hyper-threading and using very long chains (1,000,000 runs)!
+We re-run the tests on the Dual-core machine, by cleaning the PC operation from any interference by other programs and show results in Table \ref{tab:trail2}.
+A speed-up rate of 1.06 (i.e. 5.6\% time gain) can be obtained simply hiding the MATLAB waitbar. The speed-up rate can be pushed to 1.22 (i.e. 18\% time gain) by disconnecting the network and setting the priority of the process to real time. It can be noted that from the original configuration, taking 11:02 hours to run the two parallel chains, the computational time can be reduced to 4:40 hours (i.e. for a total time gain of over 60\% with respect to the serial computation) by parallelizing and optimally configuring the operating environment.
+These results are somehow surprising and show how it is possible to reduce dramatically the computational time with slight modification in the software configuration.
+\begin{table}[t]
+\begin{centering}
+\begin{tabular}{p{5cm}|l|l}
+  % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ...
+Environment	& Computing time & Speed-up rate \\
+& & w.r.t. Table \ref{tab:trail}\\ \hline
+Parallel Waitbar Not Visible & 5:06:00 & 1.06 \\ \hline
+Parallel waitbar Not Visible, Real-time Process priority,
+Unplugged network cable. &
+	4:40:49 & 1.22\\
+  \hline
+\end{tabular}
+\caption{Trail results with different software configurations (optimized operating environment for computational requirements).}\label{tab:trail2}
+\end{centering}
+\end{table}
+
+Given the excellent results reported above, we have parallelized many other DYNARE functions. This implies that parallel instances can be invoked many times during a single DYNARE session. Under the basic parallel toolbox implementation, that we call the `Open/Close' strategy, this implies that MATLAB instances are opened and closed many times by system calls, possibly slowing down the computation, specially for `entry-level' computer resources. As mentioned before, this suggested to implement an alternative strategy for the parallel toolbox, that we call the `Always-Open' strategy, where the slave MATLAB threads, once opened, stay alive and wait for new tasks assigned by the master until the full DYNARE procedure is completed. We show next the tests of these latest implementations.
+
+\subsection{Test 3}\label{s:test3}
+In this Section we use the \cite{Lubik2003} model as test function\footnote{The \cite{Lubik2003} model is also selected as the `official' test model for the parallel toolbox in DYNARE.} and a very simple computer class, quite diffuse nowadays: Netbook personal Computer. In particular we used the Dell Mini 10 with Processor Intel\textsuperscript{\textregistered} Atom\texttrademark Z520 (1,33 GHz, 533 MHz), 1 GB di RAM (with Hyper-trading). First, we tested the computational gain of running a full Bayesian estimation: Metropolis (two parallel chains), MCMC diagnostics, posterior IRF's and filtered, smoothed, forecasts, etc. In other words, we designed DYNARE sessions that invoke all parallelized functions. Results are shown in Figures \ref{fig:netbook_complete_openclose}-\ref{fig:netbook_partial_openclose}.
+\begin{figure}[p]
+\begin{centering}
+  % Requires \usepackage{graphicx}
+  \epsfxsize=300pt \epsfbox{netbook_complete_openclose.pdf}
+  \caption{Computational Time (s) versus Metropolis length, running all the parallelized functions in DYNARE and the basic parallel implementation (the `Open/Close' strategy). \citep{Lubik2003}.}\label{fig:netbook_complete_openclose}
+\end{centering}
+\end{figure}
+\begin{figure}[p]
+\begin{centering}
+  % Requires \usepackage{graphicx}
+  \epsfxsize=300pt \epsfbox{netbook_partial_openclose.pdf}
+  \caption{Computational Time (s) versus Metropolis length, loading previously performed MH runs and running \emph{only} the parallelized functions after Metropolis \citep{Lubik2003}. Basic parallel implementation (the `Open/Close' strategy).}\label{fig:netbook_partial_openclose}
+\end{centering}
+\end{figure}
+In Figure \ref{fig:netbook_complete_openclose} we show the computational time versus the length of the Metropolis chains in the serial and parallel setting (`Open/Close' strategy). With very short chain length, parallel setting obviously slows down performances of the computations (due to delays in open/close MATLAB sessions and in synchronization), while increasing the chain length, we can get speed-up rates up to 1.41 on this `entry-level' portable computer (single processor and Hyper-threading).
+In order to appreciate the gain of parallelizing all functions invoked after Metropolis, in Figure \ref{fig:netbook_partial_openclose} we show the results of the experiment, but without running Metropolis, i.e. we use the options \verb"load_mh_files = 1" and \verb"mh_replic = 0" DYNARE options (i.e. Metropolis and MCMC diagnostics are not invoked). The parallelization of the functions invoked after Metropolis allows to attain speed-up rates of 1.14 (i.e. time gain of about 12\%). Note that the computational cost of these functions is proportional to the chain length only when the latter is relatively small. In fact, the number of sub-draws taken by \verb"posteriorIRF.m" or \verb"prior_posterior_statistics.m" is proportional to the total number of MH draws up to a maximum threshold of 500 sub-draws (for IRF's) and 1,200 sub-draws (for smoother). This is reflected in the shape of the plots, which attain a plateau when these thresholds are reached.
+%\begin{table}
+%\begin{centering}
+%\begin{tabular}{l|l|l}
+%  % after \\: \hline or \cline{col1-col2} \cline{col3-col4} ...
+%Chain Length & Time Serial (s) & Time Parallel (s) \\ \hline					
+%105 & 85 & 151 \\
+%1005 & 246 & 287 \\
+%5005 & 755 & 599 \\
+%10005 & 1246 & 948 \\
+%15005 & 1647 & 1250 \\
+%20005 & 2068 & 1502 \\
+%25005 & 2366 & 1675 \\
+% \hline
+%\end{tabular}
+%\caption{Trail results for the \cite{Lubik2003} model. Computational Time running all the parallelized functions in DYNARE and the basic parallel implementation (the `Open/Close' strategy).}\label{tab:trail_ls2003}
+%\end{centering}
+%\end{table}
+\begin{figure}
+\begin{centering}
+  % Requires \usepackage{graphicx}
+  \epsfxsize=300pt \epsfbox{netbook_complete_comp.pdf}
+  \caption{Comparison of the `Open/Close' strategy and the `Always-open' strategy. Computational Time (s) versus Metropolis length, running all the parallelized functions in DYNARE \citep{Lubik2003}.}\label{fig:netbook_complete_comp}
+\end{centering}
+\end{figure}
+\begin{figure}
+\begin{centering}
+  % Requires \usepackage{graphicx}
+  \epsfxsize=300pt \epsfbox{netbook_partial_comp.pdf}
+  \caption{Comparison of the `Open/Close' strategy and the `Always-open' strategy. Computational Time (s) versus Metropolis length, running only the parallelized functions after Metropolis \citep{Lubik2003}.}\label{fig:netbook_partial_comp}
+\end{centering}
+\end{figure}
+In Figures \ref{fig:netbook_complete_comp}-\ref{fig:netbook_partial_comp} we plot results of the same type of tests just described, but comparing the `Open/Close' and the `Always-open' strategies. We can see in both graphs that the more sophisticated approach 'Always-open' provides some reduction in computational time. When the entire Bayesian analysis is performed (including Metropolis and MCMC diagnostics, Figure \ref{fig:netbook_complete_comp}) the gain is on average of 5\%, but it can be more than 10\% for short chains. When the Metropolis is not performed, the gain rises on average at about 10\%. As expectable, the gain of the `Always-open' strategy is specially visible when the computational time spent in a single parallel session is not too long if compared to the cost of opening and closing new MATLAB sessions under the `Open/Close' approach.
+
+
+\subsection{Test 4}\label{s:test4}
+Here we increase the dimension of the test model, using the QUEST III model \citep{Ratto_et_al_EconModel2009}, using a more powerful Notebook Samsung Q 45 with an Dual core Processor Intel Centrino. In Figures \ref{fig:quest_complete_openclose}-\ref{fig:quest_partial_openclose} we show the computational gain of the parallel coding with the `Open/Close' strategy. When the Metropolis is included in the analysis (Figure \ref{fig:quest_complete_openclose}), the computational gain increases with the chain length. For 50,000 MH iterations, the speed-up rate is about 1.42 (i.e. a 30\% time gain), but pushing the computation up to 1,000,000 runs provides an almost ideal speed-up of 1.9 (i.e. a gain of about 50\% similar to Figure \ref{fig:test_time_comp}).
+It is also interesting to note that for this medium/large size model, even at very short chain length, the parallel coding is always winning over the serial. Excluding the Metropolis from DYNARE execution (Figure \ref{fig:quest_partial_openclose}), we can see that the speed-up rate of running the posterior analysis in parallel on two cores reaches 1.6 (i.e. 38\% of time gain).
+\begin{figure}[!ht]
+\begin{centering}
+  % Requires \usepackage{graphicx}
+  \epsfxsize=300pt \epsfbox{quest_complete_openclose.pdf}
+  \caption{Computational Time (s) versus Metropolis length, running all the parallelized functions in DYNARE and the basic parallel implementation (the `Open/Close' strategy). \citep{Ratto_et_al_EconModel2009}.}\label{fig:quest_complete_openclose}
+\end{centering}
+\end{figure}
+\begin{figure}[!hb]
+\begin{centering}
+  % Requires \usepackage{graphicx}
+  \epsfxsize=300pt \epsfbox{quest_partial_openclose.pdf}
+  \caption{Computational Time (s) versus Metropolis length, loading previously performed MH runs and running \emph{only} the parallelized functions after Metropolis \citep{Ratto_et_al_EconModel2009}. Basic parallel implementation (the `Open/Close' strategy).}\label{fig:quest_partial_openclose}
+\end{centering}
+\end{figure}
+
+We also checked the efficacy of the `Always-open' approach with respect to the `Open/Close' (Figures \ref{fig:quest_complete_comp} and \ref{fig:quest_partial_comp}). We can see in Figure \ref{fig:quest_complete_comp} that, running the entire Bayesian analysis, no advantage can be appreciated from the more sophisticated `Always-open' approach.
+\begin{figure}[t]
+\begin{centering}
+  % Requires \usepackage{graphicx}
+  \epsfxsize=300pt \epsfbox{quest_complete_comp.pdf}
+  \caption{Comparison of the `Open/Close' strategy and the `Always-open' strategy. Computational Time (s) versus Metropolis length, running all the parallelized functions in DYNARE \citep{Ratto_et_al_EconModel2009}.}\label{fig:quest_complete_comp}
+\end{centering}
+\end{figure}
+\begin{figure}[!ht]
+\begin{centering}
+  % Requires \usepackage{graphicx}
+  \epsfxsize=300pt \epsfbox{quest_partial_comp.pdf}
+  \caption{Comparison of the `Open/Close' strategy and the `Always-open' strategy. Computational Time (s) versus Metropolis length, running only the parallelized functions after Metropolis \citep[QUEST III model][]{Ratto_et_al_EconModel2009}.}\label{fig:quest_partial_comp}
+\end{centering}
+\end{figure}
+
+On the other hand, in Figure \ref{fig:quest_partial_comp}, we can see that the `Always-open' approach still provides a small speed-up rate of about 1.03. These results confirm the previous comment that the gain of the `Always-open' strategy is specially visible when the computational time spent in a single parallel session is not too long, and therefore, the bigger the model size, the less the advantage of this strategy.
+
+
+\section{Conclusions}
+The methodology identified for parallelizing MATLAB codes within DYNARE proved to be effective in reducing the computational time of the most extensive loops. This methodology is suitable for `embarrassingly parallel' codes, requiring only a minimal communication flow between slave and master threads. The parallel DYNARE is built around a few `core' routines, that act as a sort of `parallel paradigm'. Based on those routines, parallelization of expensive loops is made quite simple for DYNARE developers. A basic message passing system is also provided, that allows the master thread to monitor the progress of slave threads. The test model \verb"ls2003.mod" is available in the folder \verb"\tests\parallel" of the DYNARE distribution, that allows running parallel examples.
+
+% ----------------------------------------------------------------
+\bibliographystyle{plainnat}
+%\bibliographystyle{amsplain}
+%\bibliographystyle{alpha}
+\bibliography{marco}
+
+\newpage
+\begin{figure}
+\begin{centering}
+  % Requires \usepackage{graphicx}
+  \epsfxsize=300pt \epsfbox{RWMH_quest1_PriorsAndPosteriors1Comp.pdf}
+  \caption{Prior (grey lines) and posterior density of estimated parameters (black = 100,000 runs; red = 1,000,000 runs) using the RWMH algorithm \citep[QUEST III model][]{Ratto_et_al_EconModel2009}.}\label{fig:quest_RWMH_comp1}
+\end{centering}
+\end{figure}
+\begin{figure}
+\begin{centering}
+  % Requires \usepackage{graphicx}
+  \epsfxsize=300pt \epsfbox{RWMH_quest1_PriorsAndPosteriors2Comp.pdf}
+  \caption{Prior (grey lines) and posterior density of estimated parameters (black = 100,000 runs; red = 1,000,000 runs) using the RWMH algorithm \citep[QUEST III model][]{Ratto_et_al_EconModel2009}.}\label{fig:quest_RWMH_comp2}
+\end{centering}
+\end{figure}
+\begin{figure}
+\begin{centering}
+  % Requires \usepackage{graphicx}
+  \epsfxsize=300pt \epsfbox{RWMH_quest1_PriorsAndPosteriors3Comp.pdf}
+  \caption{Prior (grey lines) and posterior density of estimated parameters (black = 100,000 runs; red = 1,000,000 runs) using the RWMH algorithm \citep[QUEST III model][]{Ratto_et_al_EconModel2009}.}\label{fig:quest_RWMH_comp3}
+\end{centering}
+\end{figure}
+\begin{figure}
+\begin{centering}
+  % Requires \usepackage{graphicx}
+  \epsfxsize=300pt \epsfbox{RWMH_quest1_PriorsAndPosteriors4Comp.pdf}
+  \caption{Prior (grey lines) and posterior density of estimated parameters (black = 100,000 runs; red = 1,000,000 runs) using the RWMH algorithm \citep[QUEST III model][]{Ratto_et_al_EconModel2009}.}\label{fig:quest_RWMH_comp4}
+\end{centering}
+\end{figure}
+\begin{figure}
+\begin{centering}
+  % Requires \usepackage{graphicx}
+  \epsfxsize=300pt \epsfbox{RWMH_quest1_PriorsAndPosteriors5Comp.pdf}
+  \caption{Prior (grey lines) and posterior density of estimated parameters (black = 100,000 runs; red = 1,000,000 runs) using the RWMH algorithm \citep[QUEST III model][]{Ratto_et_al_EconModel2009}.}\label{fig:quest_RWMH_comp5}
+\end{centering}
+\end{figure}
+\begin{figure}
+\begin{centering}
+  % Requires \usepackage{graphicx}
+  \epsfxsize=300pt \epsfbox{RWMH_quest1_PriorsAndPosteriors6Comp.pdf}
+  \caption{Prior (grey lines) and posterior density of estimated parameters (black = 100,000 runs; red = 1,000,000 runs) using the RWMH algorithm \citep[QUEST III model][]{Ratto_et_al_EconModel2009}.}\label{fig:quest_RWMH_comp6}
+\end{centering}
+\end{figure}
+\begin{figure}
+\begin{centering}
+  % Requires \usepackage{graphicx}
+  \epsfxsize=300pt \epsfbox{RWMH_quest1_PriorsAndPosteriors7Comp.pdf}
+  \caption{Prior (grey lines) and posterior density of estimated parameters (black = 100,000 runs; red = 1,000,000 runs) using the RWMH algorithm \citep[QUEST III model][]{Ratto_et_al_EconModel2009}.}\label{fig:quest_RWMH_comp7}
+\end{centering}
+\end{figure}
+
+\clearpage
+\newpage
+
+\appendix
+\section{A tale on parallel computing}
+This is a general introduction to Parallel Computing. Readers can skip it, provided they have a basic knowledge of DYNARE and Computer Programming \citep{GoffeCreel_Grid_2008,Azzini_etal_DYNARE_2007,ParallelDYNARE}.
+There exists an ample scientific literature as well as an enormous quantity of information on the Web, about parallel computing. Sometimes, this amount of information may result ambiguous and confusing in the notation adopted and the description of technologies.  Then main the goal here is therefore to provide a very simple introduction to this subject, leaving the reader to \cite{Brookshear} for a more extensive and clear introduction to computer science.
+
+Modern computer systems (hardware and software) is conceptually identical to the first computer developed by J. Von Neumann. Nevertheless, over time, hardware, software, but most importantly \emph{hardware \& software together} have acquired an ever increasing ability to perform incredibly complex and intensive tasks. Given this complexity, we use to explain the modern computer systems as the ``avenue paradigm'', that we summarize in the next tale.
+
+Nowadays there is a small but lovely town called ``CompuTown''. In CompuTown there are many roads, which are all very similar to each other, and also many gardens. The most important road in CompuTown is the Von Neumann Avenue. The first building in Von Neumann Avenue has three floors (this is a \emph{computer system}: PC, workstation, etc.; see Figure \ref{fig:building} and \cite{Brookshear}). Floors communicate between them only with a single stair. In each floor there are people coming from the same country, with the same language, culture and uses. People living, moving and interacting with each other in the first and second floor are  the \emph{programs} or software agents or, more generally speaking, \emph{algorithms} (see chapters 3, 5, 6 and 7 in \cite{Brookshear}). Examples of the latter are the softwares MATLAB, Octave, and a particular program called the \emph{operating system} (Windows, Linux, Mac OS, etc.).
+
+\begin{figure}
+  % Requires \usepackage{graphicx}
+  \hspace{-15pt}
+  \epsfxsize=400pt \epsfbox{AvenueParadigm.pdf}
+  \caption{The first building in Von Neumann Avenue: a \emph{Computer System}}\label{fig:building}
+\end{figure}
+
+
+People at the \emph{ground floor} are the transistors, the RAM, the CPU, the hard disk, etc. (i.e. the \emph{Computer Architecture}, see chapters 1 and 2 in \citeauthor{Brookshear}).
+People at the \emph{second floor} communicate with people at the \emph{first floor} using the only existing scale (the \emph{pipe}). In these communications, people talk two different languages, and therefore do not understand each other. To remove this problem people define a set of words, fixed and understood by everybody: the \emph{Programming Languages}. More specifically, these languages are called \emph{high-level programming languages} (Java, C/C++, FORTRAN,MATLAB, etc.), because they are related to people living on the upper floors of the building! Sometimes people in the building use also pictures to communicate: \emph{the icons} and  \emph{graphical user interface}.
+
+In a similar way, people at the first floor communicate with people at the ground floor. Not surprisingly, in this case, people use \emph{low-level programming languages} to communicate to each other (assembler, binary code, machine language, etc.). More importantly, however, people at the first floor must also manage and coordinate the requests from people on the second floor to people at the ground floor, since there is no direct communication between ground and second floor. For example they need to translate high-level programming languages into binary code\footnote{The process to transform an high-level programming languages into binary code is called compilation process.}: the \emph{Operating System } performs this task.
+
+Sometimes, people at the second floor try to talk directly with people at the ground floor, via the \emph{system calls}. In the parallelizing software presented in this document, we will use frequently these system calls, to distribute the jobs between the available hardware resources, and to coordinate the overall parallel computational process.
+If only a single person without family lives on the ground floor, such as the porter, we have a CPU single core.
+In this case, the porter can only do one task at a time for the people in first or second floor (the main characteristic of the Von Neumann architecture). For example, in the morning he first collects and sorts the mail for the people in the building, and only after completing this task he can take care of the garden.
+If the porter has to do many jobs, he needs to write in a paper the list of things to do: the \emph{memory} and the \emph{CPU load}. Furthermore, to properly perform its tasks, sometimes the porter has to move some objects trough the passageways at the ground floor (the \emph{System Bus}). If the passageways have standard width, we will have a 32 bits CPU architecture (or bus). If the passageways are very large we will have, for example, a 64 bits CPU architecture (or bus).
+In this scenario, there will be very busy days where many tasks have to be done and many things have to be moved around: the porter will be very tired, although he will be able to `survive'. The most afflicted are always the people at the first floor. Every day they have a lot of new, complex requests from the people at the second floor. These requests must be translated in a correct way and passed to the porter.
+The people at the second floor (the highest floor) ``live in cloud cuckoo land''. These people want everything to be done easily and promptly: the artificial intelligence, robotics, etc.
+The activity in the building increases over time, so the porter decides to get helped in order to reduce the execution time for a single job. There are two ways to do this:
+\begin{itemize}
+\item the municipality of CompuTown interconnects all the buildings in the city using roads, so that the porter can share and distribute the jobs (the \emph{Computer Networks}): if the porters involved have the same nationality and language we have a \emph{Computer Cluster}, otherwise we have a \emph{Grid}. Nevertheless, in both cases, it is necessary to define a correct way in which porters can manage, share and complete a shared job: the \emph{communication protocol} (TCP/IP, internet protocol, etc.);
+\item the building administrator employs an additional porter, producing a \emph{Bi-Processor Computer}. In other case, the porter may get married, producing a \emph{dual-core CPU}. In this case, the wife can help the porter to perform his tasks or even take entirely some jobs for her (for example do the accounting, take care of the apartment, etc.). If the couple has a children, they can have a further little help: the \emph{thread} and then the \emph{Hyper-threading} technology.
+\end{itemize}
+
+Now a problem arises: who should coordinate the activities between the porters (and their family) and between the other buildings? Or, in other words, should we refurbish the first and second floors to take advantage of the innovations on the ground floor and of the new roads in CompuTown?
+First we can lodge new persons at the first floor: the operating systems with a set of network tools and multi-processors support, as well as new people at the second floor with new programming paradigms (MPI, OpenMP, Parrallel DYNARE, etc.). Second, a more complex communication scheme between first and ground floor is necessary, building a new set of stairs. So, for example, if we have two stairs between ground and first floor and two porters, using multi-processors and a new parallel programming paradigm, we can assign jobs to each porter directly and independently, and then coordinate the overall work. In parallel DYNARE we use this kind of `refurbishing' to reduce the computational time and to meet the request of people at the second floor.
+
+Unfortunately, this is only an idealized  scenario, where all the citizens in CompuTown live in peace and cooperate between them. In reality, some building occupants argue with each other and this can cause stopping their job: these kinds of conflicts may be linked to \emph{software and hardware compatibility} (between ground and first floor), or to different \emph{software versions} (between second and first floor). The  building administration or the municipality of CompuTown have to take care of these problems an fix them, to make the computer system operate properly.
+
+This tale (that can be also called \emph{The Programs's Society}) covered in a few pages the fundamental ideas of computer science.
+
+
+\end{document}
+% ----------------------------------------------------------------
diff --git a/examples/Gali_2015.mod b/examples/Gali_2015.mod
index 834b211e5cbadff46d62fb0f9fe21c79e247f994..dd43158cc1f48643372fdd1a50573d7a3936e277 100644
--- a/examples/Gali_2015.mod
+++ b/examples/Gali_2015.mod
@@ -20,7 +20,7 @@
  */
 
 /*
- * Copyright © 2021 Dynare Team
+ * Copyright © 2021-2023 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -147,13 +147,13 @@ end;
 varobs yhat;
 
 % Run prior function to get prior slope of the PC based on independent priors
-hh=figure('Name','Slope of the Phillips Curve');
+hh_fig=figure('Name','Slope of the Phillips Curve');
 prior_function(function='Gali_2015_PC_slope');
 PC_slope_vec=cell2mat(oo_.prior_function_results(:,1));
 
 optimal_bandwidth = mh_optimal_bandwidth(PC_slope_vec,length(PC_slope_vec),0,'gaussian');
 [density(:,1),density(:,2)] = kernel_density_estimate(PC_slope_vec,512,length(PC_slope_vec),optimal_bandwidth,'gaussian');
-figure(hh)
+figure(hh_fig)
 subplot(3,1,1)
 plot(density(:,1),density(:,2));
 title('Prior')
@@ -165,7 +165,7 @@ posterior_function(function='Gali_2015_PC_slope');
 PC_slope_vec=cell2mat(oo_.posterior_function_results(:,1));
 optimal_bandwidth = mh_optimal_bandwidth(PC_slope_vec,length(PC_slope_vec),0,'gaussian');
 [density(:,1),density(:,2)] = kernel_density_estimate(PC_slope_vec,512,length(PC_slope_vec),optimal_bandwidth,'gaussian');
-figure(hh)
+figure(hh_fig)
 subplot(3,1,2)
 plot(density(:,1),density(:,2));
 title('Updated Prior')
@@ -178,7 +178,7 @@ posterior_function(function='Gali_2015_PC_slope');
 PC_slope_vec=cell2mat(oo_.posterior_function_results(:,1));
 optimal_bandwidth = mh_optimal_bandwidth(PC_slope_vec,length(PC_slope_vec),0,'gaussian');
 [density(:,1),density(:,2)] = kernel_density_estimate(PC_slope_vec,512,length(PC_slope_vec),optimal_bandwidth,'gaussian');
-figure(hh)
+figure(hh_fig)
 subplot(3,1,3)
 plot(density(:,1),density(:,2));
 title('Posterior')
diff --git a/matlab/+mom/check_plot.m b/matlab/+mom/check_plot.m
deleted file mode 100644
index 249debd018819c6c103e27214f2258a596b939fd..0000000000000000000000000000000000000000
--- a/matlab/+mom/check_plot.m
+++ /dev/null
@@ -1,185 +0,0 @@
-function check_plot(fun,xparam,SE_vec,options_,M_,estim_params_,Bounds,bayestopt_,varargin)
-%function check_plot(fun,xparam,SE_vec,options_,M_,estim_params_,Bounds,bayestopt_,varargin)
-% Checks the estimated local minimum of the moment's distance objective
-
-
-% Copyright © 2020-2021 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/>.
-
-TeX = options_.TeX;
-if ~isempty(SE_vec)
-    [ s_min, k ] = min(SE_vec);
-end
-
-fval = feval(fun,xparam,varargin{:});
-
-if ~isempty(SE_vec)
-    skipline()
-    disp('LOCAL MINIMUM CHECK')
-    skipline()
-    fprintf('Fval obtained by the minimization routine: %f', fval);
-    skipline()
-    if s_min<eps
-        fprintf('Most negative variance %f for parameter %d (%s = %f)', s_min, k , bayestopt_.name{k}, xparam(k))
-    end
-end
-
-[nbplt,nr,nc,lr,lc,nstar] = pltorg(length(xparam));
-
-if ~exist([M_.dname filesep 'graphs'],'dir')
-    mkdir(M_.dname,'graphs');
-end
-if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
-    fidTeX = fopen([M_.dname, '/graphs/', M_.fname '_MoMCheckPlots.tex'],'w');
-    fprintf(fidTeX,'%% TeX eps-loader file generated by mom.check_plot.m (Dynare).\n');
-    fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
-    fprintf(fidTeX,' \n');
-end
-
-ll = options_.mode_check.neighbourhood_size;
-if isinf(ll)
-    options_.mode_check.symmetric_plots = false;
-end
-
-mcheck = struct('cross',struct(),'emin',struct());
-
-for plt = 1:nbplt
-    if TeX
-        NAMES = [];
-        TeXNAMES = [];
-    end
-    hh = dyn_figure(options_.nodisplay,'Name','Minimum check plots');
-    for k=1:min(nstar,length(xparam)-(plt-1)*nstar)
-        subplot(nr,nc,k)
-        kk = (plt-1)*nstar+k;
-        [name,texname] = get_the_name(kk,TeX,M_,estim_params_,options_);
-        xx = xparam;
-        if xparam(kk)~=0 || ~isinf(Bounds.lb(kk)) || ~isinf(Bounds.lb(kk))
-            l1 = max(Bounds.lb(kk),(1-sign(xparam(kk))*ll)*xparam(kk)); m1 = 0; %lower bound
-            l2 = min(Bounds.ub(kk),(1+sign(xparam(kk))*ll)*xparam(kk)); %upper bound
-        else
-            %size info for 0 parameter is missing, use prior standard
-            %deviation
-            upper_bound=Bounds.lb(kk);
-            if isinf(upper_bound)
-                upper_bound=-1e-6*options_.huge_number;
-            end
-            lower_bound=Bounds.ub(kk);
-            if isinf(lower_bound)
-                lower_bound=-1e-6*options_.huge_number;
-            end
-            l1 = max(lower_bound,-bayestopt_.p2(kk)); m1 = 0; %lower bound
-            l2 = min(upper_bound,bayestopt_.p2(kk)); %upper bound
-        end
-        binding_lower_bound=0;
-        binding_upper_bound=0;
-        if isequal(xparam(kk),Bounds.lb(kk))
-            binding_lower_bound=1;
-            bound_value=Bounds.lb(kk);
-        elseif isequal(xparam(kk),Bounds.ub(kk))
-            binding_upper_bound=1;
-            bound_value=Bounds.ub(kk);
-        end
-        if options_.mode_check.symmetric_plots && ~binding_lower_bound && ~binding_upper_bound
-            if l2<(1+ll)*xparam(kk) %test whether upper bound is too small due to prior binding
-                l1 = xparam(kk) - (l2-xparam(kk)); %adjust lower bound to become closer
-                m1 = 1;
-            end
-            if ~m1 && (l1>(1-ll)*xparam(kk)) && (xparam(kk)+(xparam(kk)-l1)<Bounds.ub(kk)) % if lower bound was truncated and using difference from lower bound does not violate upper bound
-                l2 = xparam(kk) + (xparam(kk)-l1); %set upper bound to same distance as lower bound
-            end
-        end
-        z1 = l1:((xparam(kk)-l1)/(options_.mode_check.number_of_points/2)):xparam(kk);
-        z2 = xparam(kk):((l2-xparam(kk))/(options_.mode_check.number_of_points/2)):l2;
-        z  = union(z1,z2);
-        if options_.mom.penalized_estimator
-            y = zeros(length(z),2);
-            dy=(xx-bayestopt_.p1)'/diag(bayestopt_.p2.^2)*(xx-bayestopt_.p1);
-        else
-            y = zeros(length(z),1);            
-        end
-        for i=1:length(z)
-            xx(kk) = z(i);
-            [fval, info, exit_flag] = feval(fun,xx,varargin{:});
-            if exit_flag
-                y(i,1) = fval;
-            else
-                y(i,1) = NaN;
-                if options_.debug
-                    fprintf('mom.check_plot:: could not solve model for parameter %s at value %4.3f, error code: %u\n',name,z(i),info(1))
-                end
-            end
-            if options_.mom.penalized_estimator
-                prior=(xx-bayestopt_.p1)'/diag(bayestopt_.p2.^2)*(xx-bayestopt_.p1);
-                y(i,2)  = (y(i,1)+prior-dy);
-            end
-        end
-        mcheck.cross = setfield(mcheck.cross, name, [transpose(z), y]);
-        mcheck.emin = setfield(mcheck.emin, name, xparam(kk));
-        fighandle=plot(z,y);
-        hold on
-        yl=get(gca,'ylim');
-        plot( [xparam(kk) xparam(kk)], yl, 'c', 'LineWidth', 1)
-        NaN_index = find(isnan(y(:,1)));
-        zNaN = z(NaN_index);
-        yNaN = yl(1)*ones(size(NaN_index));
-        plot(zNaN,yNaN,'o','MarkerEdgeColor','r','MarkerFaceColor','r','MarkerSize',6);
-        if TeX
-            title(texname,'interpreter','latex')
-        else
-            title(name,'interpreter','none')
-        end
-
-        axis tight
-        if binding_lower_bound || binding_upper_bound
-            xl=get(gca,'xlim');
-            plot( [bound_value bound_value], yl, 'r--', 'LineWidth', 1)
-            xlim([xl(1)-0.5*binding_lower_bound*(xl(2)-xl(1)) xl(2)+0.5*binding_upper_bound*(xl(2)-xl(1))])
-        end
-        hold off
-        drawnow
-    end
-    if options_.mom.penalized_estimator
-        if isoctave
-            axes('outerposition',[0.3 0.93 0.42 0.07],'box','on'),
-        else
-            axes('position',[0.3 0.01 0.42 0.05],'box','on'),
-        end
-        line_color=get(fighandle,'color');
-        plot([0.48 0.68],[0.5 0.5],'color',line_color{2})
-        hold on, plot([0.04 0.24],[0.5 0.5],'color',line_color{1})
-        set(gca,'xlim',[0 1],'ylim',[0 1],'xtick',[],'ytick',[])
-        text(0.25,0.5,'log-post')
-        text(0.69,0.5,'log-lik kernel')
-    end
-    dyn_saveas(hh,[M_.dname, '/graphs/', M_.fname '_MoMCheckPlots' int2str(plt) ],options_.nodisplay,options_.graph_format);
-    if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
-        % TeX eps loader file
-        fprintf(fidTeX,'\\begin{figure}[H]\n');
-        fprintf(fidTeX,'\\centering \n');
-        fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_MoMCheckPlots%s}\n',options_.figures.textwidth*min(k/nc,1),[M_.dname, '/graphs/',M_.fname],int2str(plt));
-        fprintf(fidTeX,'\\caption{Method of Moments check plots.}');
-        fprintf(fidTeX,'\\label{Fig:MoMCheckPlots:%s}\n',int2str(plt));
-        fprintf(fidTeX,'\\end{figure}\n');
-        fprintf(fidTeX,' \n');
-    end
-end
-if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
-    fclose(fidTeX);
-end
-
-save([M_.dname filesep 'graphs' filesep M_.fname '_MoMCheckPlots_data.mat'],'mcheck');
diff --git a/matlab/+mom/default_option_mom_values.m b/matlab/+mom/default_option_mom_values.m
index c0bc017d24f53fdc3990b3833c3b9b3376d2d6e4..9a27c76134200e06da184e80a547ea21b124bf43 100644
--- a/matlab/+mom/default_option_mom_values.m
+++ b/matlab/+mom/default_option_mom_values.m
@@ -29,6 +29,7 @@ function options_mom_ = default_option_mom_values(options_mom_, options_, dname,
 % o user_has_matlab_license
 % o user_has_octave_forge_package
 % -------------------------------------------------------------------------
+
 % Copyright © 2023 Dynare Team
 %
 % This file is part of Dynare.
diff --git a/matlab/+mom/run.m b/matlab/+mom/run.m
index 3f750906e2fc4c75a7166b5593d45b48dec22176..70b0204831023d5ab60c9160cafdbcc5e79c079a 100644
--- a/matlab/+mom/run.m
+++ b/matlab/+mom/run.m
@@ -560,12 +560,16 @@ if strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_meth
     end
     [~, ~, ~,~,~, oo_] = feval(objective_function, xparam1, Bounds, oo_, estim_params_, M_, options_mom_); % compute model moments and oo_.mom.model_moments_params_derivs
     options_mom_.mom.compute_derivs = false; % reset to not compute derivatives in objective function during optimization
-    SE = mom.standard_errors(xparam1, objective_function, Bounds, oo_, estim_params_, M_, options_mom_, Woptflag);
-    % mode check plots
-    if options_mom_.mode_check.status
-        mom.check_plot(objective_function,xparam1,SE,options_mom_,M_,estim_params_,Bounds,bayestopt_,...
-            Bounds, oo_, estim_params_, M_, options_mom_);
-    end
+    [stdh,hessian_xparam1] = mom.standard_errors(xparam1, objective_function, Bounds, oo_, estim_params_, M_, options_mom_, Woptflag);
+end
+
+
+% -------------------------------------------------------------------------
+% checks for mode and hessian at the mode
+% -------------------------------------------------------------------------
+if options_mom_.mode_check.status
+    mode_check(objective_function, xparam1, hessian_xparam1, options_mom_, M_, estim_params_, bayestopt_, Bounds, true,...               
+               Bounds, oo_, estim_params_, M_, options_mom_, bayestopt_);
 end
 
 
@@ -574,7 +578,7 @@ end
 % -------------------------------------------------------------------------
 if strcmp(options_mom_.mom.mom_method,'SMM') || strcmp(options_mom_.mom.mom_method,'GMM')
     % Store results in output structure
-    oo_.mom = display_estimation_results_table(xparam1,SE,M_,options_mom_,estim_params_,bayestopt_,oo_.mom,prior_dist_names,options_mom_.mom.mom_method,lower(options_mom_.mom.mom_method));
+    oo_.mom = display_estimation_results_table(xparam1,stdh,M_,options_mom_,estim_params_,bayestopt_,oo_.mom,prior_dist_names,options_mom_.mom.mom_method,lower(options_mom_.mom.mom_method));
     % J test
     oo_ = mom.Jtest(xparam1, objective_function, Woptflag, oo_, options_mom_, bayestopt_, Bounds, estim_params_, M_, dataset_.nobs);
     % display comparison of model moments and data moments
diff --git a/matlab/+occbin/DSGE_smoother.m b/matlab/+occbin/DSGE_smoother.m
index 656e84a3ce6fbb9e455208997f26e836d9700971..79319b3868e28efd8fd8b9ab57e3d65fa2ec93ae 100644
--- a/matlab/+occbin/DSGE_smoother.m
+++ b/matlab/+occbin/DSGE_smoother.m
@@ -42,7 +42,7 @@ function [alphahat,etahat,epsilonhat,ahat0,SteadyState,trend_coeff,aKK,T0,R0,P,P
 % - alphahat0     [double]  (m*1) array, smoothed endogenous variables in period 0 (a_{0|T})  (decision-rule order)
 % - state_uncertainty0 [double] (K,K,1) array, storing the uncertainty in period 0
 
-% Copyright © 2021 Dynare Team
+% Copyright © 2021-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -401,7 +401,7 @@ if (~is_changed || occbin_smoother_debug) && nargin==12
             if M_.Sigma_e(j,j)
                 j1=j1+1;
                 if mod(j1,9)==1
-                    hfig = dyn_figure(options_.nodisplay,'name','Occbin smoothed shocks');
+                    hh_fig = dyn_figure(options_.nodisplay,'name','Occbin smoothed shocks');
                     ifig=ifig+1;
                     isub=0;
                 end
@@ -427,7 +427,7 @@ if (~is_changed || occbin_smoother_debug) && nargin==12
             if mod(j1,9)~=0 && j==M_.exo_nbr
                 annotation('textbox', [0.1,0,0.35,0.05],'String', 'Linear','Color','Blue','horizontalalignment','center','interpreter','none');
                 annotation('textbox', [0.55,0,0.35,0.05],'String', 'Piecewise','Color','Red','horizontalalignment','center','interpreter','none');
-                dyn_saveas(hfig,[GraphDirectoryName filesep M_.fname,'_smoothedshocks_occbin',int2str(ifig)],options_.nodisplay,options_.graph_format);
+                dyn_saveas(hh_fig,[GraphDirectoryName filesep M_.fname,'_smoothedshocks_occbin',int2str(ifig)],options_.nodisplay,options_.graph_format);
             end
         end
     end
diff --git a/matlab/+occbin/IVF_core.m b/matlab/+occbin/IVF_core.m
index ad943bafbe4514dfddd9db89763bd61339f9f3a5..82cacf2a1d2f48761b93503b7dfc001a2a2c27af 100644
--- a/matlab/+occbin/IVF_core.m
+++ b/matlab/+occbin/IVF_core.m
@@ -65,13 +65,13 @@ opts_simul.piecewise_only = 1;
 filtered_errs=zeros(sample_length,n_obs);
 
 if options_.occbin.likelihood.waitbar
-    hh = dyn_waitbar(0,'IVF_core: Filtering the shocks');
-    set(hh,'Name','IVF_core: Filtering the shocks.');
+    hh_fig = dyn_waitbar(0,'IVF_core: Filtering the shocks');
+    set(hh_fig,'Name','IVF_core: Filtering the shocks.');
 end
 
 for this_period=1:sample_length
     if options_.occbin.likelihood.waitbar
-        dyn_waitbar(this_period/sample_length, hh, sprintf('Period %u of %u', this_period,sample_length));
+        dyn_waitbar(this_period/sample_length, hh_fig, sprintf('Period %u of %u', this_period,sample_length));
     end
     current_obs = obs(this_period,:);
     init_val_old = init_val;
@@ -89,7 +89,7 @@ for this_period=1:sample_length
         filtered_errs=NaN;
         error_code(1) = 304;
         error_code(4) = 1000;
-        if options_.occbin.likelihood.waitbar; dyn_waitbar_close(hh); end
+        if options_.occbin.likelihood.waitbar; dyn_waitbar_close(hh_fig); end
         return
     end
     filtered_errs(this_period,inan)=err_vals_out';
@@ -103,7 +103,7 @@ for this_period=1:sample_length
         error_code(1) = 306;
         error_code(4) = max(abs(err_vals_out))/1000;
         filtered_errs=NaN;
-        if options_.occbin.likelihood.waitbar; dyn_waitbar_close(hh); end
+        if options_.occbin.likelihood.waitbar; dyn_waitbar_close(hh_fig); end
         return
     end
     if max(abs(resids(this_period,:)))>0.001
@@ -112,12 +112,12 @@ for this_period=1:sample_length
         filtered_errs=NaN;
         error_code(1) = 303;
         error_code(4) = max(abs(resids(this_period,:)))*100;
-        if options_.occbin.likelihood.waitbar; dyn_waitbar_close(hh); end
+        if options_.occbin.likelihood.waitbar; dyn_waitbar_close(hh_fig); end
         return
     end
 end
 if options_.occbin.likelihood.waitbar
-    dyn_waitbar_close(hh);
+    dyn_waitbar_close(hh_fig);
 end
 
 end
\ No newline at end of file
diff --git a/matlab/+occbin/graph.m b/matlab/+occbin/graph.m
index 8aafca77a3c504dc61f406f6319380236f68d21c..938d4f636c47ec9fd67824cabff5d0ada3a17202 100644
--- a/matlab/+occbin/graph.m
+++ b/matlab/+occbin/graph.m
@@ -8,7 +8,7 @@ function graph(M_, options_, options_occbin_, oo_, var_list)
 % - oo_                 [structure]     Matlab's structure containing the results
 % - var_list            [char]          list of the variables to plot 
 
-% Copyright © 2021 Dynare Team
+% Copyright © 2021-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -79,7 +79,7 @@ end
 [nbplt,nr,nc,lr,lc,nstar] = pltorg(number_of_plots_to_draw_endo+number_of_plots_to_draw_exo);
 
 for fig = 1:nbplt
-    hh = dyn_figure(options_.nodisplay,'Name',['Occbin simulated paths, figure ' int2str(fig)]);
+    hh_fig = dyn_figure(options_.nodisplay,'Name',['Occbin simulated paths, figure ' int2str(fig)]);
     for plt = 1:nstar
         if fig==nbplt && ~lr==0
             subplot(lr,lc,plt);
@@ -121,7 +121,7 @@ for fig = 1:nbplt
             break
         end
     end
-    dyn_saveas(hh,[M_.dname, '/graphs/'  M_.fname '_occbin_' int2str(fig)],options_.nodisplay,options_.graph_format);
+    dyn_saveas(hh_fig,[M_.dname, '/graphs/'  M_.fname '_occbin_' int2str(fig)],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');
diff --git a/matlab/+occbin/solve_one_constraint.m b/matlab/+occbin/solve_one_constraint.m
index 2f7834df9d589ea14b7c7f497f30411d432eaad2..54ff78cfb2f1e56f0fb087fff25df54f573f7991 100644
--- a/matlab/+occbin/solve_one_constraint.m
+++ b/matlab/+occbin/solve_one_constraint.m
@@ -114,13 +114,13 @@ else
 end
 
 if opts_simul_.waitbar
-    hh = dyn_waitbar(0,'Occbin: Solving the model');
-    set(hh,'Name','Occbin: Solving the model.');
+    hh_fig = dyn_waitbar(0,'Occbin: Solving the model');
+    set(hh_fig,'Name','Occbin: Solving the model.');
 end
 
 for shock_period = 1:n_shocks_periods
     if opts_simul_.waitbar
-        dyn_waitbar(shock_period/n_shocks_periods, hh, sprintf('Period %u of %u', shock_period,n_shocks_periods));
+        dyn_waitbar(shock_period/n_shocks_periods, hh_fig, sprintf('Period %u of %u', shock_period,n_shocks_periods));
     end
     
     regime_change_this_iteration=true;
@@ -312,7 +312,7 @@ for shock_period = 1:n_shocks_periods
                 if periodic_solution
                     disp_verbose(['Max error:' num2str(merr) '.'],opts_simul_.debug)
                 else
-                    if opts_simul_.waitbar; dyn_waitbar_close(hh); end
+                    if opts_simul_.waitbar; dyn_waitbar_close(hh_fig); end
                     error_flag = 310;
                     return
                 end
@@ -324,7 +324,7 @@ for shock_period = 1:n_shocks_periods
                 disp_verbose('Did not converge -- increase maxit.',opts_simul_.debug)
                     error_flag = 311;
                 end
-                if opts_simul_.waitbar; dyn_waitbar_close(hh); end
+                if opts_simul_.waitbar; dyn_waitbar_close(hh_fig); end
                 return
             end
         else
@@ -333,7 +333,7 @@ for shock_period = 1:n_shocks_periods
     end
     if any(error_code_period)
         disp_verbose('Increase nperiods.',opts_simul_.debug)
-        if opts_simul_.waitbar; dyn_waitbar_close(hh); end
+        if opts_simul_.waitbar; dyn_waitbar_close(hh_fig); end
         error_flag = 312;
         return
     end
@@ -363,5 +363,5 @@ if ~opts_simul_.piecewise_only
 end
 
 if opts_simul_.waitbar
-    dyn_waitbar_close(hh); 
+    dyn_waitbar_close(hh_fig); 
 end
diff --git a/matlab/+occbin/solve_two_constraints.m b/matlab/+occbin/solve_two_constraints.m
index eab9c269b6614321f7e9cbd40a36567957834c52..79dadc8696ea4b7e70d2fa2702d77718fb33def9 100644
--- a/matlab/+occbin/solve_two_constraints.m
+++ b/matlab/+occbin/solve_two_constraints.m
@@ -124,13 +124,13 @@ else
 end
 
 if opts_simul_.waitbar
-    hh = dyn_waitbar(0,'Occbin: Solving the model');
-    set(hh,'Name','Occbin: Solving the model.');
+    hh_fig = dyn_waitbar(0,'Occbin: Solving the model');
+    set(hh_fig,'Name','Occbin: Solving the model.');
 end
 
 for shock_period = 1:n_shocks_periods
     if opts_simul_.waitbar
-        dyn_waitbar(shock_period/n_shocks_periods, hh, sprintf('Period %u of %u', shock_period,n_shocks_periods));
+        dyn_waitbar(shock_period/n_shocks_periods, hh_fig, sprintf('Period %u of %u', shock_period,n_shocks_periods));
     end
     regime_change_this_iteration=true;
     nperiods_endogenously_increased = false;
@@ -348,7 +348,7 @@ for shock_period = 1:n_shocks_periods
                     disp_verbose(['Max error:' num2str(min_err) '.'],opts_simul_.debug)
                 else
                     error_flag = 310;
-                    if opts_simul_.waitbar; dyn_waitbar_close(hh); end
+                    if opts_simul_.waitbar; dyn_waitbar_close(hh_fig); end
                     return;
                 end
             else
@@ -359,7 +359,7 @@ for shock_period = 1:n_shocks_periods
                     disp_verbose('Did not converge -- increase maxit.',opts_simul_.debug)
                     error_flag = 311;
                 end
-                if opts_simul_.waitbar; dyn_waitbar_close(hh); end
+                if opts_simul_.waitbar; dyn_waitbar_close(hh_fig); end
                 return;
             end
         else
@@ -371,7 +371,7 @@ for shock_period = 1:n_shocks_periods
     if any(error_code_period)
         disp_verbose('Increase nperiods.',opts_simul_.debug)
         error_flag = 312;
-        if opts_simul_.waitbar; dyn_waitbar_close(hh); end
+        if opts_simul_.waitbar; dyn_waitbar_close(hh_fig); end
         return;
     end
     
@@ -396,5 +396,5 @@ if ~opts_simul_.piecewise_only
 end
 
 if opts_simul_.waitbar
-    dyn_waitbar_close(hh); 
+    dyn_waitbar_close(hh_fig); 
 end
diff --git a/matlab/CutSample.m b/matlab/CutSample.m
index 937ff413e40545fbe99c5fe7f295f82b3828adc2..462aa070a4c3906dd6537c2063f0c3902796cb28 100644
--- a/matlab/CutSample.m
+++ b/matlab/CutSample.m
@@ -1,5 +1,5 @@
-function CutSample(M_, options_, estim_params_)
-% function CutSample(M_, options_, estim_params_)
+function CutSample(M_, options_, dispString)
+% function CutSample(M_, options_, dispString)
 % Takes a subset from metropolis draws by storing the required information
 % like the first MH-file to be loaded and the first line in that file to be
 % loaded into the record structure saved on harddisk into the
@@ -8,7 +8,7 @@ function CutSample(M_, options_, estim_params_)
 % INPUTS
 %   M_               [structure]    Dynare model structure
 %   options_         [structure]    Dynare options structure
-%   estim_params_    [structure]    Parameter structure
+%   dispString       [string]       String to be displayed in the command window
 %
 % OUTPUTS
 %    none
@@ -33,8 +33,6 @@ function CutSample(M_, options_, estim_params_)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
 
-dispString = 'Estimation::mcmc';
-
 % Get the path to the metropolis files.
 MetropolisFolder = CheckPath('metropolis',M_.dname);
 
diff --git a/matlab/DSMH_sampler.m b/matlab/DSMH_sampler.m
index f1724a560864aa5fb50c0fcc351df156a77ed2d1..35621f8ffac54af17c0ce393e9244c02fe3adbe0 100644
--- a/matlab/DSMH_sampler.m
+++ b/matlab/DSMH_sampler.m
@@ -33,7 +33,7 @@ function DSMH_sampler(TargetFun,xparam1,mh_bounds,dataset_,dataset_info,options_
 % Then the comments write here can be used for all the other pairs of
 % parallel functions and also for management functions.
 
-% Copyright © 2006-2022 Dynare Team
+% Copyright © 2006-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -125,7 +125,7 @@ if TeX
     NAMES = [];
     TeXNAMES = [];
 end
-hh = dyn_figure(options_.nodisplay,'Name','Parameters Densities');
+hh_fig = dyn_figure(options_.nodisplay,'Name','Parameters Densities');
 for k=1:npar %min(nstar,npar-(plt-1)*nstar)
     subplot(ceil(sqrt(npar)),floor(sqrt(npar)),k)
     %kk = (plt-1)*nstar+k;
@@ -144,7 +144,7 @@ for k=1:npar %min(nstar,npar-(plt-1)*nstar)
     axis tight
     drawnow
 end
-dyn_saveas(hh,[ M_.fname '_param_density' int2str(plt) ],options_.nodisplay,options_.graph_format);
+dyn_saveas(hh_fig,[ M_.fname '_param_density' int2str(plt) ],options_.nodisplay,options_.graph_format);
 if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
     % TeX eps loader file
     fprintf(fidTeX,'\\begin{figure}[H]\n');
diff --git a/matlab/GetAllPosteriorDraws.m b/matlab/GetAllPosteriorDraws.m
index f8cde8ef29d406f3a3f87f4dcbaaddf560554474..23222b40d7953d1e8084bd3f019be18f132dfa87 100644
--- a/matlab/GetAllPosteriorDraws.m
+++ b/matlab/GetAllPosteriorDraws.m
@@ -1,8 +1,10 @@
-function Draws = GetAllPosteriorDraws(column, FirstMhFile, FirstLine, TotalNumberOfMhFile, NumberOfDraws, nblcks, blck)
-% function Draws = GetAllPosteriorDraws(column, FirstMhFile, FirstLine, TotalNumberOfMhFile, NumberOfDraws, nblcks, blck)
+function Draws = GetAllPosteriorDraws(dname, fname, column, FirstMhFile, FirstLine, TotalNumberOfMhFile, NumberOfDraws, nblcks, blck)
+% function Draws = GetAllPosteriorDraws(dname, fname, column, FirstMhFile, FirstLine, TotalNumberOfMhFile, NumberOfDraws, nblcks, blck)
 % Gets all posterior draws
 %
 % INPUTS
+%    dname:                name of directory with results
+%    fname:                name of mod file
 %    column:               column of desired parameter in draw matrix
 %    FirstMhFile:          first mh file
 %    FirstLine:            first line
@@ -34,20 +36,18 @@ function Draws = GetAllPosteriorDraws(column, FirstMhFile, FirstLine, TotalNumbe
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
 
-global M_ 
-
 iline = FirstLine;
 linee = 1;
-DirectoryName = CheckPath('metropolis',M_.dname);
+DirectoryName = CheckPath('metropolis',dname);
 
-if nblcks>1 && nargin<7
+if nblcks>1 && nargin<9
     Draws = zeros(NumberOfDraws*nblcks,1);
     iline0=iline;
     if column>0
         for blck = 1:nblcks
             iline=iline0;
             for file = FirstMhFile:TotalNumberOfMhFile
-                load([DirectoryName '/'  M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'x2')
+                load([DirectoryName '/'  fname '_mh' int2str(file) '_blck' int2str(blck)],'x2')
                 NumberOfLines = size(x2(iline:end,:),1);
                 Draws(linee:linee+NumberOfLines-1) = x2(iline:end,column);
                 linee = linee+NumberOfLines;
@@ -58,7 +58,7 @@ if nblcks>1 && nargin<7
         for blck = 1:nblcks
             iline=iline0;
             for file = FirstMhFile:TotalNumberOfMhFile
-                load([DirectoryName '/'  M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'logpo2')
+                load([DirectoryName '/'  fname '_mh' int2str(file) '_blck' int2str(blck)],'logpo2')
                 NumberOfLines = size(logpo2(iline:end),1);
                 Draws(linee:linee+NumberOfLines-1) = logpo2(iline:end);
                 linee = linee+NumberOfLines;
@@ -72,7 +72,7 @@ else
     end
     if column>0
         for file = FirstMhFile:TotalNumberOfMhFile
-            load([DirectoryName '/'  M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'x2')
+            load([DirectoryName '/'  fname '_mh' int2str(file) '_blck' int2str(blck)],'x2')
             NumberOfLines = size(x2(iline:end,:),1);
             Draws(linee:linee+NumberOfLines-1) = x2(iline:end,column);
             linee = linee+NumberOfLines;
@@ -80,7 +80,7 @@ else
         end
     else
         for file = FirstMhFile:TotalNumberOfMhFile
-            load([DirectoryName '/'  M_.fname '_mh' int2str(file) '_blck' int2str(blck)],'logpo2')
+            load([DirectoryName '/'  fname '_mh' int2str(file) '_blck' int2str(blck)],'logpo2')
             NumberOfLines = size(logpo2(iline:end,:),1);
             Draws(linee:linee+NumberOfLines-1) = logpo2(iline:end);
             linee = linee+NumberOfLines;
diff --git a/matlab/GetPosteriorParametersStatistics.m b/matlab/GetPosteriorParametersStatistics.m
index b7713b66d7eda050588186906be6860c5b64b879..bd29b1f61a464dbc3b34e2572801d5608f5accf5 100644
--- a/matlab/GetPosteriorParametersStatistics.m
+++ b/matlab/GetPosteriorParametersStatistics.m
@@ -46,7 +46,7 @@ ncn     = estim_params_.ncn;
 np      = estim_params_.np ;
 
 MetropolisFolder = CheckPath('metropolis',M_.dname);
-OutputFolder = CheckPath('Output',M_.dname);
+latexFolder = CheckPath('latex',M_.dname);
 FileName = M_.fname;
 
 record=load_last_mh_history_file(MetropolisFolder,FileName);
@@ -86,7 +86,7 @@ end
 if np
     type = 'parameters';
     if TeX
-        fid = TeXBegin(OutputFolder, M_.fname, 1, type);
+        fid = TeXBegin(latexFolder, M_.fname, 1, type);
     end
     skipline()
     disp(type)
@@ -94,7 +94,7 @@ if np
     ip = nvx+nvn+ncx+ncn+1;
     for i=1:np
         if options_.mh_replic || (options_.load_mh_file && ~options_.load_results_after_load_mh)
-            Draws = GetAllPosteriorDraws(ip, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, mh_nblck);
+            Draws = GetAllPosteriorDraws(M_.dname, M_.fname, ip, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, mh_nblck);
             [post_mean, post_median, post_var, hpd_interval, post_deciles, density] = posterior_moments(Draws, 1, options_.mh_conf_sig);
             name = bayestopt_.name{ip};
             oo_ = Filloo(oo_, name, type, post_mean, hpd_interval, post_median, post_var, post_deciles, density);
@@ -103,7 +103,7 @@ if np
                 name = bayestopt_.name{ip};
                 [post_mean, hpd_interval, post_var] = Extractoo(oo_, name, type);
             catch
-                Draws = GetAllPosteriorDraws(ip, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, mh_nblck);
+                Draws = GetAllPosteriorDraws(M_.dname, M_.fname, ip, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, mh_nblck);
                 [post_mean, post_median, post_var, hpd_interval, post_deciles, density] = posterior_moments(Draws, 1, options_.mh_conf_sig);
                 name = bayestopt_.name{ip};
                 oo_ = Filloo(oo_, name, type, post_mean, hpd_interval, post_median, post_var, post_deciles, density);
@@ -129,7 +129,7 @@ end
 if nvx
     type = 'shocks_std';
     if TeX
-        fid = TeXBegin(OutputFolder, FileName,2, 'standard deviation of structural shocks');
+        fid = TeXBegin(latexFolder, FileName,2, 'standard deviation of structural shocks');
     end
     ip = 1;
     skipline()
@@ -137,7 +137,7 @@ if nvx
     disp(tit2)
     for i=1:nvx
         if options_.mh_replic || (options_.load_mh_file && ~options_.load_results_after_load_mh)
-            Draws = GetAllPosteriorDraws(ip, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, mh_nblck);
+            Draws = GetAllPosteriorDraws(M_.dname, M_.fname, ip, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, mh_nblck);
             [post_mean, post_median, post_var, hpd_interval, post_deciles, density] = posterior_moments(Draws, 1, options_.mh_conf_sig);
             k = estim_params_.var_exo(i,1);
             name = M_.exo_names{k};
@@ -149,7 +149,7 @@ if nvx
                 name = M_.exo_names{k};
                 [post_mean, hpd_interval, post_var] = Extractoo(oo_, name, type);
             catch
-                Draws = GetAllPosteriorDraws(ip, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, mh_nblck);
+                Draws = GetAllPosteriorDraws(M_.dname, M_.fname, ip, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, mh_nblck);
                 [post_mean, post_median, post_var, hpd_interval, post_deciles, density] = ...
                     posterior_moments(Draws, 1, options_.mh_conf_sig);
                 k = estim_params_.var_exo(i,1);
@@ -173,7 +173,7 @@ end
 if nvn
     type = 'measurement_errors_std';
     if TeX
-        fid = TeXBegin(OutputFolder, FileName, 3, 'standard deviation of measurement errors');
+        fid = TeXBegin(latexFolder, FileName, 3, 'standard deviation of measurement errors');
     end
     skipline()
     disp('standard deviation of measurement errors')
@@ -181,7 +181,7 @@ if nvn
     ip = nvx+1;
     for i=1:nvn
         if options_.mh_replic || (options_.load_mh_file && ~options_.load_results_after_load_mh)
-            Draws = GetAllPosteriorDraws(ip, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, mh_nblck);
+            Draws = GetAllPosteriorDraws(M_.dname, M_.fname, ip, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, mh_nblck);
             [post_mean, post_median, post_var, hpd_interval, post_deciles, density] = posterior_moments(Draws, 1, options_.mh_conf_sig);
             name = options_.varobs{estim_params_.nvn_observable_correspondence(i,1)};
             oo_ = Filloo(oo_, name, type, post_mean, hpd_interval, post_median, post_var, post_deciles, density);
@@ -190,7 +190,7 @@ if nvn
                 name = options_.varobs{estim_params_.nvn_observable_correspondence(i,1)};
                 [post_mean,hpd_interval,post_var] = Extractoo(oo_,name,type);
             catch
-                Draws = GetAllPosteriorDraws(ip,FirstMhFile,FirstLine,TotalNumberOfMhFiles,NumberOfDraws, mh_nblck);
+                Draws = GetAllPosteriorDraws(M_.dname, M_.fname, ip,FirstMhFile,FirstLine,TotalNumberOfMhFiles,NumberOfDraws, mh_nblck);
                 [post_mean, post_median, post_var, hpd_interval, post_deciles, density] = posterior_moments(Draws,1,options_.mh_conf_sig);
                 name = options_.varobs{estim_params_.nvn_observable_correspondence(i,1)};
                 oo_ = Filloo(oo_,name,type,post_mean,hpd_interval,post_median,post_var,post_deciles,density);
@@ -212,7 +212,7 @@ end
 if ncx
     type = 'shocks_corr';
     if TeX
-        fid = TeXBegin(OutputFolder,FileName,4,'correlation of structural shocks');
+        fid = TeXBegin(latexFolder,FileName,4,'correlation of structural shocks');
     end
     skipline()
     disp('correlation of shocks')
@@ -220,7 +220,7 @@ if ncx
     ip = nvx+nvn+1;
     for i=1:ncx
         if options_.mh_replic || (options_.load_mh_file && ~options_.load_results_after_load_mh)
-            Draws = GetAllPosteriorDraws(ip, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, mh_nblck);
+            Draws = GetAllPosteriorDraws(M_.dname, M_.fname, ip, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, mh_nblck);
             [post_mean, post_median, post_var, hpd_interval, post_deciles, density] = posterior_moments(Draws,1,options_.mh_conf_sig);
             k1 = estim_params_.corrx(i,1);
             k2 = estim_params_.corrx(i,2);
@@ -237,7 +237,7 @@ if ncx
                 NAME = sprintf('%s_%s', M_.exo_names{k1}, M_.exo_names{k2});
                 [post_mean,hpd_interval,post_var] = Extractoo(oo_, NAME, type);
             catch
-                Draws = GetAllPosteriorDraws(ip, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, mh_nblck);
+                Draws = GetAllPosteriorDraws(M_.dname, M_.fname, ip, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, mh_nblck);
                 [post_mean, post_median, post_var, hpd_interval, post_deciles, density] = posterior_moments(Draws, 1, options_.mh_conf_sig);
                 k1 = estim_params_.corrx(i,1);
                 k2 = estim_params_.corrx(i,2);
@@ -262,7 +262,7 @@ end
 if ncn
     type = 'measurement_errors_corr';
     if TeX
-        fid = TeXBegin(OutputFolder, FileName, 5, 'correlation of measurement errors');
+        fid = TeXBegin(latexFolder, FileName, 5, 'correlation of measurement errors');
     end
     skipline()
     disp('correlation of measurement errors')
@@ -270,7 +270,7 @@ if ncn
     ip = nvx+nvn+ncx+1;
     for i=1:ncn
         if options_.mh_replic || (options_.load_mh_file && ~options_.load_results_after_load_mh)
-            Draws = GetAllPosteriorDraws(ip,FirstMhFile,FirstLine,TotalNumberOfMhFiles,NumberOfDraws, mh_nblck);
+            Draws = GetAllPosteriorDraws(M_.dname, M_.fname, ip,FirstMhFile,FirstLine,TotalNumberOfMhFiles,NumberOfDraws, mh_nblck);
             [post_mean, post_median, post_var, hpd_interval, post_deciles, density] = posterior_moments(Draws, 1, options_.mh_conf_sig);
             k1 = estim_params_.corrn(i,1);
             k2 = estim_params_.corrn(i,2);
@@ -285,7 +285,7 @@ if ncn
                 NAME = sprintf('%s_%s', M_.endo_names{k1}, M_.endo_names{k2});
                 [post_mean,hpd_interval,post_var] = Extractoo(oo_, NAME, type);
             catch
-                Draws = GetAllPosteriorDraws(ip, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, mh_nblck);
+                Draws = GetAllPosteriorDraws(M_.dname, M_.fname, ip, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, mh_nblck);
                 [post_mean, post_median, post_var, hpd_interval, post_deciles, density] = posterior_moments(Draws, 1, options_.mh_conf_sig);
                 k1 = estim_params_.corrn(i,1);
                 k2 = estim_params_.corrn(i,2);
diff --git a/matlab/Herbst_Schorfheide_sampler.m b/matlab/Herbst_Schorfheide_sampler.m
index b73b8f87b6868086d7a02b3fcb7268e3a6c6924a..8db32815fe492f806496ea9c02935e7546a3ffd4 100644
--- a/matlab/Herbst_Schorfheide_sampler.m
+++ b/matlab/Herbst_Schorfheide_sampler.m
@@ -33,7 +33,7 @@ function Herbst_Schorfheide_sampler(TargetFun,xparam1,mh_bounds,dataset_,dataset
 % Then the comments write here can be used for all the other pairs of
 % parallel functions and also for management functions.
 
-% Copyright © 2006-2022 Dynare Team
+% Copyright © 2006-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -152,7 +152,7 @@ if TeX
     NAMES = [];
     TeXNAMES = [];
 end
-hh = dyn_figure(options_.nodisplay,'Name','Parameters Densities');
+hh_fig = dyn_figure(options_.nodisplay,'Name','Parameters Densities');
 for k=1:npar %min(nstar,npar-(plt-1)*nstar)
     subplot(ceil(sqrt(npar)),floor(sqrt(npar)),k)
     %kk = (plt-1)*nstar+k;
@@ -171,7 +171,7 @@ for k=1:npar %min(nstar,npar-(plt-1)*nstar)
     axis tight
     drawnow
 end
-dyn_saveas(hh,[ M_.fname '_param_density' int2str(plt) ],options_.nodisplay,options_.graph_format);
+dyn_saveas(hh_fig,[ M_.fname '_param_density' int2str(plt) ],options_.nodisplay,options_.graph_format);
 if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
     % TeX eps loader file
     fprintf(fidTeX,'\\begin{figure}[H]\n');
diff --git a/matlab/MakeAllFigures.m b/matlab/MakeAllFigures.m
index 2e18af357c5f76a6e13c672b0b303411b872b963..e14f86579517dc6d690e0c6c5b44c85dc2aa8bcc 100644
--- a/matlab/MakeAllFigures.m
+++ b/matlab/MakeAllFigures.m
@@ -1,6 +1,6 @@
 function MakeAllFigures(NumberOfPlots,Caption,FigureProperties,Info)
 
-% Copyright © 2005-2017 Dynare Team
+% Copyright © 2005-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -97,45 +97,45 @@ for plt = 1:NumberOfPlots
     subplot(nr,nc,plt)
     hold on
     for curve = 1:NumberOfCurves
-        hh = plot(x{curve},y{curve});
+        hh_fig = plot(x{curve},y{curve});
         if strcmpi(PltType{curve},'PriorDensity')
-            set(hh,'Color',[0.7 0.7 0.7],'LineStyle','-','LineWidth',2)
+            set(hh_fig,'Color',[0.7 0.7 0.7],'LineStyle','-','LineWidth',2)
             %
             %
         elseif strcmpi(PltType{curve},'DensityEstimate')
-            set(hh,'Color','k','LineStyle','-','LineWidth',2)
+            set(hh_fig,'Color','k','LineStyle','-','LineWidth',2)
             %
             %
         elseif strcmpi(PltType{curve},'ModeEstimate')
-            set(hh,'Color','g','LineStyle','--','LineWidth',2)
+            set(hh_fig,'Color','g','LineStyle','--','LineWidth',2)
             %
             %
         elseif strcmpi(PltType{curve},'SmoothVariable')
-            set(hh,'Color','k','LineStyle','-','LineWidth',2)
+            set(hh_fig,'Color','k','LineStyle','-','LineWidth',2)
             %
             %
         elseif strcmpi(PltType{curve},'Deciles')
-            set(hh,'Color','g','LineStyle','-','LineWidth',1)
+            set(hh_fig,'Color','g','LineStyle','-','LineWidth',1)
             %
             %
         elseif strcmpi(PltType{curve},'Forecasts')
-            set(hh,'Color','','LineStyle','-','LineWidth',2)
+            set(hh_fig,'Color','','LineStyle','-','LineWidth',2)
             %
             %
         elseif strcmpi(PltType{curve},'ForecastsHPD')
-            set(hh,'Color','k','LineStyle','-','LineWidth',1)
+            set(hh_fig,'Color','k','LineStyle','-','LineWidth',1)
             %
             %
         elseif strcmpi(PltType{curve},'ForecastsDeciles')
-            set(hh,'Color','g','LineStyle','-','LineWidth',1)
+            set(hh_fig,'Color','g','LineStyle','-','LineWidth',1)
             %
             %
         elseif strcmpi(PltType{curve},'DiagnosticWithin')
-            set(hh,'Color','b','LineStyle','-','LineWidth',2)
+            set(hh_fig,'Color','b','LineStyle','-','LineWidth',2)
             %
             %
         elseif strcmpi(PltType{curve},'DiagnosticPooled')
-            set(hh,'Color','r','LineStyle','-','LineWidth',2)
+            set(hh_fig,'Color','r','LineStyle','-','LineWidth',2)
             %
             %
         end
diff --git a/matlab/PlotPosteriorDistributions.m b/matlab/PlotPosteriorDistributions.m
index 5cb0a2d7bba77601a19f4d66917c6292a006d1ba..6a5cec13d0b93f737cd78d674bbebe7168a94a20 100644
--- a/matlab/PlotPosteriorDistributions.m
+++ b/matlab/PlotPosteriorDistributions.m
@@ -4,19 +4,19 @@ function oo_ = PlotPosteriorDistributions(estim_params_, M_, options_, bayestopt
 % plots posterior distributions
 %
 % INPUTS
-%    estim_params_   [structure]
-%    M_              [structure]
-%    options_        [structure]
-%    bayestopt_      [structure]
-%    oo_             [structure]
+%    estim_params_    [structure]  information on estimated paramters
+%    M_               [structure]  information on model
+%    options_         [structure]  information on options
+%    bayestopt_       [structure]  information on priors
+%    oo_              [structure]  results
 %
 % OUTPUTS
-%    oo_             [structure]
+%    oo_             [structure]   updated results
 %
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright © 2005-2018 Dynare Team
+% Copyright © 2005-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -32,8 +32,8 @@ function oo_ = PlotPosteriorDistributions(estim_params_, M_, options_, bayestopt
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
-
-OutputDirectoryName = CheckPath('Output',M_.dname);
+latexDirectoryName = CheckPath('latex',M_.dname);
+graphDirectoryName = CheckPath('graphs',M_.dname);
 
 TeX     = options_.TeX;
 nblck   = options_.mh_nblck;
@@ -50,7 +50,7 @@ nn = sqrt(MaxNumberOfPlotPerFigure);
 figurename = 'Priors and posteriors';
 
 if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
-    fidTeX = fopen([OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors.tex'],'w');
+    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');
@@ -63,7 +63,7 @@ for i=1:npar
     subplotnum = subplotnum+1;
     if subplotnum == 1
         figunumber = figunumber+1;
-        hfig=dyn_figure(options_.nodisplay, 'Name', figurename);
+        hh_fig=dyn_figure(options_.nodisplay, 'Name', figurename);
     end
     [nam,texnam] = get_the_name(i, TeX, M_, estim_params_, options_);
     [x2, f2, abscissa, dens, binf2, bsup2] = draw_prior_density(i, bayestopt_);
@@ -128,8 +128,8 @@ for i=1:npar
     borneinf = min(binf1, binf2);
     bornesup = max(bsup1, bsup2);
     subplot(nn, nn, subplotnum)
-    hh = plot(x2, f2, '-k', 'linewidth', 2);
-    set(hh, 'color', [0.7 0.7 0.7]);
+    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 ~options_.mh_posterior_mode_estimation
@@ -145,12 +145,12 @@ for i=1:npar
     hold off
     drawnow
     if subplotnum == MaxNumberOfPlotPerFigure || i == npar
-        dyn_saveas(hfig,[OutputDirectoryName '/' M_.fname '_PriorsAndPosteriors' int2str(figunumber)], options_.nodisplay, options_.graph_format);
+        dyn_saveas(hh_fig,[graphDirectoryName filesep M_.fname '_PriorsAndPosteriors' int2str(figunumber)], options_.nodisplay, options_.graph_format);
         if 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), OutputDirectoryName, M_.fname, int2str(figunumber));
+                    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');
diff --git a/matlab/PosteriorIRF.m b/matlab/PosteriorIRF.m
index b5356fd7b18c7768f8910404f9ecf28ad6d06740..61f7361d973116943fd5eb7cdf196ede38fc71a3 100644
--- a/matlab/PosteriorIRF.m
+++ b/matlab/PosteriorIRF.m
@@ -1,9 +1,10 @@
-function PosteriorIRF(type)
+function PosteriorIRF(type,dispString)
 % Builds posterior IRFs after the MH algorithm.
 %
 % INPUTS
 %   o type       [char]     string specifying the joint density of the
 %                           deep parameters ('prior','posterior').
+%   o dispString [char]     string to display in the console.
 %
 % OUTPUTS
 %   None                    (oo_ and plots).
@@ -36,8 +37,6 @@ function PosteriorIRF(type)
 
 global options_ estim_params_ oo_ M_ bayestopt_ dataset_ dataset_info
 
-dispString = 'Estimation::mcmc';
-
 % Set the number of periods
 if isempty(options_.irf) || ~options_.irf
     options_.irf = 40;
diff --git a/matlab/PosteriorIRF_core2.m b/matlab/PosteriorIRF_core2.m
index f9fa28ab9426d0f80130ba929865a80c7c692a09..73ea4c493ecb330552ae884d2c5e82e19473b4f0 100644
--- a/matlab/PosteriorIRF_core2.m
+++ b/matlab/PosteriorIRF_core2.m
@@ -30,7 +30,7 @@ function myoutput=PosteriorIRF_core2(myinputs,fpar,npar,whoiam,ThisMatlab)
 % SPECIAL REQUIREMENTS.
 %   None.
 %
-% Copyright © 2006-2018 Dynare Team
+% Copyright © 2006-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -103,12 +103,12 @@ for i=fpar:npar
         if max(abs(MeanIRF(:,j,i))) >= options_.impulse_responses.plot_threshold
             subplotnum = subplotnum+1;
             if subplotnum == 1 && options_.relative_irf
-                hh = dyn_figure(options_.nodisplay,'Name',['Relative response to orthogonalized shock to ' tit{i}]);
+                hh_fig = dyn_figure(options_.nodisplay,'Name',['Relative response to orthogonalized shock to ' tit{i}]);
             elseif subplotnum == 1 && ~options_.relative_irf
-                hh = dyn_figure(options_.nodisplay,'Name',['Orthogonalized shock to ' tit{i}]);
+                hh_fig = dyn_figure(options_.nodisplay,'Name',['Orthogonalized shock to ' tit{i}]);
             end
 
-            set(0,'CurrentFigure',hh)
+            set(0,'CurrentFigure',hh_fig)
             subplot(nn,nn,subplotnum);
             if ~MAX_nirfs_dsgevar
                 if ~isnan(min(HPDIRF(:,1,j,i)))
@@ -155,7 +155,7 @@ for i=fpar:npar
 
         if subplotnum == MaxNumberOfPlotPerFigure || (j == nvar  && subplotnum> 0)
             figunumber = figunumber+1;
-            dyn_saveas(hh,[DirectoryName '/'  M_.fname '_Bayesian_IRF_' tit{i} '_' int2str(figunumber)],options_.nodisplay,options_.graph_format);
+            dyn_saveas(hh_fig,[DirectoryName '/'  M_.fname '_Bayesian_IRF_' tit{i} '_' int2str(figunumber)],options_.nodisplay,options_.graph_format);
             if RemoteFlag==1
                 OutputFileName = [OutputFileName; {[DirectoryName,filesep], [M_.fname '_Bayesian_IRF_' deblank(tit(i,:)) '_' int2str(figunumber) '.*']}];
             end
diff --git a/matlab/UnivariateSpectralDensity.m b/matlab/UnivariateSpectralDensity.m
index d829ba3f30d94207dceac2cc4b2bb58cfdc13b60..862dde5e612b3b2f67bac80688c330d26b2828f8 100644
--- a/matlab/UnivariateSpectralDensity.m
+++ b/matlab/UnivariateSpectralDensity.m
@@ -19,7 +19,7 @@ function [oo_] = UnivariateSpectralDensity(M_,oo_,options_,var_list)
 
 % Adapted from th_autocovariances.m.
 
-% Copyright © 2006-2020 Dynare Team
+% Copyright © 2006-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -155,12 +155,12 @@ if ~options_.nograph
     end
 
     for i= 1:nvar
-        hh = dyn_figure(options_.nodisplay,'Name',['Spectral Density of ' M_.endo_names{ivar(i)} '.']);
+        hh_fig = dyn_figure(options_.nodisplay,'Name',['Spectral Density of ' M_.endo_names{ivar(i)} '.']);
         plot(freqs,f(i,:),'-k','linewidth',2)
         xlabel('0 \leq \omega \leq \pi')
         ylabel('f(\omega)')
         box on
         axis tight
-        dyn_saveas(hh,[M_.dname ,filesep,'graphs', filesep, 'SpectralDensity_' M_.endo_names{ivar(i)}],options_.nodisplay,options_.graph_format)
+        dyn_saveas(hh_fig,[M_.dname ,filesep,'graphs', filesep, 'SpectralDensity_' M_.endo_names{ivar(i)}],options_.nodisplay,options_.graph_format)
     end
 end
diff --git a/matlab/calibrate_mh_scale_parameter.m b/matlab/calibrate_mh_scale_parameter.m
index af940fb33318cb52014c2941d7bf0163a92e005b..0a5d0a25368c57fede85d7b20cf539c98329732f 100644
--- a/matlab/calibrate_mh_scale_parameter.m
+++ b/matlab/calibrate_mh_scale_parameter.m
@@ -20,7 +20,7 @@ function Scale = calibrate_mh_scale_parameter(ObjectiveFunction, CovarianceMatri
 
 
 
-% Copyright © 2020-2021 Dynare Team
+% Copyright © 2020-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -38,8 +38,8 @@ function Scale = calibrate_mh_scale_parameter(ObjectiveFunction, CovarianceMatri
 % along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
 
 % Fire up the wait bar
-hh = dyn_waitbar(0,'Tuning of the scale parameter...');
-set(hh,'Name','Tuning of the scale parameter.');
+hh_fig = dyn_waitbar(0,'Tuning of the scale parameter...');
+set(hh_fig,'Name','Tuning of the scale parameter.');
 
 % Intilialize various counters.
 j = 1; jj  = 1; isux = 0; jsux = 0; i = 0;
@@ -100,7 +100,7 @@ while j<=options.maxiter
     prtfrc = j/options.maxiter;
     % Update the waitbar
     if ~mod(j, 10)
-        dyn_waitbar(prtfrc, hh, sprintf('Acceptance ratio [during last %u]: %f [%f]', options.stepsize, isux/j, jsux/jj));
+        dyn_waitbar(prtfrc, hh_fig, sprintf('Acceptance ratio [during last %u]: %f [%f]', options.stepsize, isux/j, jsux/jj));
     end
     % Adjust the value of the scale parameter.
     if ~mod(j, options.stepsize)
@@ -135,4 +135,4 @@ while j<=options.maxiter
     jj = jj + 1;
 end
 
-dyn_waitbar_close(hh);
\ No newline at end of file
+dyn_waitbar_close(hh_fig);
\ No newline at end of file
diff --git a/matlab/check_posterior_sampler_options.m b/matlab/check_posterior_sampler_options.m
index d00d1913dca838866df440e9775452c6f0bf7153..7848cf6ce563fac6264dfe359195b9f0719b44c1 100644
--- a/matlab/check_posterior_sampler_options.m
+++ b/matlab/check_posterior_sampler_options.m
@@ -1,5 +1,5 @@
-function [posterior_sampler_options, options_, bayestopt_] = check_posterior_sampler_options(posterior_sampler_options, fname, dname, options_, bounds, bayestopt_)
-% function [posterior_sampler_options, options_, bayestopt_] = check_posterior_sampler_options(posterior_sampler_options, fname, dname, options_, bounds, bayestopt_)
+function [posterior_sampler_options, options_, bayestopt_] = check_posterior_sampler_options(posterior_sampler_options, fname, dname, options_, bounds, bayestopt_,outputFolderName)
+% function [posterior_sampler_options, options_, bayestopt_] = check_posterior_sampler_options(posterior_sampler_options, fname, dname, options_, bounds, bayestopt_,outputFolderName)
 % initialization of posterior samplers
 %
 % INPUTS
@@ -14,6 +14,7 @@ function [posterior_sampler_options, options_, bayestopt_] = check_posterior_sam
 %   posterior_sampler_options:       checked posterior sampler options
 %   options_:       structure storing the options
 %   bayestopt_:     structure storing information about priors
+%   outputFolderName: string of folder to store mat files
 %
 % SPECIAL REQUIREMENTS
 %   none
@@ -35,6 +36,9 @@ function [posterior_sampler_options, options_, bayestopt_] = check_posterior_sam
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
 
+if nargin < 7
+    outputFolderName = 'Output';
+end
 
 init=0;
 if isempty(posterior_sampler_options)
@@ -392,7 +396,7 @@ if ~strcmp(posterior_sampler_options.posterior_sampling_method,'slice')
 end
 
 if options_.load_mh_file && posterior_sampler_options.use_mh_covariance_matrix
-    [~, invhess] = compute_mh_covariance_matrix(bayestopt_,fname,dname);
+    [~, invhess] = compute_mh_covariance_matrix(bayestopt_,fname,dname,outputFolderName);
     posterior_sampler_options.invhess = invhess;
 end
 
diff --git a/matlab/compute_mh_covariance_matrix.m b/matlab/compute_mh_covariance_matrix.m
index 3e1abab1568f98e339f6ca934778f5da817dbf7d..e7f0c6a5955d4bf6b259a7d3d41867c8974f32e0 100644
--- a/matlab/compute_mh_covariance_matrix.m
+++ b/matlab/compute_mh_covariance_matrix.m
@@ -1,5 +1,5 @@
-function [posterior_mean,posterior_covariance,posterior_mode,posterior_kernel_at_the_mode] = compute_mh_covariance_matrix(bayestopt_,fname,dname)
-% function [posterior_mean,posterior_covariance,posterior_mode,posterior_kernel_at_the_mode] = compute_mh_covariance_matrix(bayestopt_,fname,dname)
+function [posterior_mean,posterior_covariance,posterior_mode,posterior_kernel_at_the_mode] = compute_mh_covariance_matrix(bayestopt_,fname,dname,outputFolderName)
+% function [posterior_mean,posterior_covariance,posterior_mode,posterior_kernel_at_the_mode] = compute_mh_covariance_matrix(bayestopt_,fname,dname,outputFolderName)
 % Estimation of the posterior covariance matrix, posterior mean, posterior mode and evaluation of the posterior kernel at the
 % estimated mode, using the draws from a metropolis-hastings. The estimated posterior mode and covariance matrix are saved in
 % a file <fname>_mh_mode.mat.
@@ -8,6 +8,7 @@ function [posterior_mean,posterior_covariance,posterior_mode,posterior_kernel_at
 %   o  bayestopt_                    [struct]  characterizing priors
 %   o  fname                         [string]  name of model
 %   o  dname                         [string]  name of directory with metropolis folder
+%   o  outputFolderName              [string]  name of directory to store results
 %
 % OUTPUTS
 %   o  posterior_mean                [double]  (n*1) vector, posterior expectation of the parameters.
@@ -34,6 +35,9 @@ function [posterior_mean,posterior_covariance,posterior_mode,posterior_kernel_at
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
+if nargin < 4
+    outputFolderName = 'Output';
+end
 MetropolisFolder = CheckPath('metropolis',dname);
 BaseName = [MetropolisFolder filesep fname];
 
@@ -70,4 +74,4 @@ hh = inv(posterior_covariance);
 fval = posterior_kernel_at_the_mode;
 parameter_names = bayestopt_.name;
 
-save([dname filesep 'Output' filesep fname '_mh_mode.mat'],'xparam1','hh','fval','parameter_names');
\ No newline at end of file
+save([dname filesep outputFolderName filesep fname '_mh_mode.mat'],'xparam1','hh','fval','parameter_names');
\ No newline at end of file
diff --git a/matlab/convergence_diagnostics/mcmc_diagnostics.m b/matlab/convergence_diagnostics/mcmc_diagnostics.m
index 1a3bc0cbbf3b9a886feba7804a7356207ca726a4..518172c49cfc6e285e92a517978f6be3c238f2fc 100644
--- a/matlab/convergence_diagnostics/mcmc_diagnostics.m
+++ b/matlab/convergence_diagnostics/mcmc_diagnostics.m
@@ -33,8 +33,8 @@ function oo_ = mcmc_diagnostics(options_, estim_params_, M_, oo_)
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
-
-OutputFolder = CheckPath('Output',M_.dname);
+graphFolder = CheckPath('graphs',M_.dname);
+latexFolder = CheckPath('latex',M_.dname);
 MetropolisFolder = CheckPath('metropolis',M_.dname);
 ModelName = M_.fname;
 
@@ -79,7 +79,7 @@ for jj = 1:npar
         par_name_temp = get_the_name(jj, options_.TeX, M_, estim_params_, options_);
         param_name = vertcat(param_name, par_name_temp);
     end
-    Draws = GetAllPosteriorDraws(jj, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, nblck);
+    Draws = GetAllPosteriorDraws(M_.dname, M_.fname, jj, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, nblck);
     Draws = reshape(Draws, [NumberOfDraws nblck]);
     Nc = min(1000, NumberOfDraws/2);
     for ll = 1:nblck
@@ -191,11 +191,11 @@ if nblck == 1 % Brooks and Gelman tests need more than one block
         Raftery_Lewis_q=options_.convergence.rafterylewis.qrs(1);
         Raftery_Lewis_r=options_.convergence.rafterylewis.qrs(2);
         Raftery_Lewis_s=options_.convergence.rafterylewis.qrs(3);
-        oo_.Raftery_Lewis = raftery_lewis(x2,Raftery_Lewis_q,Raftery_Lewis_r,Raftery_Lewis_s);
-        oo_.Raftery_Lewis.parameter_names=param_name;
+        oo_.convergence.raftery_lewis = raftery_lewis(x2,Raftery_Lewis_q,Raftery_Lewis_r,Raftery_Lewis_s);
+        oo_.convergence.raftery_lewis.parameter_names=param_name;
         my_title=sprintf('Raftery/Lewis (1992) Convergence Diagnostics, based on quantile q=%4.3f with precision r=%4.3f with probability s=%4.3f.',Raftery_Lewis_q,Raftery_Lewis_r,Raftery_Lewis_s);
         headers = {'Variables'; 'M (burn-in)'; 'N (req. draws)'; 'N+M (total draws)'; 'k (thinning)'};
-        raftery_data_mat=[oo_.Raftery_Lewis.M_burn,oo_.Raftery_Lewis.N_prec,oo_.Raftery_Lewis.N_total,oo_.Raftery_Lewis.k_thin];
+        raftery_data_mat=[oo_.convergence.raftery_lewis.M_burn,oo_.convergence.raftery_lewis.N_prec,oo_.convergence.raftery_lewis.N_total,oo_.convergence.raftery_lewis.k_thin];
         raftery_data_mat=[raftery_data_mat;max(raftery_data_mat)];
         labels_Raftery_Lewis = vertcat(param_name, 'Maximum');
         lh = cellofchararraymaxlength(labels_Raftery_Lewis)+2;
@@ -228,7 +228,7 @@ if NumberOfDraws < Origin
 end
 
 if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
-    fidTeX = fopen([OutputFolder '/' ModelName '_UnivariateDiagnostics.tex'],'w');
+    fidTeX = fopen([latexFolder '/' ModelName '_UnivariateDiagnostics.tex'],'w');
     fprintf(fidTeX,'%% TeX eps-loader file generated by mcmc_diagnostics.m (Dynare).\n');
     fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
     fprintf(fidTeX,' \n');
@@ -277,7 +277,7 @@ clear pmet temp moyenne CSUP CINF csup cinf n linea iter tmp;
 pages = floor(npar/npardisp); % changed from 3 to npardisp
 k = 0;
 for i = 1:pages
-    h=dyn_figure(options_.nodisplay,'Name','MCMC univariate convergence diagnostic (Brooks and Gelman,1998)');
+    hh_fig = dyn_figure(options_.nodisplay,'Name','MCMC univariate convergence diagnostic (Brooks and Gelman,1998)');
     boxplot = 1;
     for j = 1:npardisp % Loop over parameters  %npardisp instead of 3
         k = k+1;
@@ -311,11 +311,11 @@ for i = 1:pages
             boxplot = boxplot + 1;
         end
     end
-    dyn_saveas(h,[OutputFolder '/' ModelName '_udiag' int2str(i)],options_.nodisplay,options_.graph_format);
+    dyn_saveas(hh_fig,[graphFolder '/' ModelName '_udiag' int2str(i)],options_.nodisplay,options_.graph_format);
     if 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_udiag%s}\n',options_.figures.textwidth*min((boxplot-1)/3,1),[OutputFolder '/' ModelName],int2str(i));
+        fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_udiag%s}\n',options_.figures.textwidth*min((boxplot-1)/3,1),[graphFolder '/' ModelName],int2str(i));
         fprintf(fidTeX,'\\caption{Univariate convergence diagnostics for the Metropolis-Hastings.\n');
         fprintf(fidTeX,'The first, second and third columns are respectively the criteria based on\n');
         fprintf(fidTeX,'the eighty percent interval, the second and third moments.}');
@@ -333,7 +333,7 @@ if reste
         nr = npardisp;
         nc = 3;
     end
-    h = dyn_figure(options_.nodisplay,'Name','MCMC univariate convergence diagnostic (Brooks and Gelman, 1998)');
+    hh_fig = dyn_figure(options_.nodisplay,'Name','MCMC univariate convergence diagnostic (Brooks and Gelman, 1998)');
     boxplot = 1;
     for j = 1:reste
         k = k+1;
@@ -375,11 +375,11 @@ if reste
             boxplot = boxplot + 1;
         end
     end
-    dyn_saveas(h,[ OutputFolder '/' ModelName '_udiag' int2str(pages+1)],options_.nodisplay,options_.graph_format);
+    dyn_saveas(hh_fig,[ graphFolder '/' ModelName '_udiag' int2str(pages+1)],options_.nodisplay,options_.graph_format);
     if 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_udiag%s}\n',options_.figures.textwidth*min((boxplot-1)/nc,1),[OutputFolder '/' ModelName],int2str(pages+1));
+        fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_udiag%s}\n',options_.figures.textwidth*min((boxplot-1)/nc,1),[graphFolder '/' ModelName],int2str(pages+1));
         if reste == 2
             fprintf(fidTeX,'\\caption{Univariate convergence diagnostics for the Metropolis-Hastings.\n');
             fprintf(fidTeX,'The first, second and third columns are respectively the criteria based on\n');
@@ -401,7 +401,7 @@ clear UDIAG;
 % Multivariate diagnostic.
 %
 if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
-    fidTeX = fopen([OutputFolder '/' ModelName '_MultivariateDiagnostics.tex'],'w');
+    fidTeX = fopen([latexFolder '/' ModelName '_MultivariateDiagnostics.tex'],'w');
     fprintf(fidTeX,'%% TeX eps-loader file generated by mcmc_diagnostics.m (Dynare).\n');
     fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
     fprintf(fidTeX,' \n');
@@ -445,7 +445,7 @@ for iter  = Origin:StepSize:NumberOfDraws
 end
 MDIAG(:,[2 4 6],:) = MDIAG(:,[2 4 6],:)/nblck;
 
-h = dyn_figure(options_.nodisplay,'Name','Multivariate convergence diagnostic');
+hh_fig = dyn_figure(options_.nodisplay,'Name','Multivariate convergence diagnostic');
 boxplot = 1;
 for crit = 1:3
     if crit == 1
@@ -470,12 +470,12 @@ for crit = 1:3
     title(namnam,'Interpreter','none');
     boxplot = boxplot + 1;
 end
-dyn_saveas(h,[ OutputFolder '/' ModelName '_mdiag'],options_.nodisplay,options_.graph_format);
+dyn_saveas(hh_fig,[ graphFolder '/' ModelName '_mdiag'],options_.nodisplay,options_.graph_format);
 
 if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
     fprintf(fidTeX,'\\begin{figure}[H]\n');
     fprintf(fidTeX,'\\centering \n');
-    fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s_mdiag}\n',[OutputFolder '/' ModelName]);
+    fprintf(fidTeX,'\\includegraphics[width=0.8\\textwidth]{%s_mdiag}\n',[graphFolder '/' ModelName]);
     fprintf(fidTeX,'\\caption{Multivariate convergence diagnostics for the Metropolis-Hastings.\n');
     fprintf(fidTeX,'The first, second and third rows are respectively the criteria based on\n');
     fprintf(fidTeX,'the eighty percent interval, the second and third moments. The different \n');
diff --git a/matlab/display_estimation_results_table.m b/matlab/display_estimation_results_table.m
index 4d0b7031a45460e27b5384d4456cae99d6e496ba..6078d50317506c955c0ff39556dd245febbf3495 100644
--- a/matlab/display_estimation_results_table.m
+++ b/matlab/display_estimation_results_table.m
@@ -20,7 +20,7 @@ function oo_=display_estimation_results_table(xparam1,stdh,M_,options_,estim_par
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright © 2014-2018 Dynare Team
+% Copyright © 2014-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -177,11 +177,11 @@ if any(xparam1(1:nvx+nvn)<0)
     warning(sprintf('Some estimated standard deviations are negative.\n         Dynare internally works with variances so that the sign does not matter.\n         Nevertheless, it is recommended to impose either prior restrictions (Bayesian Estimation)\n         or a lower bound (ML) to assure positive values.'))
 end
 
-OutputDirectoryName = CheckPath('Output',M_.dname);
+latexDirectoryName = CheckPath('latex',M_.dname);
 
 if any(bayestopt_.pshape > 0) && options_.TeX %% Bayesian estimation (posterior mode) Latex output
     if np
-        filename = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_1.tex'];
+        filename = [latexDirectoryName '/' M_.fname '_Posterior_Mode_1.tex'];
         fidTeX = fopen(filename,'w');
         TeXBegin_Bayesian(fidTeX,1,'parameters')
         ip = nvx+nvn+ncx+ncn+1;
@@ -198,7 +198,7 @@ if any(bayestopt_.pshape > 0) && options_.TeX %% Bayesian estimation (posterior
         TeXEnd(fidTeX)
     end
     if nvx
-        TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_2.tex'];
+        TeXfile = [latexDirectoryName '/' M_.fname '_Posterior_Mode_2.tex'];
         fidTeX = fopen(TeXfile,'w');
         TeXBegin_Bayesian(fidTeX,2,'standard deviation of structural shocks')
         ip = 1;
@@ -216,7 +216,7 @@ if any(bayestopt_.pshape > 0) && options_.TeX %% Bayesian estimation (posterior
         TeXEnd(fidTeX)
     end
     if nvn
-        TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_3.tex'];
+        TeXfile = [latexDirectoryName '/' M_.fname '_Posterior_Mode_3.tex'];
         fidTeX  = fopen(TeXfile,'w');
         TeXBegin_Bayesian(fidTeX,3,'standard deviation of measurement errors')
         ip = nvx+1;
@@ -234,7 +234,7 @@ if any(bayestopt_.pshape > 0) && options_.TeX %% Bayesian estimation (posterior
         TeXEnd(fidTeX)
     end
     if ncx
-        TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_4.tex'];
+        TeXfile = [latexDirectoryName '/' M_.fname '_Posterior_Mode_4.tex'];
         fidTeX = fopen(TeXfile,'w');
         TeXBegin_Bayesian(fidTeX,4,'correlation of structural shocks')
         ip = nvx+nvn+1;
@@ -253,7 +253,7 @@ if any(bayestopt_.pshape > 0) && options_.TeX %% Bayesian estimation (posterior
         TeXEnd(fidTeX)
     end
     if ncn
-        TeXfile = [OutputDirectoryName '/' M_.fname '_Posterior_Mode_5.tex'];
+        TeXfile = [latexDirectoryName '/' M_.fname '_Posterior_Mode_5.tex'];
         fidTeX = fopen(TeXfile,'w');
         TeXBegin_Bayesian(fidTeX,5,'correlation of measurement errors')
         ip = nvx+nvn+ncx+1;
@@ -273,7 +273,7 @@ if any(bayestopt_.pshape > 0) && options_.TeX %% Bayesian estimation (posterior
     end
 elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
     if np
-        filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_1.tex'];
+        filename = [latexDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_1.tex'];
         fidTeX = fopen(filename, 'w');
         TeXBegin_ML(fidTeX, 1, 'parameters', table_title, LaTeXtitle)
         ip = nvx+nvn+ncx+ncn+1;
@@ -288,7 +288,7 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
         TeXEnd(fidTeX)
     end
     if nvx
-        filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_2.tex'];
+        filename = [latexDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_2.tex'];
         fidTeX = fopen(filename, 'w');
         TeXBegin_ML(fidTeX, 2, 'standard deviation of structural shocks', table_title, LaTeXtitle)
         ip = 1;
@@ -304,7 +304,7 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
         TeXEnd(fidTeX)
     end
     if nvn
-        filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_3.tex'];
+        filename = [latexDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_3.tex'];
         fidTeX = fopen(filename, 'w');
         TeXBegin_ML(fidTeX, 3, 'standard deviation of measurement errors', table_title, LaTeXtitle)
         ip = nvx+1;
@@ -320,7 +320,7 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
         TeXEnd(fidTeX)
     end
     if ncx
-        filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_4.tex'];
+        filename = [latexDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_4.tex'];
         fidTeX = fopen(filename, 'w');
         TeXBegin_ML(fidTeX, 4, 'correlation of structural shocks', table_title,LaTeXtitle)
         ip = nvx+nvn+1;
@@ -337,7 +337,7 @@ elseif all(bayestopt_.pshape == 0) && options_.TeX %% MLE and GMM Latex output
         TeXEnd(fidTeX)
     end
     if ncn
-        filename = [OutputDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_5.tex'];
+        filename = [latexDirectoryName '/' M_.fname '_' LaTeXtitle '_Mode_5.tex'];
         fidTeX = fopen(filename, 'w');
         TeXBegin_ML(fidTeX, 5, 'correlation of measurement errors', table_title, LaTeXtitle)
         ip = nvx+nvn+ncx+1;
diff --git a/matlab/dynare_estimation.m b/matlab/dynare_estimation.m
index 15ef024f208cab09983f1d3e9ffe611165af0398..14e90d403bbcdb103a6cfc9624ce488ff8065a8a 100644
--- a/matlab/dynare_estimation.m
+++ b/matlab/dynare_estimation.m
@@ -12,7 +12,7 @@ function oo_recursive_=dynare_estimation(var_list,dname)
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright © 2003-2021 Dynare Team
+% Copyright © 2003-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -164,7 +164,7 @@ if nnobs > 1 && horizon > 0
     for i = 1:length(var_list)
         if mod(i,nstar) == 1
             plot_index=plot_index+1;
-            hfig = dyn_figure(options_.nodisplay,'Name',['Out of sample forecasts (',num2str(plot_index),')']);
+            hh_fig = dyn_figure(options_.nodisplay,'Name',['Out of sample forecasts (',num2str(plot_index),')']);
             m = 1;
         end
         subplot(nr,nc,m)
@@ -221,7 +221,7 @@ if nnobs > 1 && horizon > 0
         xlim([nobs(1)-offsetx nobs(end)+horizon])
         m = m + 1;
         if mod(i+1,nstar) == 1 || i==length(var_list)
-            dyn_saveas(hfig,[M_.dname,filesep,'graphs',filesep M_.fname '_RecursiveForecasts_' int2str(plot_index)],options_.nodisplay,options_.graph_format);
+            dyn_saveas(hh_fig,[M_.dname,filesep,'graphs',filesep M_.fname '_RecursiveForecasts_' int2str(plot_index)],options_.nodisplay,options_.graph_format);
         end
     end
 end
diff --git a/matlab/dynare_estimation_1.m b/matlab/dynare_estimation_1.m
index f4349f224f54407dbeeb1c90faba519c3a547d54..704c2b9c65f3a2786cbeeda406978c182d94707c 100644
--- a/matlab/dynare_estimation_1.m
+++ b/matlab/dynare_estimation_1.m
@@ -309,7 +309,8 @@ end
 if options_.mode_check.status && ~options_.mh_posterior_mode_estimation
     ana_deriv_old = options_.analytic_derivation;
     options_.analytic_derivation = 0;
-    mode_check(objective_function,xparam1,hh,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
+    mode_check(objective_function,xparam1,hh,options_,M_,estim_params_,bayestopt_,bounds,false,...
+               dataset_, dataset_info, options_, M_, estim_params_, bayestopt_, bounds,oo_);
     options_.analytic_derivation = ana_deriv_old;
 end
 
@@ -411,12 +412,12 @@ if (any(bayestopt_.pshape  >0 ) && options_.mh_replic) || ...
         if options_.mh_replic
             ana_deriv_old = options_.analytic_derivation;
             options_.analytic_derivation = 0;
-            posterior_sampler(objective_function,posterior_sampler_options.proposal_distribution,xparam1,posterior_sampler_options,bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_);
+            posterior_sampler(objective_function,posterior_sampler_options.proposal_distribution,xparam1,posterior_sampler_options,bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_,dispString);
             options_.analytic_derivation = ana_deriv_old;
         end
     end
     %% Here I discard first mh_drop percent of the draws:
-    CutSample(M_, options_, estim_params_);
+    CutSample(M_, options_, dispString);
     if options_.mh_posterior_mode_estimation
         [~,~,posterior_mode,~] = compute_mh_covariance_matrix(bayestopt_,M_.fname,M_.dname);
         oo_=fill_mh_mode(posterior_mode',NaN(length(posterior_mode),1),M_,options_,estim_params_,bayestopt_,oo_,'posterior');
@@ -475,7 +476,7 @@ if (any(bayestopt_.pshape  >0 ) && options_.mh_replic) || ...
                 if error_flag
                     error('%s: I cannot compute the posterior IRFs!',dispString)
                 end
-                PosteriorIRF('posterior');
+                PosteriorIRF('posterior',dispString);
             end
             if options_.moments_varendo
                 if error_flag
@@ -507,7 +508,7 @@ if (any(bayestopt_.pshape  >0 ) && options_.mh_replic) || ...
                     error('%s: I cannot compute the posterior statistics!',dispString)
                 end
                 if options_.order==1 && ~options_.particle.status
-                    prior_posterior_statistics('posterior',dataset_,dataset_info); %get smoothed and filtered objects and forecasts
+                    prior_posterior_statistics('posterior',dataset_,dataset_info,dispString); %get smoothed and filtered objects and forecasts
                 else
                     error('%s: Particle Smoothers are not yet implemented.',dispString)
                 end
diff --git a/matlab/dynare_sensitivity.m b/matlab/dynare_sensitivity.m
index 07e440e810f7c21200c4c2c94f25ea33caa0dabc..4a3389d225f08bc92122f6ed692843e306aa7fc2 100644
--- a/matlab/dynare_sensitivity.m
+++ b/matlab/dynare_sensitivity.m
@@ -410,9 +410,9 @@ if options_gsa.rmse
                 end
 
             end
-            prior_posterior_statistics('gsa',dataset_, dataset_info);
+            prior_posterior_statistics('gsa',dataset_, dataset_info,'gsa::mcmc');
             if options_.bayesian_irf
-                PosteriorIRF('gsa');
+                PosteriorIRF('gsa','gsa::mcmc');
             end
             options_gsa.load_rmse=0;
             %   else
diff --git a/matlab/dyntable.m b/matlab/dyntable.m
index 29d0b6c9a746d80dc47fa7573bdd211bb1cd2f62..47d24fc2978aa2d1b85f6561544f59ba099f866d 100644
--- a/matlab/dyntable.m
+++ b/matlab/dyntable.m
@@ -15,7 +15,7 @@ function dyntable(options_, title, headers, labels, values, label_width, val_wid
 % OUTPUTS
 % none
 
-% Copyright © 2002-2022 Dynare Team
+% Copyright © 2002-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -73,11 +73,11 @@ if nargin==9
 end
 
 if length(headers) > 0
-    hh = sprintf(label_format_leftbound , headers{1});
+    hh_tbl = sprintf(label_format_leftbound , headers{1});
     for i=2:length(headers)
-        hh  = [hh sprintf(header_string_format, headers{i})];
+        hh_tbl  = [hh_tbl sprintf(header_string_format, headers{i})];
     end
-    disp(hh)
+    disp(hh_tbl)
 end
 
 for i=1:size(values,1)
diff --git a/matlab/ep/extended_path.m b/matlab/ep/extended_path.m
index 0b4bfb1ef504dc2c70929e504178c209180fce96..d94aa1f0bca2c971f0b846ac13bef063049b87c3 100644
--- a/matlab/ep/extended_path.m
+++ b/matlab/ep/extended_path.m
@@ -19,7 +19,7 @@ function [ts, DynareResults] = extended_path(initialconditions, samplesize, exog
 %
 % SPECIAL REQUIREMENTS
 
-% Copyright © 2009-2020 Dynare Team
+% Copyright © 2009-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -46,8 +46,8 @@ endogenous_variables_paths = NaN(DynareModel.endo_nbr,samplesize+1);
 endogenous_variables_paths(:,1) = initialconditions;
 
 % Set waitbar (graphic or text  mode)
-hh = dyn_waitbar(0,'Please wait. Extended Path simulations...');
-set(hh,'Name','EP simulations.');
+hh_fig = dyn_waitbar(0,'Please wait. Extended Path simulations...');
+set(hh_fig,'Name','EP simulations.');
 
 % Initialize while-loop index.
 t = 1;
@@ -55,7 +55,7 @@ t = 1;
 % Main loop.
 while (t <= samplesize)
     if ~mod(t,10)
-        dyn_waitbar(t/samplesize,hh,'Please wait. Extended Path simulations...');
+        dyn_waitbar(t/samplesize,hh_fig,'Please wait. Extended Path simulations...');
     end
     % Set period index.
     t = t+1;
@@ -83,7 +83,7 @@ while (t <= samplesize)
 end % (while) loop over t
 
 % Close waitbar.
-dyn_waitbar_close(hh);
+dyn_waitbar_close(hh_fig);
 
 % Set the initial period.
 if isdates(DynareOptions.initial_period)
diff --git a/matlab/execute_prior_posterior_function.m b/matlab/execute_prior_posterior_function.m
index 3ac13f177edf5348d62b852de5f60e99349f917b..4967370e571647c958f631e29a711019bffc8d74 100644
--- a/matlab/execute_prior_posterior_function.m
+++ b/matlab/execute_prior_posterior_function.m
@@ -52,7 +52,7 @@ n_draws=options_.sampling_draws;
 if strcmpi(type,'posterior')
     % Get informations about the _posterior_draws files.
     % discard first mh_drop percent of the draws:
-    CutSample(M_, options_, estim_params_);
+    CutSample(M_, options_, 'prior_posterior_function');
     % initialize metropolis draws
     options_.sub_draws = n_draws; % set draws for sampling; changed value is not returned to base workspace
     [error_flag, ~, options_] = metropolis_draw(1, options_, estim_params_, M_);
diff --git a/matlab/forecast_graphs.m b/matlab/forecast_graphs.m
index fffcbe359e20523dbf2bbc7f4f513d26c0c46533..6bc15522f268018f9bd28b4e3f3f644a938b00cf 100644
--- a/matlab/forecast_graphs.m
+++ b/matlab/forecast_graphs.m
@@ -8,7 +8,7 @@ function forecast_graphs(var_list,M_, oo_,options_)
 %   o oo_                   outputs structure
 %   o options_              options structure
 
-% Copyright © 2008-2018 Dynare Team
+% Copyright © 2008-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -61,11 +61,11 @@ end
 
 m = 1;
 n_fig = 1;
-hh = dyn_figure(options_.nodisplay, 'Name', 'Forecasts (I)');
+hh_fig = dyn_figure(options_.nodisplay, 'Name', 'Forecasts (I)');
 
 for j= 1:nvar
     if m > nc*nr
-        dyn_saveas(hh,[ dname '/graphs/forcst' int2str(n_fig)], options_.nodisplay, options_.graph_format);
+        dyn_saveas(hh_fig,[ dname '/graphs/forcst' int2str(n_fig)], 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');
@@ -76,7 +76,7 @@ for j= 1:nvar
             fprintf(fidTeX,' \n');
         end
         n_fig =n_fig+1;
-        eval(['hh=dyn_figure(options_.nodisplay,''Name'',''Forecasts (' int2str(n_fig) ')'');']);
+        eval(['hh_fig=dyn_figure(options_.nodisplay,''Name'',''Forecasts (' int2str(n_fig) ')'');']);
         m = 1;
     end
     subplot(nr, nc, m);
@@ -99,7 +99,7 @@ for j= 1:nvar
 end
 
 if m > 1
-    dyn_saveas(hh,[dname '/graphs/forcst' int2str(n_fig)],options_.nodisplay,options_.graph_format);
+    dyn_saveas(hh_fig,[dname '/graphs/forcst' int2str(n_fig)],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');
@@ -124,10 +124,10 @@ if isfield(oo_.forecast,'HPDinf_ME')
 
     m = 1;
     n_fig = 1;
-    hh=dyn_figure(options_.nodisplay,'Name','Forecasts including ME (I)');
+    hh_fig=dyn_figure(options_.nodisplay,'Name','Forecasts including ME (I)');
     for j= 1:length(var_names)
         if m > nc*nr
-            dyn_saveas(hh,[ dname '/graphs/forcst_ME' int2str(n_fig)],options_.nodisplay,options_.graph_format);
+            dyn_saveas(hh_fig,[ dname '/graphs/forcst_ME' int2str(n_fig)],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');
@@ -138,7 +138,7 @@ if isfield(oo_.forecast,'HPDinf_ME')
                 fprintf(fidTeX,' \n');
             end
             n_fig =n_fig+1;
-            eval(['hh=dyn_figure(options_.nodisplay,''Name'',''Forecasts (' int2str(n_fig) ')'');']);
+            eval(['hh_fig=dyn_figure(options_.nodisplay,''Name'',''Forecasts (' int2str(n_fig) ')'');']);
             m = 1;
         end
         subplot(nr,nc,m);
@@ -162,7 +162,7 @@ if isfield(oo_.forecast,'HPDinf_ME')
     end
 
     if m > 1
-        dyn_saveas(hh,[dname '/graphs/forcst_ME' int2str(n_fig)],options_.nodisplay,options_.graph_format);
+        dyn_saveas(hh_fig,[dname '/graphs/forcst_ME' int2str(n_fig)],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');
diff --git a/matlab/gsa/filt_mc_.m b/matlab/gsa/filt_mc_.m
index 02549596cf5bbafcbd25deea1dc8ce289a5b1376..ebe9ca9eee1a386e5f8bd0bc801dc6c871822eea 100644
--- a/matlab/gsa/filt_mc_.m
+++ b/matlab/gsa/filt_mc_.m
@@ -391,7 +391,7 @@ else
             end
             if mod(i,9)==1
                 ifig=ifig+1;
-                hh=dyn_figure(options_.nodisplay,'name',[temp_name,' ',int2str(ifig)]);
+                hh_fig=dyn_figure(options_.nodisplay,'name',[temp_name,' ',int2str(ifig)]);
             end
             subplot(3,3,i-9*(ifig-1))
             h=cumplot(lnprior(ixx(1:nfilt0(i),i)));
@@ -407,18 +407,18 @@ else
                     annotation('textbox', [0.55,0,0.35,0.05],'String', 'Log-prior for WORSE R2', 'Color','Red','horizontalalignment','center');
                 end
                 if options_.opt_gsa.ppost
-                    dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnprior',int2str(ifig)],options_.nodisplay,options_.graph_format);
+                    dyn_saveas(hh_fig,[OutDir filesep fname_ '_rmse_post_lnprior',int2str(ifig)],options_.nodisplay,options_.graph_format);
                     if options_.TeX
                         create_TeX_loader(options_,[OutDir '/' fname_ '_rmse_post_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_post_lnprior',options_.figures.textwidth*min((i-9*(ifig-1))/3,1))
                     end
                 else
                     if options_.opt_gsa.pprior
-                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_lnprior',int2str(ifig) ],options_.nodisplay,options_.graph_format);
+                        dyn_saveas(hh_fig,[OutDir filesep fname_ '_rmse_prior_lnprior',int2str(ifig) ],options_.nodisplay,options_.graph_format);
                         if options_.TeX
                             create_TeX_loader(options_,[OutDir '/' fname_ '_rmse_prior_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_prior_lnprior',options_.figures.textwidth*min((i-9*(ifig-1))/3,1))
                         end
                     else
-                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_lnprior',int2str(ifig) ],options_.nodisplay,options_.graph_format);
+                        dyn_saveas(hh_fig,[OutDir filesep fname_ '_rmse_mc_lnprior',int2str(ifig) ],options_.nodisplay,options_.graph_format);
                         if options_.TeX
                             create_TeX_loader(options_,[OutDir '/' fname_ '_rmse_mc_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_mc_lnprior',options_.figures.textwidth*min((i-9*(ifig-1))/3,1))
                         end
@@ -439,7 +439,7 @@ else
             end
             if mod(i,9)==1
                 ifig=ifig+1;
-                hh = dyn_figure(options_.nodisplay,'Name',[temp_name,' ',int2str(ifig)]);
+                hh_fig = dyn_figure(options_.nodisplay,'Name',[temp_name,' ',int2str(ifig)]);
             end
             subplot(3,3,i-9*(ifig-1))
             h=cumplot(likelihood(ixx(1:nfilt0(i),i)));
@@ -458,18 +458,18 @@ else
                     annotation('textbox', [0.55,0,0.35,0.05],'String', 'Log-likelihood for WORSE R2', 'Color','Red','horizontalalignment','center');
                 end
                 if options_.opt_gsa.ppost
-                    dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnlik',int2str(ifig) ],options_.nodisplay,options_.graph_format);
+                    dyn_saveas(hh_fig,[OutDir filesep fname_ '_rmse_post_lnlik',int2str(ifig) ],options_.nodisplay,options_.graph_format);
                     if options_.TeX
                         create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_post_lnprior',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_post_lnprior',options_.figures.textwidth*min((i-9*(ifig-1))/3,1));
                     end
                 else
                     if options_.opt_gsa.pprior
-                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_lnlik',int2str(ifig)],options_.nodisplay,options_.graph_format);
+                        dyn_saveas(hh_fig,[OutDir filesep fname_ '_rmse_prior_lnlik',int2str(ifig)],options_.nodisplay,options_.graph_format);
                         if options_.TeX
                             create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_prior_lnlik',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_prior_lnlik',options_.figures.textwidth*min((i-9*(ifig-1))/3,1));
                         end
                     else
-                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_lnlik',int2str(ifig) ],options_.nodisplay,options_.graph_format);
+                        dyn_saveas(hh_fig,[OutDir filesep fname_ '_rmse_mc_lnlik',int2str(ifig) ],options_.nodisplay,options_.graph_format);
                         if options_.TeX
                             create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_mc_lnlik',int2str(ifig) ],ifig,[temp_name,' ',int2str(ifig)],'rmse_mc_lnlik',options_.figures.textwidth*min((i-9*(ifig-1))/3,1));
                         end
@@ -490,7 +490,7 @@ else
             end
             if mod(i,9)==1
                 ifig=ifig+1;
-                hh = dyn_figure(options_.nodisplay,'Name',[temp_name,' ',int2str(ifig)]);
+                hh_fig = dyn_figure(options_.nodisplay,'Name',[temp_name,' ',int2str(ifig)]);
             end
             subplot(3,3,i-9*(ifig-1))
             h=cumplot(logpo2(ixx(1:nfilt0(i),i)));
@@ -509,18 +509,18 @@ else
                     annotation('textbox', [0.55,0,0.35,0.05],'String', 'Log-posterior for WORSE R2', 'Color','Red','horizontalalignment','center');
                 end
                 if options_.opt_gsa.ppost
-                    dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnpost',int2str(ifig) ],options_.nodisplay,options_.graph_format);
+                    dyn_saveas(hh_fig,[OutDir filesep fname_ '_rmse_post_lnpost',int2str(ifig) ],options_.nodisplay,options_.graph_format);
                     if options_.TeX
                         create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_post_lnpost',int2str(ifig) ],ifig,[temp_name,' ',int2str(ifig)],'rmse_post_lnpost',options_.figures.textwidth*min((i-9*(ifig-1))/3,1));
                     end
                 else
                     if options_.opt_gsa.pprior
-                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_lnpost',int2str(ifig)],options_.nodisplay,options_.graph_format);
+                        dyn_saveas(hh_fig,[OutDir filesep fname_ '_rmse_prior_lnpost',int2str(ifig)],options_.nodisplay,options_.graph_format);
                         if options_.TeX
                             create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_prior_lnpost',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_prior_lnpost',options_.figures.textwidth*min((i-9*(ifig-1))/3,1));
                         end
                     else
-                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_lnpost',int2str(ifig)],options_.nodisplay,options_.graph_format);
+                        dyn_saveas(hh_fig,[OutDir filesep fname_ '_rmse_mc_lnpost',int2str(ifig)],options_.nodisplay,options_.graph_format);
                         if options_.TeX
                             create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_mc_lnpost',int2str(ifig)],ifig,[temp_name,' ',int2str(ifig)],'rmse_mc_lnpost',options_.figures.textwidth*min((i-9*(ifig-1))/3,1));
                         end
@@ -746,7 +746,7 @@ else
         for iy = 1:length(vvarvecm)
             ipar = find(any(squeeze(PPV(iy,:,:))<alpha));
             for ix=1:ceil(length(ipar)/5)
-                hh = dyn_figure(options_.nodisplay,'name',[temp_name,' observed variable ', vvarvecm{iy}]);
+                hh_fig = dyn_figure(options_.nodisplay,'name',[temp_name,' observed variable ', vvarvecm{iy}]);
                 for j=1+5*(ix-1):min(length(ipar),5*ix)
                     subplot(2,3,j-5*(ix-1))
                     h0=cumplot(x(:,ipar(j)));
@@ -782,18 +782,18 @@ else
                     set(h0,'fontsize',6,'position',[0.7 0.1 0.2 0.3],'interpreter','none');
                 end
                 if options_.opt_gsa.ppost
-                    dyn_saveas(hh,[ OutDir filesep fname_ '_rmse_post_' vvarvecm{iy} '_' int2str(ix)],options_.nodisplay,options_.graph_format);
+                    dyn_saveas(hh_fig,[ OutDir filesep fname_ '_rmse_post_' vvarvecm{iy} '_' int2str(ix)],options_.nodisplay,options_.graph_format);
                     if options_.TeX
                         create_TeX_loader(options_,[ OutDir filesep fname_ '_rmse_post_' vvarvecm{iy} '_' int2str(ix)],ix,[temp_name,' observed variable $',vvarvecm_tex{iy} '$'],['rmse_post_' vvarvecm{iy}],1)
                     end
                 else
                     if options_.opt_gsa.pprior
-                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_' vvarvecm{iy} '_' int2str(ix) ],options_.nodisplay,options_.graph_format);
+                        dyn_saveas(hh_fig,[OutDir filesep fname_ '_rmse_prior_' vvarvecm{iy} '_' int2str(ix) ],options_.nodisplay,options_.graph_format);
                         if options_.TeX
                             create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_prior_' vvarvecm{iy} '_' int2str(ix) ],ix,[temp_name,' observed variable $',vvarvecm_tex{iy} '$'],['rmse_prior_' vvarvecm{iy}],1)
                         end
                     else
-                        dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_' vvarvecm{iy} '_' int2str(ix)],options_.nodisplay,options_.graph_format);
+                        dyn_saveas(hh_fig,[OutDir filesep fname_ '_rmse_mc_' vvarvecm{iy} '_' int2str(ix)],options_.nodisplay,options_.graph_format);
                         if options_.TeX
                             create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_mc_' vvarvecm{iy} '_' int2str(ix)],ix,[temp_name,' observed variable $',vvarvecm_tex{iy} '$'],['rmse_mc_' vvarvecm{iy}],1)
                         end
@@ -803,7 +803,7 @@ else
         end
         % now I plot by individual parameters
         for ix=1:ceil(length(nsnam)/5)
-            hh = dyn_figure(options_.nodisplay,'name',[temp_name,' estimated params and shocks ',int2str(ix)]);
+            hh_fig = dyn_figure(options_.nodisplay,'name',[temp_name,' estimated params and shocks ',int2str(ix)]);
             for j=1+5*(ix-1):min(size(snam2,1),5*ix)
                 subplot(2,3,j-5*(ix-1))
                 h0=cumplot(x(:,nsnam(j)));
@@ -840,18 +840,18 @@ else
                 set(h0,'fontsize',6,'position',[0.7 0.1 0.2 0.3],'interpreter','none');
             end
             if options_.opt_gsa.ppost
-                dyn_saveas(hh,[ OutDir filesep fname_ '_rmse_post_params_' int2str(ix)],options_.nodisplay,options_.graph_format);
+                dyn_saveas(hh_fig,[ OutDir filesep fname_ '_rmse_post_params_' int2str(ix)],options_.nodisplay,options_.graph_format);
                 if options_.TeX
                     create_TeX_loader(options_,[ OutDir filesep fname_ '_rmse_post_params_' int2str(ix)],ix,[temp_name,' estimated params and shocks ',int2str(ix)],'rmse_post_params',1)
                 end
             else
                 if options_.opt_gsa.pprior
-                    dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_params_' int2str(ix) ],options_.nodisplay,options_.graph_format);
+                    dyn_saveas(hh_fig,[OutDir filesep fname_ '_rmse_prior_params_' int2str(ix) ],options_.nodisplay,options_.graph_format);
                     if options_.TeX
                         create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_prior_params_' int2str(ix) ],ix,[temp_name,' estimated params and shocks ',int2str(ix)],'rmse_prior_params',1)
                     end
                 else
-                    dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_params_' int2str(ix)],options_.nodisplay,options_.graph_format);
+                    dyn_saveas(hh_fig,[OutDir filesep fname_ '_rmse_mc_params_' int2str(ix)],options_.nodisplay,options_.graph_format);
                     if options_.TeX
                         create_TeX_loader(options_,[OutDir filesep fname_ '_rmse_mc_params_' int2str(ix)],ix,[temp_name,' estimated params and shocks ',int2str(ix)],'rmse_mc_params',1)
                     end
diff --git a/matlab/gsa/map_ident_.m b/matlab/gsa/map_ident_.m
index 73eb02fbc94ae44e553a214ed17bb2f61081454a..7a1b525f1e7d2779bf4ae6f3a07a46785bedf7f3 100644
--- a/matlab/gsa/map_ident_.m
+++ b/matlab/gsa/map_ident_.m
@@ -5,7 +5,7 @@ function map_ident_(OutputDirectoryName,opt_gsa)
 % marco.ratto@ec.europa.eu
 
 % Copyright © 2012-2016 European Commission
-% Copyright © 2012-2018 Dynare Team
+% Copyright © 2012-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -90,7 +90,7 @@ if opt_gsa.load_ident_files==0
         ifig=0;
         for j=1:M_.exo_nbr
             if mod(j,6)==1
-                hh=dyn_figure(options_.nodisplay,'name',['Variance decomposition shocks']);
+                hh_fig=dyn_figure(options_.nodisplay,'name',['Variance decomposition shocks']);
                 ifig=ifig+1;
                 iplo=0;
             end
@@ -108,7 +108,7 @@ if opt_gsa.load_ident_files==0
             ylabel(' ')
             title(M_.exo_names{j},'interpreter','none')
             if mod(j,6)==0 | j==M_.exo_nbr
-                dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_vdec_exo_',int2str(ifig)],options_.nodisplay,options_.graph_format);
+                dyn_saveas(hh_fig,[OutputDirectoryName,'/',fname_,'_vdec_exo_',int2str(ifig)],options_.nodisplay,options_.graph_format);
                 create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_vdec_exo_',int2str(ifig)],ifig,['Variance decomposition shocks'],'vdec_exo',options_.figures.textwidth*min(iplo/3,1))
             end
         end
@@ -219,7 +219,7 @@ if opt_gsa.morris==1
             load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAvdec','vdec','ir_vdec','ic_vdec')
         end
 
-        hh = dyn_figure(options_.nodisplay,'name','Screening identification: variance decomposition');
+        hh_fig = dyn_figure(options_.nodisplay,'name','Screening identification: variance decomposition');
         %   boxplot(SAvdec,'whis',10,'symbol','r.')
         myboxplot(SAvdec,[],'.',[],10)
         set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
@@ -232,7 +232,7 @@ if opt_gsa.morris==1
         end
         xlabel(' ')
         title('Elementary effects variance decomposition')
-        dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_vdec'],options_.nodisplay,options_.graph_format);
+        dyn_saveas(hh_fig,[OutputDirectoryName,'/',fname_,'_morris_vdec'],options_.nodisplay,options_.graph_format);
         create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_vdec'],1,'Screening identification: variance decomposition','morris_vdec',1)
     else
         save([OutputDirectoryName,'/',fname_,'_morris_IDE.mat'],'vdec')
@@ -325,7 +325,7 @@ if opt_gsa.morris==1
         load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'ac','ir_ac','ic_ac')
     end
 
-    hh=dyn_figure(options_.nodisplay,'name','Screening identification: theoretical moments');
+    hh_fig=dyn_figure(options_.nodisplay,'name','Screening identification: theoretical moments');
     %   boxplot(SAcc,'whis',10,'symbol','r.')
     myboxplot(SAcc,[],'.',[],10)
     set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
@@ -338,7 +338,7 @@ if opt_gsa.morris==1
     end
     xlabel(' ')
     title('Elementary effects in the moments')
-    dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_moments'],options_.nodisplay,options_.graph_format);
+    dyn_saveas(hh_fig,[OutputDirectoryName,'/',fname_,'_morris_moments'],options_.nodisplay,options_.graph_format);
     create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_moments'],1,'Screening identification: theoretical moments','morris_moments',1)
 
     %   close(gcf),
@@ -722,7 +722,7 @@ if opt_gsa.morris==1
     else
         load([OutputDirectoryName,'/',fname_,'_morris_IDE'],'SAnorm','SAmunorm','SAsignorm')
     end
-    hh=dyn_figure(options_.nodisplay,'name','Screening identification: model'); %bar(SAnorm(:,irel))
+    hh_fig=dyn_figure(options_.nodisplay,'name','Screening identification: model'); %bar(SAnorm(:,irel))
                                                                                 %   boxplot(SAnorm','whis',10,'symbol','r.')
     myboxplot(SAnorm',[],'.',[],10)
     set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
@@ -736,10 +736,10 @@ if opt_gsa.morris==1
     end
     xlabel(' ')
     title('Elementary effects in the model')
-    dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morris_par'],options_.nodisplay,options_.graph_format);
+    dyn_saveas(hh_fig,[OutputDirectoryName,'/',fname_,'_morris_par'],options_.nodisplay,options_.graph_format);
     create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_morris_par'],1,'Screening identification: model','morris_par',1)
 
-    %   hh=dyn_figure(options_.nodisplay); %bar(SAmunorm(:,irel))
+    %   hh_fig=dyn_figure(options_.nodisplay); %bar(SAmunorm(:,irel))
     % %   boxplot(SAmunorm','whis',10,'symbol','r.')
     %   myboxplot(SAmunorm',[],'.',[],10)
     %   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
@@ -752,9 +752,9 @@ if opt_gsa.morris==1
     %   end
     %   xlabel(' ')
     %   title('\mu in the model')
-    %   dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morrismu_par'],options_.nodisplay,options_.graph_format);
+    %   dyn_saveas(hh_fig,[OutputDirectoryName,'/',fname_,'_morrismu_par'],options_.nodisplay,options_.graph_format);
     %
-    %   hh=dyn_figure(options_.nodisplay); %bar(SAsignorm(:,irel))
+    %   hh_fig=dyn_figure(options_.nodisplay); %bar(SAsignorm(:,irel))
     % %   boxplot(SAsignorm','whis',10,'symbol','r.')
     %   myboxplot(SAsignorm',[],'.',[],10)
     %   set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
@@ -767,7 +767,7 @@ if opt_gsa.morris==1
     %   end
     %   xlabel(' ')
     %   title('\sigma in the model')
-    %   dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_morrissig_par'],options_.nodisplay,options_.graph_format);
+    %   dyn_saveas(hh_fig,[OutputDirectoryName,'/',fname_,'_morrissig_par'],options_.nodisplay,options_.graph_format);
 
     %     figure, bar(SAnorm(:,irel)')
     %     set(gca,'xtick',[1:j0])
@@ -1521,7 +1521,7 @@ else  % main effects analysis
     %   SAmeanexo=mean(SAmomN(:,1:nshock));
 
     %   figure, bar(latent'*SAcc),
-    hh=dyn_figure(options_.nodisplay,'Name',['Identifiability indices in the ',fsuffix,' moments.']);
+    hh_fig=dyn_figure(options_.nodisplay,'Name',['Identifiability indices in the ',fsuffix,' moments.']);
     bar(sum(SAcc))
     set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:npT])
     set(gca,'xlim',[0.5 npT+0.5])
@@ -1534,7 +1534,7 @@ else  % main effects analysis
     end
     xlabel(' ')
     title(['Identifiability indices in the ',fsuffix,' moments.'],'interpreter','none')
-    dyn_saveas(hh,[OutputDirectoryName,'/',fname_,'_ident_ALL',fsuffix],options_.nodisplay,options_.graph_format);
+    dyn_saveas(hh_fig,[OutputDirectoryName,'/',fname_,'_ident_ALL',fsuffix],options_.nodisplay,options_.graph_format);
     create_TeX_loader(options_,[OutputDirectoryName,'/',fname_,'_ident_ALL',fsuffix],1,['Identifiability indices in the ',fsuffix,' moments.'],['ident_ALL',fsuffix]',1)
 
     %   figure, bar(SAmeanexo),
diff --git a/matlab/gsa/pick.m b/matlab/gsa/pick.m
index 7e63244b577acea62c4e3f9ffb2dc8278523b8df..de1cdabaf85af9eba30f057e929ca2e828f5eb24 100644
--- a/matlab/gsa/pick.m
+++ b/matlab/gsa/pick.m
@@ -1,7 +1,7 @@
 function pick
 %
 % Copyright © 2001-2017 European Commission
-% Copyright © 2017 DynareTeam
+% Copyright © 2017-2023 DynareTeam
 
 % This file is part of GLUEWIN
 % GLUEWIN is a MATLAB code designed for analysing the output
@@ -68,9 +68,9 @@ KK=K;
 
 set(button1,'Label',['Save ',num2str(K)],'Callback',['scatter_callback(',num2str(KK),',''save'')']);
 set(button2,'Label',['Eval ',num2str(K)],'Callback',['scatter_callback(',num2str(KK),',''eval'')']);
-hh=findobj(gcf,'type','axes','Tag','scatter');
-for k=1:length(hh)
-    axes(hh(k));
+hh_obj=findobj(gcf,'type','axes','Tag','scatter');
+for k=1:length(hh_obj)
+    axes(hh_obj(k));
     dum=get(gca,'children');
     dumx=get(dum(end),'xdata');
     dumy=get(dum(end),'ydata');
diff --git a/matlab/gsa/redform_map.m b/matlab/gsa/redform_map.m
index dbdd586fba5a42ea3dee0ffe11ca630f6b8b5c5b..1dd6f0d1b912087ad50de5edbee33394f2693623 100644
--- a/matlab/gsa/redform_map.m
+++ b/matlab/gsa/redform_map.m
@@ -16,7 +16,7 @@ function redform_map(dirname,options_gsa_)
 % marco.ratto@ec.europa.eu
 
 % Copyright © 2012-2016 European Commission
-% Copyright © 2012-2018 Dynare Team
+% Copyright © 2012-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -165,7 +165,7 @@ for j = 1:length(anamendo)
             if (max(y0)-min(y0))>1.e-10
                 if mod(iplo,9)==0 && isempty(threshold) && ~options_.nograph
                     ifig=ifig+1;
-                    hfig = dyn_figure(options_.nodisplay,'name',['Reduced Form Mapping: ', namendo,' vs shocks ',int2str(ifig)]);
+                    hh_fig = dyn_figure(options_.nodisplay,'name',['Reduced Form Mapping: ', namendo,' vs shocks ',int2str(ifig)]);
                     iplo=0;
                 end
                 iplo=iplo+1;
@@ -273,7 +273,7 @@ for j = 1:length(anamendo)
                 end
 
                 if isempty(threshold) && ~options_.nograph
-                    figure(hfig)
+                    figure(hh_fig)
                     subplot(3,3,iplo),
                     if ilog
                         [saso, iso] = sort(-silog(:,js));
@@ -292,7 +292,7 @@ for j = 1:length(anamendo)
                     end
                     title([logflag,' ',namendo,' vs ',namexo],'interpreter','none')
                     if iplo==9
-                        dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],options_.nodisplay,options_.graph_format);
+                        dyn_saveas(hh_fig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],options_.nodisplay,options_.graph_format);
                         create_TeX_loader(options_,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],[logflag,' ',strrep(namendo,'_','\_'),' vs ',strrep(namexo,'_','\_')],['redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],1)
                     end
                 end
@@ -303,7 +303,7 @@ for j = 1:length(anamendo)
         end
     end
     if iplo<9 && iplo>0 && ifig && ~options_.nograph
-        dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],options_.nodisplay,options_.graph_format);
+        dyn_saveas(hh_fig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],options_.nodisplay,options_.graph_format);
         create_TeX_loader(options_,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],[logflag,' ',strrep(namendo,'_','\_'),' vs ',strrep(namexo,'_','\_')],['redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],options_.figures.textwidth*min(iplo/3,1))
     end
     ifig=0;
@@ -320,7 +320,7 @@ for j = 1:length(anamendo)
             if (max(y0)-min(y0))>1.e-10
                 if mod(iplo,9)==0 && isempty(threshold) && ~options_.nograph
                     ifig=ifig+1;
-                    hfig = dyn_figure(options_.nodisplay,'name',['Reduced Form Mapping: ' namendo,' vs lags ',int2str(ifig)]);
+                    hh_fig = dyn_figure(options_.nodisplay,'name',['Reduced Form Mapping: ' namendo,' vs lags ',int2str(ifig)]);
                     iplo=0;
                 end
                 iplo=iplo+1;
@@ -429,7 +429,7 @@ for j = 1:length(anamendo)
                 end
 
                 if isempty(threshold) && ~options_.nograph
-                    figure(hfig),
+                    figure(hh_fig),
                     subplot(3,3,iplo),
                     if ilog
                         [saso, iso] = sort(-silog(:,js));
@@ -448,7 +448,7 @@ for j = 1:length(anamendo)
                     end
                     title([logflag,' ',namendo,' vs ',namlagendo,'(-1)'],'interpreter','none')
                     if iplo==9
-                        dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],options_.nodisplay,options_.graph_format);
+                        dyn_saveas(hh_fig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],options_.nodisplay,options_.graph_format);
                         create_TeX_loader(options_,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],[logflag,' ',strrep(namendo,'_','\_'),' vs ',strrep(namlagendo,'_','\_'),'(-1)'],['redform_', namendo,'_vs_lags_',logflag,':',num2str(ifig)],1)
                     end
                 end
@@ -459,14 +459,14 @@ for j = 1:length(anamendo)
         end
     end
     if iplo<9 && iplo>0 && ifig && ~options_.nograph
-        dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],options_.nodisplay,options_.graph_format);
+        dyn_saveas(hh_fig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],options_.nodisplay,options_.graph_format);
         create_TeX_loader(options_,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],[logflag,' ',strrep(namendo,'_','\_'),' vs ',strrep(namlagendo,'_','\_'),'(-1)'],['redform_', namendo,'_vs_lags_',logflag,':',num2str(ifig)],options_.figures.textwidth*min(iplo/3,1));
     end
 end
 
 if isempty(threshold) && ~options_.nograph
     if ilog==0
-        hfig=dyn_figure(options_.nodisplay,'name','Reduced Form GSA'); %bar(si)
+        hh_fig=dyn_figure(options_.nodisplay,'name','Reduced Form GSA'); %bar(si)
                                                                        % boxplot(si','whis',10,'symbol','r.')
         myboxplot(si',[],'.',[],10)
         xlabel(' ')
@@ -478,11 +478,11 @@ if isempty(threshold) && ~options_.nograph
             text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
         end
         title('Reduced form GSA')
-        dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_gsa'],options_.nodisplay,options_.graph_format);
+        dyn_saveas(hh_fig,[dirname,filesep,M_.fname,'_redform_gsa'],options_.nodisplay,options_.graph_format);
         create_TeX_loader(options_,[dirname,filesep,M_.fname,'_redform_gsa'],'Reduced Form GSA','redform_gsa')
 
     else
-        hfig=dyn_figure(options_.nodisplay,'name','Reduced Form GSA'); %bar(silog)
+        hh_fig=dyn_figure(options_.nodisplay,'name','Reduced Form GSA'); %bar(silog)
                                                                        % boxplot(silog','whis',10,'symbol','r.')
         myboxplot(silog',[],'.',[],10)
         set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
@@ -494,7 +494,7 @@ if isempty(threshold) && ~options_.nograph
             text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
         end
         title('Reduced form GSA - Log-transformed elements')
-        dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_gsa_log'],options_.nodisplay,options_.graph_format);
+        dyn_saveas(hh_fig,[dirname,filesep,M_.fname,'_redform_gsa_log'],options_.nodisplay,options_.graph_format);
         create_TeX_loader(options_,[dirname,filesep,M_.fname,'_redform_gsa_log'],'Reduced form GSA - Log-transformed elements','redform_gsa_log')
 
     end
@@ -560,7 +560,7 @@ if iload==0
         y1 = log(y0*isig+lam);
     end
     if ~options_.nograph
-        hfig=dyn_figure(options_.nodisplay,'name',options_map.figtitle);
+        hh_fig=dyn_figure(options_.nodisplay,'name',options_map.figtitle);
         subplot(221)
         if ilog
             hist(y1,30)
@@ -647,7 +647,7 @@ if iload==0
     gsa_.x0=x0(ifit,:);
     %   copyfile([fname,'_est.mat'],[fname,'.mat'])
     if ~options_.nograph
-        figure(hfig);
+        figure(hh_fig);
         subplot(223),
         plot(y0(ifit),[gsa_.fit y0(ifit)],'.'),
         r2 = gsa_.r2;
@@ -672,7 +672,7 @@ if iload==0
             plot(yn,[yf yn],'.'),
             title(['Out-of-sample prediction - R2=' num2str(r2,2)],'interpreter','none')
         end
-        dyn_saveas(hfig,fname,options_.nodisplay,options_.graph_format);
+        dyn_saveas(hh_fig,fname,options_.nodisplay,options_.graph_format);
         create_TeX_loader(options_,fname,['Out-of-sample prediction - R2=' num2str(r2,2)],'redform_gsa_log')
 
         if options_.nodisplay
@@ -685,10 +685,10 @@ else
     load([fname,'_map.mat'],'gsa_')
     if ~options_.nograph
         yf = ss_anova_fcast(x0, gsa_);
-        hfig=dyn_figure(options_.nodisplay,'name',options_map.title);
+        hh_fig=dyn_figure(options_.nodisplay,'name',options_map.title);
         plot(y0,[yf y0],'.'),
         title([namy,' vs ', namx,' pred'],'interpreter','none')
-        dyn_saveas(hfig,[fname '_pred'],options_.nodisplay,options_.graph_format);
+        dyn_saveas(hh_fig,[fname '_pred'],options_.nodisplay,options_.graph_format);
         create_TeX_loader(options_,[fname '_pred'],options_map.title,[namy,' vs ', namx,' pred'])
 
     end
@@ -762,7 +762,7 @@ return
 
 function indmcf = redform_mcf(y0, x0, options_mcf, options_)
 
-hfig=dyn_figure(options_.nodisplay,'name',options_mcf.amcf_title);
+hh_fig=dyn_figure(options_.nodisplay,'name',options_mcf.amcf_title);
 
 [post_mean, post_median, post_var, hpd_interval, post_deciles, ...
  density] = posterior_moments(y0,1,0.9);
@@ -813,7 +813,7 @@ if ~isoctave
                'horizontalalignment','center');
 end
 
-dyn_saveas(hfig,[options_mcf.OutputDirectoryName filesep options_mcf.fname_,'_',options_mcf.amcf_name],options_.nodisplay,options_.graph_format);
+dyn_saveas(hh_fig,[options_mcf.OutputDirectoryName filesep options_mcf.fname_,'_',options_mcf.amcf_name],options_.nodisplay,options_.graph_format);
 create_TeX_loader(options_,[options_mcf.OutputDirectoryName filesep options_mcf.fname_,'_',options_mcf.amcf_name],strrep(options_mcf.amcf_title,'_','\_'),[options_mcf.fname_,'_',options_mcf.amcf_name])
 
 return
diff --git a/matlab/gsa/redform_screen.m b/matlab/gsa/redform_screen.m
index 704923f9c57a734a9aa912645d829c819df7d41b..c7cb31d4b027fc7dada348b9bf8e08de8100fb7c 100644
--- a/matlab/gsa/redform_screen.m
+++ b/matlab/gsa/redform_screen.m
@@ -11,7 +11,7 @@ function redform_screen(dirname, options_gsa_)
 % marco.ratto@ec.europa.eu
 
 % Copyright © 2012-2016 European Commission
-% Copyright © 2012-2018 Dynare Team
+% Copyright © 2012-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -66,7 +66,7 @@ for j=1:size(anamendo,1)
             if ~isempty(y0)
                 if mod(iplo,9)==0
                     ifig = ifig+1;
-                    hh = dyn_figure(options_.nodisplay, 'name', [namendo,[' vs. shocks '], int2str(ifig)]);
+                    hh_fig = dyn_figure(options_.nodisplay, 'name', [namendo,[' vs. shocks '], int2str(ifig)]);
                     iplo = 0;
                 end
                 iplo = iplo+1;
@@ -84,7 +84,7 @@ for j=1:size(anamendo,1)
                 end
                 title([namendo,' vs. ',namexo],'interpreter','none')
                 if iplo==9
-                    dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],options_.nodisplay,options_.graph_format);
+                    dyn_saveas(hh_fig,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],options_.nodisplay,options_.graph_format);
                     create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],ifig,[namendo,' vs. shocks ',int2str(ifig)],[namendo,'_vs_shock'],1)
                 end
 
@@ -92,7 +92,7 @@ for j=1:size(anamendo,1)
         end
     end
     if iplo<9 && iplo>0 && ifig
-        dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_shocks_',num2str(ifig)],options_.nodisplay,options_.graph_format);
+        dyn_saveas(hh_fig,[dirname,'/',M_.fname,'_', namendo,'_vs_shocks_',num2str(ifig)],options_.nodisplay,options_.graph_format);
         create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_shock_',num2str(ifig)],ifig,[namendo,' vs. shocks ',int2str(ifig)],[namendo,'_vs_shock'],options_.figures.textwidth*min(iplo/3))
     end
 
@@ -107,7 +107,7 @@ for j=1:size(anamendo,1)
             if ~isempty(y0)
                 if mod(iplo,9)==0
                     ifig=ifig+1;
-                    hh=dyn_figure(options_.nodisplay,'name',[namendo,' vs. lagged endogenous ',int2str(ifig)]);
+                    hh_fig=dyn_figure(options_.nodisplay,'name',[namendo,' vs. lagged endogenous ',int2str(ifig)]);
                     iplo=0;
                 end
                 iplo=iplo+1;
@@ -127,19 +127,19 @@ for j=1:size(anamendo,1)
 
                 title([namendo,' vs. ',namlagendo,'(-1)'],'interpreter','none')
                 if iplo==9
-                    dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],options_.nodisplay,options_.graph_format);
+                    dyn_saveas(hh_fig,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],options_.nodisplay,options_.graph_format);
                     create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],ifig,[namendo,' vs. lagged endogenous ',int2str(ifig)],[namendo,'_vs_lags'],1)
                 end
             end
         end
     end
     if iplo<9 && iplo>0 && ifig
-        dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],options_.nodisplay,options_.graph_format);
+        dyn_saveas(hh_fig,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],options_.nodisplay,options_.graph_format);
         create_TeX_loader(options_,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],ifig,[namendo,' vs. lagged endogenous ',int2str(ifig)],[namendo,'_vs_lags'],options_.figures.textwidth*min(iplo/3))
     end
 end
 
-hh=dyn_figure(options_.nodisplay,'Name','Reduced form screening');
+hh_fig=dyn_figure(options_.nodisplay,'Name','Reduced form screening');
 %bar(SA)
 % boxplot(SA','whis',10,'symbol','r.')
 myboxplot(SA',[],'.',[],10)
@@ -153,7 +153,7 @@ end
 xlabel(' ')
 ylabel('Elementary Effects')
 title('Reduced form screening')
-dyn_saveas(hh,[dirname,'/',M_.fname,'_redform_screen'],options_.nodisplay,options_.graph_format);
+dyn_saveas(hh_fig,[dirname,'/',M_.fname,'_redform_screen'],options_.nodisplay,options_.graph_format);
 create_TeX_loader(options_,[dirname,'/',M_.fname,'_redform_screen'],1,'Reduced form screening','redform_screen',1)
 
 
diff --git a/matlab/gsa/scatter_mcf.m b/matlab/gsa/scatter_mcf.m
index 8aaa96d858de6eec8bbe9e142c50fb6a4e10a559..d0c34394859b1751970674991a7a71f8398dbb9e 100644
--- a/matlab/gsa/scatter_mcf.m
+++ b/matlab/gsa/scatter_mcf.m
@@ -5,7 +5,7 @@ function  scatter_mcf(X,Y,vnames,plotsymbol, fnam, dirname, figtitle, xparam1, D
 % marco.ratto@ec.europa.eu
 
 % Copyright © 2014-2016 European Commission
-% Copyright © 2014-2017 Dynare Team
+% Copyright © 2014-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -84,7 +84,7 @@ figtitle_tex=strrep(figtitle,'_','\_');
 
 fig_nam_=[fnam];
 if ~nograph
-    hh=dyn_figure(DynareOptions.nodisplay,'name',figtitle);
+    hh_fig=dyn_figure(DynareOptions.nodisplay,'name',figtitle);
 end
 
 bf = 0.1;
@@ -166,7 +166,7 @@ if ~isoctave
 end
 
 if ~nograph
-    dyn_saveas(hh,[dirname,filesep,fig_nam_],DynareOptions.nodisplay,DynareOptions.graph_format);
+    dyn_saveas(hh_fig,[dirname,filesep,fig_nam_],DynareOptions.nodisplay,DynareOptions.graph_format);
     if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
         fidTeX = fopen([dirname,'/',fig_nam_ '.tex'],'w');
         fprintf(fidTeX,'%% TeX eps-loader file generated by scatter_mcf.m (Dynare).\n');
diff --git a/matlab/gsa/scatter_plots.m b/matlab/gsa/scatter_plots.m
index 9fbcf2f261771490a34942e8e09239514a9a0dcf..2a0d989aae118d4328cc30f92cf4ffbca9e577c2 100644
--- a/matlab/gsa/scatter_plots.m
+++ b/matlab/gsa/scatter_plots.m
@@ -6,7 +6,7 @@ function scatter_plots(X,xp,vnames,plotsymbol, fnam, dirname, figtitle, xparam1,
 %
 
 % Copyright © 2017 European Commission
-% Copyright © 2017 Dynare Team
+% Copyright © 2017-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -73,8 +73,8 @@ figtitle_tex=strrep(figtitle,'_','\_');
 
 fig_nam_=[fnam];
 
-hh=dyn_figure(DynareOptions.nodisplay,'name',figtitle);
-set(hh,'userdata',{X,xp})
+hh_fig=dyn_figure(DynareOptions.nodisplay,'name',figtitle);
+set(hh_fig,'userdata',{X,xp})
 
 bf = 0.1;
 ffs = 0.05/(p-1);
@@ -172,7 +172,7 @@ end
 % end
 
 if ~nograph
-    dyn_saveas(hh,[dirname,filesep,fig_nam_],DynareOptions.nodisplay,DynareOptions.graph_format);
+    dyn_saveas(hh_fig,[dirname,filesep,fig_nam_],DynareOptions.nodisplay,DynareOptions.graph_format);
     if DynareOptions.TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
         fidTeX = fopen([dirname,'/',fig_nam_ '.tex'],'w');
         fprintf(fidTeX,'%% TeX eps-loader file generated by scatter_plots.m (Dynare).\n');
diff --git a/matlab/gsa/stab_map_1.m b/matlab/gsa/stab_map_1.m
index 7b47bc2f0b135faf94b6e09ee0113f5bf31895b7..f1ba4422f9f0c25dc9c9341e0a12958812d623fe 100644
--- a/matlab/gsa/stab_map_1.m
+++ b/matlab/gsa/stab_map_1.m
@@ -21,7 +21,7 @@ function [proba, dproba] = stab_map_1(lpmat, ibehaviour, inonbehaviour, aname, i
 % marco.ratto@ec.europa.eu
 
 % Copyright © 2012-2016 European Commission
-% Copyright © 2012-2017 Dynare Team
+% Copyright © 2012-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -82,7 +82,7 @@ if iplot && ~options_.nograph
     ftit=bayestopt_.name(ipar+nshock*(1-ishock));
 
     for i=1:ceil(nparplot/12)
-        hh=dyn_figure(options_.nodisplay,'name',atitle);
+        hh_fig=dyn_figure(options_.nodisplay,'name',atitle);
         for j=1+12*(i-1):min(nparplot,12*i)
             subplot(3,4,j-12*(i-1))
             if ~isempty(ibehaviour)
@@ -98,7 +98,7 @@ if iplot && ~options_.nograph
             title([ftit{j},'. p-value ', num2str(proba(ipar(j)),2)],'interpreter','none')
         end
         if nparplot>12
-            dyn_saveas(hh,[dirname,filesep,fname_,'_',aname,'_SA_',int2str(i)],options_.nodisplay,options_.graph_format);
+            dyn_saveas(hh_fig,[dirname,filesep,fname_,'_',aname,'_SA_',int2str(i)],options_.nodisplay,options_.graph_format);
             if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                 fidTeX = fopen([dirname,filesep,fname_,'_',aname,'_SA_',int2str(i) '.tex'],'w');
                 fprintf(fidTeX,'%% TeX eps-loader file generated by stab_map_1.m (Dynare).\n');
@@ -113,7 +113,7 @@ if iplot && ~options_.nograph
                 fclose(fidTeX);
             end
         else
-            dyn_saveas(hh,[dirname,filesep,fname_,'_',aname,'_SA'],options_.nodisplay,options_.graph_format);
+            dyn_saveas(hh_fig,[dirname,filesep,fname_,'_',aname,'_SA'],options_.nodisplay,options_.graph_format);
             if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                 fidTeX = fopen([dirname,filesep,fname_,'_',aname,'_SA.tex'],'w');
                 fprintf(fidTeX,'%% TeX eps-loader file generated by stab_map_1.m (Dynare).\n');
diff --git a/matlab/gsa/stab_map_2.m b/matlab/gsa/stab_map_2.m
index 3e6e508c18ee127c6ef6569118e3e991be62a2e9..50a33603f6725787cc03b9449699967f55245ca2 100644
--- a/matlab/gsa/stab_map_2.m
+++ b/matlab/gsa/stab_map_2.m
@@ -6,7 +6,7 @@ function indcorr = stab_map_2(x,alpha2, pvalue_crit, fnam, dirname,xparam1,figti
 % marco.ratto@ec.europa.eu
 
 % Copyright © 2011-2016 European Commission
-% Copyright © 2011-2018 Dynare Team
+% Copyright © 2011-2023 Dynare Team
 % This file is part of Dynare.
 %
 % Dynare is free software: you can redistribute it and/or modify
@@ -118,7 +118,7 @@ for j=1:npar
                 if ~nograph
                     if mod(j2,12)==1
                         ifig=ifig+1;
-                        hh=dyn_figure(options_.nodisplay,'name',[figtitle,' sample bivariate projection ', num2str(ifig)]);
+                        hh_fig=dyn_figure(options_.nodisplay,'name',[figtitle,' sample bivariate projection ', num2str(ifig)]);
                     end
                     subplot(3,4,j2-(ifig-1)*12)
                     %             bar(c0(i2,j)),
@@ -141,7 +141,7 @@ for j=1:npar
                     end
                     title(['cc = ',num2str(c0(i2(jx),j))])
                     if (mod(j2,12)==0) && j2>0
-                        dyn_saveas(hh,[dirname,filesep,fig_nam_,int2str(ifig)],options_.nodisplay,options_.graph_format);
+                        dyn_saveas(hh_fig,[dirname,filesep,fig_nam_,int2str(ifig)],options_.nodisplay,options_.graph_format);
                         if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                             fidTeX = fopen([dirname,filesep,fig_nam_,int2str(ifig),'.tex'],'w');
                             fprintf(fidTeX,'%% TeX eps-loader file generated by stab_map_2.m (Dynare).\n');
@@ -162,7 +162,7 @@ for j=1:npar
         end
     end
     if ~nograph && (j==(npar)) && j2>0 && (mod(j2,12)~=0)
-        dyn_saveas(hh,[dirname,filesep,fig_nam_,int2str(ifig)],options_.nodisplay,options_.graph_format);
+        dyn_saveas(hh_fig,[dirname,filesep,fig_nam_,int2str(ifig)],options_.nodisplay,options_.graph_format);
         if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
             fidTeX = fopen([dirname,filesep,fig_nam_,int2str(ifig),'.tex'],'w');
             fprintf(fidTeX,'%% TeX eps-loader file generated by stab_map_2.m (Dynare).\n');
diff --git a/matlab/marginal_density.m b/matlab/marginal_density.m
index 2f8c45bd76d9565c84d26a57ec804fc0dd9d253e..e9e203686446efbe86053e847b6c7627e83a0b7c 100644
--- a/matlab/marginal_density.m
+++ b/matlab/marginal_density.m
@@ -1,5 +1,5 @@
-function [marginal,oo_] = marginal_density(M_, options_, estim_params_, oo_, bayestopt_)
-% function [marginal,oo_] = marginal_density(M_, options_, estim_params_, oo_, bayestopt_)
+function [marginal,oo_] = marginal_density(M_, options_, estim_params_, oo_, bayestopt_, outputFolderName)
+% function [marginal,oo_] = marginal_density(M_, options_, estim_params_, oo_, bayestopt_, outputFolderName)
 % Computes the marginal density
 %
 % INPUTS
@@ -7,6 +7,7 @@ function [marginal,oo_] = marginal_density(M_, options_, estim_params_, oo_, bay
 %   estim_params_    [structure]    Dynare estimation parameter structure
 %   M_               [structure]    Dynare model structure
 %   oo_              [structure]    Dynare results structure
+%   outputFolderName [string]       name of folder with results
 %
 % OUTPUTS
 %   marginal:        [double]       marginal density (modified harmonic mean)
@@ -31,7 +32,9 @@ function [marginal,oo_] = marginal_density(M_, options_, estim_params_, oo_, bay
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
-
+if nargin < 6
+    outputFolderName = 'Output';
+end
 
 MetropolisFolder = CheckPath('metropolis',M_.dname);
 ModelName = M_.fname;
@@ -47,8 +50,8 @@ TotalNumberOfMhFiles = sum(record.MhDraws(:,2));
 TotalNumberOfMhDraws = sum(record.MhDraws(:,1));
 TODROP = floor(options_.mh_drop*TotalNumberOfMhDraws);
 
-fprintf('Estimation::marginal density: I''m computing the posterior mean and covariance... ');
-[posterior_mean,posterior_covariance,posterior_mode,posterior_kernel_at_the_mode] = compute_mh_covariance_matrix(bayestopt_,M_.fname,M_.dname);
+fprintf('marginal density: I''m computing the posterior mean and covariance... ');
+[posterior_mean,posterior_covariance,posterior_mode,posterior_kernel_at_the_mode] = compute_mh_covariance_matrix(bayestopt_,M_.fname,M_.dname,outputFolderName);
 
 MU = transpose(posterior_mean);
 SIGMA = posterior_covariance;
@@ -64,16 +67,16 @@ end
 % (usefull if the user wants to perform some computations using
 % the posterior mean instead of the posterior mode ==> ).
 parameter_names = bayestopt_.name;
-save([M_.dname filesep 'Output' filesep M_.fname '_mean.mat'],'xparam1','hh','parameter_names','SIGMA');
+save([M_.dname filesep outputFolderName filesep M_.fname '_mean.mat'],'xparam1','hh','parameter_names','SIGMA');
 
-fprintf('Estimation::marginal density: I''m computing the posterior log marginal density (modified harmonic mean)... ');
+fprintf('marginal density: I''m computing the posterior log marginal density (modified harmonic mean)... ');
 try 
     % use this robust option to avoid inf/nan
     logdetSIGMA = 2*sum(log(diag(chol(SIGMA)))); 
 catch
     % in case SIGMA is not positive definite
     logdetSIGMA = nan;
-    fprintf('Estimation::marginal density: the covariance of MCMC draws is not positive definite. You may have too few MCMC draws.');
+    fprintf('marginal density: the covariance of MCMC draws is not positive definite. You may have too few MCMC draws.');
 end
 invSIGMA = hh;
 marginal = zeros(9,2);
@@ -108,18 +111,18 @@ while check_coverage
     if abs((marginal(9,2)-marginal(1,2))/marginal(9,2)) > options_.marginal_data_density.harmonic_mean.tolerance || isinf(marginal(1,2))
         fprintf('\n')
         if increase == 1
-            disp('Estimation::marginal density: The support of the weighting density function is not large enough...')
-            disp('Estimation::marginal density: I increase the variance of this distribution.')
+            disp('marginal density: The support of the weighting density function is not large enough...')
+            disp('marginal density: I increase the variance of this distribution.')
             increase = 1.2*increase;
             linee    = 0;
         else
-            disp('Estimation::marginal density: Let me try again.')
+            disp('marginal density: Let me try again.')
             increase = 1.2*increase;
             linee    = 0;
             if increase > 20
                 check_coverage = 0;
                 clear invSIGMA detSIGMA increase;
-                disp('Estimation::marginal density: There''s probably a problem with the modified harmonic mean estimator.')
+                disp('marginal density: There''s probably a problem with the modified harmonic mean estimator.')
             end
         end
     else
diff --git a/matlab/mh_autocorrelation_function.m b/matlab/mh_autocorrelation_function.m
index 8c07143bd1cd5e3289fedf18457d0bc737552d27..565c16504ce3a59621df6a1aebf967dc51f0a8d3 100644
--- a/matlab/mh_autocorrelation_function.m
+++ b/matlab/mh_autocorrelation_function.m
@@ -60,7 +60,7 @@ nblck = size(record.LastParameters,1);
 clear record;
 
 % Get all the posterior draws:
-PosteriorDraws = GetAllPosteriorDraws(column, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, nblck, blck);
+PosteriorDraws = GetAllPosteriorDraws(M_.dname, M_.fname, column, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, nblck, blck);
 
 % Compute the autocorrelation function:
 [autocov,autocor] = sample_autocovariance(PosteriorDraws,options_.mh_autocorrelation_function_size);
@@ -93,7 +93,7 @@ if options_.mh_nblck>1
     FigureName = [ FigureName , ' (block number' int2str(blck)  ').'];
 end
 
-hh=dyn_figure(options_.nodisplay,'Name',FigureName);
+hh_fig=dyn_figure(options_.nodisplay,'Name',FigureName);
 
 bar(0:options_.mh_autocorrelation_function_size,autocor,'k');
 axis tight
@@ -106,4 +106,4 @@ if ~exist([M_.dname filesep 'graphs'])
 end
 
 plot_name=get_the_name(column,0,M_,estim_params_,options_);
-dyn_saveas(hh,[M_.dname, filesep, 'graphs', filesep, 'MH_Autocorrelation_' plot_name],options_.nodisplay,options_.graph_format)
+dyn_saveas(hh_fig,[M_.dname, filesep, 'graphs', filesep, 'MH_Autocorrelation_' plot_name],options_.nodisplay,options_.graph_format)
diff --git a/matlab/missing_DiffuseKalmanSmootherH3_Z.m b/matlab/missing_DiffuseKalmanSmootherH3_Z.m
index a5894922aa5815144f5e6bdc7767a99d1611b16b..d863db5a38507bece3d6c444c65ae89c9a9c635e 100644
--- a/matlab/missing_DiffuseKalmanSmootherH3_Z.m
+++ b/matlab/missing_DiffuseKalmanSmootherH3_Z.m
@@ -64,7 +64,7 @@ function [alphahat,epsilonhat,etahat,a,P1,aK,PK,decomp,V, aalphahat,eetahat,d,al
 %   Models", S.J. Koopman and J. Durbin (2003), in Journal of Time Series
 %   Analysis, vol. 24(1), pp. 85-98.
 
-% Copyright © 2004-2021 Dynare Team
+% Copyright © 2004-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -315,8 +315,8 @@ if isoccbin
         % kalman update is not yet robust to accommodate diffuse steps
     end
     if occbin_options.opts_regime.waitbar
-        hh = dyn_waitbar(0,'Occbin: Piecewise Kalman Filter');
-        set(hh,'Name','Occbin: Piecewise Kalman Filter.');
+        hh_fig = dyn_waitbar(0,'Occbin: Piecewise Kalman Filter');
+        set(hh_fig,'Name','Occbin: Piecewise Kalman Filter.');
         waitbar_indicator=1;
     else
         waitbar_indicator=0;
@@ -346,7 +346,7 @@ while notsteady && t<smpl
     di = data_index{t}';
     if t>=first_period_occbin_update
         if waitbar_indicator
-            dyn_waitbar(t/smpl, hh, sprintf('Period %u of %u', t,smpl));
+            dyn_waitbar(t/smpl, hh_fig, sprintf('Period %u of %u', t,smpl));
         end
         occbin_options.opts_regime.waitbar=0;
         if t==1
@@ -530,7 +530,7 @@ while notsteady && t<smpl
     end
 end
 if waitbar_indicator
-    dyn_waitbar_close(hh);
+    dyn_waitbar_close(hh_fig);
 end
 
 P1(:,:,t+1) = P(:,:,t+1);
diff --git a/matlab/mode_check.m b/matlab/mode_check.m
index cefe990af4962a9326da78bfec139e3fc5110443..a7db27a108796e428e4a0812b49cba991b43f305 100644
--- a/matlab/mode_check.m
+++ b/matlab/mode_check.m
@@ -1,46 +1,32 @@
-function mode_check(fun,x,hessian_mat,DynareDataset,DatasetInfo,DynareOptions,Model,EstimatedParameters,BayesInfo,BoundsInfo,DynareResults)
-% Checks the estimated ML mode or Posterior mode.
+function mcheck = mode_check(fun,xparam,hessian_mat,options_,M_,estim_params_,bayestopt_,bounds,isMinimum, varargin)
+% function mcheck = mode_check(fun,xparam,hessian_mat,options_,M_,estim_params_,bayestopt_,bounds,isMinimum, varargin)
+% -------------------------------------------------------------------------
+% Checks the estimated ML or Posterior mode/minimum by plotting sections of
+% the likelihood/posterior kernel. Each plot shows the variation of the
+% function implied by the variations of a single parameter ( ceteris paribus)
+% -------------------------------------------------------------------------
+% INPUTS
+% - fun:            [func_handle]  objective function
+% - xparam:         [vector]       estimated mode/minimum
+% - hessian_mat:    [matrix]       hessian of the objective function at the estimated mode/minimum
+% - options_:       [structure]    Dynare options structure
+% - M_:             [structure]    Dynare model structure
+% - estim_params_:  [structure]    Dynare estimated parameters structure
+% - bayestopt_:     [structure]    information on the priors
+% - bounds:         [structure]    information on the bounds
+% - isMinimum:      [boolean]      true if xparam is a minimum, false if it is a mode
+% - varargin:       [cell]         additional arguments to be passed to fun
+% -------------------------------------------------------------------------
+% OUTPUTS
+% - mcheck: [structure]     structure containing the data for the check plots
+% - Saves the plots in the graphs folder and the data in a mat file
+% -------------------------------------------------------------------------
+% This function is called by
+% - dynare_estimation_1
+% - mom.run
+% -------------------------------------------------------------------------
 
-%@info:
-%! @deftypefn {Function File} mode_check (@var{fun}, @var{x}, @var{hessian_mat}, @var{DynareDataset}, @var{DynareOptions}, @var{Model}, @var{EstimatedParameters}, @var{BayesInfo}, @var{DynareResults})
-%! @anchor{mode_check}
-%! @sp 1
-%! Checks the estimated ML mode or Posterior mode by plotting sections of the likelihood/posterior kernel.
-%! Each plot shows the variation of the likelihood implied by the variations of a single parameter, ceteris paribus)
-%! @sp 2
-%! @strong{Inputs}
-%! @sp 1
-%! @table @ @var
-%! @item fun
-%! Objective function.
-%! @item x
-%! Estimated mode.
-%! @item start
-%! Hessian of the objective function at the estimated mode @var{x}.
-%! @item DynareDataset
-%! Structure specifying the dataset used for estimation (dataset_).
-%! @item DynareOptions
-%! Structure defining dynare's options (options_).
-%! @item Model
-%! Structure specifying the (estimated) model (M_).
-%! @item EstimatedParameters
-%! Structure specifying the estimated parameters (estimated_params_).
-%! @item BayesInfo
-%! Structure containing information about the priors used for estimation (bayestopt_).
-%! @item DynareResults
-%! Structure gathering the results (oo_).
-%! @end table
-%! @sp 2
-%! @strong{Outputs}
-%! @sp 2
-%! @strong{This function is called by:}
-%! @sp 2
-%! @strong{This function calls:}
-%! The objective function (@var{func}).
-%! @end deftypefn
-%@eod:
-
-% Copyright © 2003-2017 Dynare Team
+% Copyright © 2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -57,165 +43,188 @@ function mode_check(fun,x,hessian_mat,DynareDataset,DatasetInfo,DynareOptions,Mo
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
 
-TeX = DynareOptions.TeX;
-if ~isempty(hessian_mat)
-    [ s_min, k ] = min(diag(hessian_mat));
-end
+tolBounds = 1e-8;
 
-fval = feval(fun,x,DynareDataset,DatasetInfo,DynareOptions,Model,EstimatedParameters,BayesInfo,BoundsInfo,DynareResults);
+fval = feval(fun,xparam,varargin{:});
 
 if ~isempty(hessian_mat)
-    skipline()
-    disp('MODE CHECK')
-    skipline()
-    fprintf('Fval obtained by the minimization routine (minus the posterior/likelihood)): %f', fval);
-    skipline()
+    [ s_min, k ] = min(diag(hessian_mat));
+    if isMinimum
+        fprintf('\nMINIMUM CHECK\n\nFval obtained by the optimization routine: %f\n', fval)
+    else
+        fprintf('\nMODE CHECK\n\nFval obtained by the optimization routine: %f\n', fval)        
+    end
     if s_min<eps
-        disp(sprintf('Most negative variance %f for parameter %d (%s = %f)', s_min, k , BayesInfo.name{k}, x(k)))
+        fprintf('Most negative variance %f for parameter %d (%s = %f)\n', s_min, k , bayestopt_.name{k}, xparam(k));
     end
 end
 
-[nbplt,nr,nc,lr,lc,nstar] = pltorg(length(x));
+[nbplt,nr,nc,~,~,nstar] = pltorg(length(xparam));
 
-if ~exist([Model.dname filesep 'graphs'],'dir')
-    mkdir(Model.dname,'graphs');
-end
-if TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
-    fidTeX = fopen([Model.dname, '/graphs/', Model.fname '_CheckPlots.tex'],'w');
+graphsFolder = CheckPath('graphs',M_.dname);
+latexFolder = CheckPath('latex',M_.dname);
+
+if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
+    fidTeX = fopen([latexFolder filesep M_.fname '_CheckPlots.tex'],'w');
     fprintf(fidTeX,'%% TeX eps-loader file generated by mode_check.m (Dynare).\n');
     fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
     fprintf(fidTeX,' \n');
 end
 
-ll = DynareOptions.mode_check.neighbourhood_size;
+ll = options_.mode_check.neighbourhood_size;
 if isinf(ll)
-    DynareOptions.mode_check.symmetric_plots = false;
+    options_.mode_check.symmetric_plots = false;
 end
 
-mcheck = struct('cross',struct(),'emode',struct());
+if isMinimum
+    mcheck = struct('cross',struct(),'emin',struct());
+else
+    mcheck = struct('cross',struct(),'emode',struct());
+end
 
 for plt = 1:nbplt
-    if TeX
+    if options_.TeX
         NAMES = [];
         TeXNAMES = [];
     end
-    hh = dyn_figure(DynareOptions.nodisplay,'Name','Mode check plots');
-    for k=1:min(nstar,length(x)-(plt-1)*nstar)
+    if isMinimum
+        hh_fig = dyn_figure(options_.nodisplay,'Name','Minimum check plots');
+    else
+        hh_fig = dyn_figure(options_.nodisplay,'Name','Mode check plots');
+    end
+    for k = 1:min(nstar,length(xparam)-(plt-1)*nstar)
         subplot(nr,nc,k)
         kk = (plt-1)*nstar+k;
-        [name,texname] = get_the_name(kk,TeX,Model,EstimatedParameters,DynareOptions);
-        xx = x;
-        if x(kk)~=0 && ~isinf(BoundsInfo.lb(kk)) && ~isinf(BoundsInfo.ub(kk))
-            l1 = max(BoundsInfo.lb(kk),(1-sign(x(kk))*ll)*x(kk)); m1 = 0; %lower bound
-            l2 = min(BoundsInfo.ub(kk),(1+sign(x(kk))*ll)*x(kk)); %upper bound
+        [name,texname] = get_the_name(kk,options_.TeX,M_,estim_params_,options_);
+        xx = xparam;
+        if xparam(kk)~=0 && ~isinf(bounds.lb(kk)) && ~isinf(bounds.ub(kk))
+            l1 = max(bounds.lb(kk),(1-sign(xparam(kk))*ll)*xparam(kk)); m1 = 0; % lower bound
+            l2 = min(bounds.ub(kk),(1+sign(xparam(kk))*ll)*xparam(kk));         % upper bound
         else
-            %size info for 0 parameter is missing, use prior standard
-            %deviation
-            upper_bound=BoundsInfo.lb(kk);
+            % size info for 0 parameter is missing, use prior standard deviation
+            upper_bound = bounds.lb(kk);
             if isinf(upper_bound)
-                upper_bound=-1e-6*DynareOptions.huge_number;
+                upper_bound = -1e-6*options_.huge_number;
             end
-            lower_bound=BoundsInfo.ub(kk);
+            lower_bound = bounds.ub(kk);
             if isinf(lower_bound)
-                lower_bound=-1e-6*DynareOptions.huge_number;
+                lower_bound = -1e-6*options_.huge_number;
             end
-            l1 = max(lower_bound,-BayesInfo.p2(kk)); m1 = 0; %lower bound
-            l2 = min(upper_bound,BayesInfo.p2(kk)); %upper bound
+            l1 = max(lower_bound,-bayestopt_.p2(kk)); m1 = 0; % lower bound
+            l2 = min(upper_bound,bayestopt_.p2(kk));          % upper bound
         end
-        binding_lower_bound=0;
-        binding_upper_bound=0;
-        if abs(x(kk)-BoundsInfo.lb(kk))<1e-8
-            binding_lower_bound=1;
-            bound_value=BoundsInfo.lb(kk);
-        elseif abs(x(kk)-BoundsInfo.ub(kk))<1e-8
-            binding_upper_bound=1;
-            bound_value=BoundsInfo.ub(kk);
+        binding_lower_bound = 0;
+        binding_upper_bound = 0;
+        if abs(xparam(kk)-bounds.lb(kk))<tolBounds
+            binding_lower_bound = 1;
+            bound_value = bounds.lb(kk);
+        elseif abs(xparam(kk)-bounds.ub(kk))<tolBounds
+            binding_upper_bound = 1;
+            bound_value = bounds.ub(kk);
         end
-        if DynareOptions.mode_check.symmetric_plots && ~binding_lower_bound && ~binding_upper_bound
-            if l2<(1+ll)*x(kk) %test whether upper bound is too small due to prior binding
-                l1 = x(kk) - (l2-x(kk)); %adjust lower bound to become closer
+        if options_.mode_check.symmetric_plots && ~binding_lower_bound && ~binding_upper_bound
+            if l2<(1+ll)*xparam(kk) % test whether upper bound is too small due to prior binding
+                l1 = xparam(kk) - (l2-xparam(kk)); % adjust lower bound to become closer
                 m1 = 1;
             end
-            if ~m1 && (l1>(1-ll)*x(kk)) && (x(kk)+(x(kk)-l1)<BoundsInfo.ub(kk)) % if lower bound was truncated and using difference from lower bound does not violate upper bound
-                l2 = x(kk) + (x(kk)-l1); %set upper bound to same distance as lower bound
+            if ~m1 && (l1>(1-ll)*xparam(kk)) && (xparam(kk)+(xparam(kk)-l1)<bounds.ub(kk)) % if lower bound was truncated and using difference from lower bound does not violate upper bound
+                l2 = xparam(kk) + (xparam(kk)-l1); % set upper bound to same distance as lower bound
             end
         end
-        z1 = l1:((x(kk)-l1)/(DynareOptions.mode_check.number_of_points/2)):x(kk);
-        z2 = x(kk):((l2-x(kk))/(DynareOptions.mode_check.number_of_points/2)):l2;
+        z1 = l1:((xparam(kk)-l1)/(options_.mode_check.number_of_points/2)):xparam(kk);
+        z2 = xparam(kk):((l2-xparam(kk))/(options_.mode_check.number_of_points/2)):l2;
         z  = union(z1,z2);
-        if ~DynareOptions.mode_check.nolik
+        if ~options_.mode_check.nolik
             y = zeros(length(z),2);
-            dy = priordens(xx,BayesInfo.pshape,BayesInfo.p6,BayesInfo.p7,BayesInfo.p3,BayesInfo.p4);
+            if isfield(options_,'mom') && ( (strcmp(options_.mom.mom_method,'GMM') || strcmp(options_.mom.mom_method,'SMM')) && options_.mom.penalized_estimator )
+                dy = (xx-bayestopt_.p1)'/diag(bayestopt_.p2.^2)*(xx-bayestopt_.p1);
+            else
+                dy = priordens(xx,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4);
+            end
         end
-        for i=1:length(z)
+        for i = 1:length(z)
             xx(kk) = z(i);
-            [fval, info, exit_flag] = feval(fun,xx,DynareDataset,DatasetInfo,DynareOptions,Model,EstimatedParameters,BayesInfo,BoundsInfo,DynareResults);
+            [fval, info, exit_flag] = feval(fun,xx, varargin{:});                
             if exit_flag
                 y(i,1) = fval;
             else
                 y(i,1) = NaN;
-                if DynareOptions.debug
-                    fprintf('mode_check:: could not solve model for parameter %s at value %4.3f, error code: %u (%s)\n',name,z(i),info(1),get_error_message(info, DynareOptions))
+                if options_.debug
+                    fprintf('mode_check:: could not solve model for parameter %s at value %4.3f, error code: %u (%s)\n',name,z(i),info(1),get_error_message(info, options_));
                 end
             end
-            if ~DynareOptions.mode_check.nolik
-                lnprior = priordens(xx,BayesInfo.pshape,BayesInfo.p6,BayesInfo.p7,BayesInfo.p3,BayesInfo.p4);
+            if ~options_.mode_check.nolik
+                if isfield(options_,'mom') && ( (strcmp(options_.mom.mom_method,'GMM') || strcmp(options_.mom.mom_method,'SMM')) && options_.mom.penalized_estimator )
+                    lnprior = (xx-bayestopt_.p1)'/diag(bayestopt_.p2.^2)*(xx-bayestopt_.p1);
+                else
+                    lnprior = priordens(xx,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4);
+                end
                 y(i,2)  = (y(i,1)+lnprior-dy);
             end
         end
-        mcheck.cross = setfield(mcheck.cross, name, [transpose(z), -y]);
-        mcheck.emode = setfield(mcheck.emode, name, x(kk));
-        fighandle=plot(z,-y);
+        if isMinimum
+            mcheck.cross = setfield(mcheck.cross, name, [transpose(z), y]); % keep y
+            mcheck.emin = setfield(mcheck.emin, name, xparam(kk));          % store as min
+            fighandle = plot(z,y);
+        else
+            mcheck.cross = setfield(mcheck.cross, name, [transpose(z), -y]); % multiply y by -1
+            mcheck.emode = setfield(mcheck.emode, name, xparam(kk));         % store as mode
+            fighandle = plot(z,-y);
+        end        
         hold on
-        yl=get(gca,'ylim');
-        plot( [x(kk) x(kk)], yl, 'c', 'LineWidth', 1)
+        yl = get(gca,'ylim');
+        plot( [xparam(kk) xparam(kk)], yl, 'c', 'LineWidth', 1);
         NaN_index = find(isnan(y(:,1)));
         zNaN = z(NaN_index);
         yNaN = yl(1)*ones(size(NaN_index));
         plot(zNaN,yNaN,'o','MarkerEdgeColor','r','MarkerFaceColor','r','MarkerSize',6);
-        if TeX
+        if options_.TeX
             title(texname,'interpreter','latex')
         else
             title(name,'interpreter','none')
         end
-
         axis tight
         if binding_lower_bound || binding_upper_bound
-            xl=get(gca,'xlim');
-            plot( [bound_value bound_value], yl, 'r--', 'LineWidth', 1)
-            xlim([xl(1)-0.5*binding_lower_bound*(xl(2)-xl(1)) xl(2)+0.5*binding_upper_bound*(xl(2)-xl(1))])
+            xl = get(gca,'xlim');
+            plot( [bound_value bound_value], yl, 'r--', 'LineWidth', 1);
+            xlim([xl(1)-0.5*binding_lower_bound*(xl(2)-xl(1)) xl(2)+0.5*binding_upper_bound*(xl(2)-xl(1))]);
         end
         hold off
         drawnow
     end
-    if ~DynareOptions.mode_check.nolik
+    if ~options_.mode_check.nolik
         if isoctave
-            axes('outerposition',[0.3 0.93 0.42 0.07],'box','on'),
+            axes('outerposition',[0.3 0.93 0.42 0.07],'box','on');
         else
-            axes('position',[0.3 0.01 0.42 0.05],'box','on'),
+            axes('position',[0.3 0.01 0.42 0.05],'box','on');
         end
         line_color=get(fighandle,'color');
-        plot([0.48 0.68],[0.5 0.5],'color',line_color{2})
-        hold on, plot([0.04 0.24],[0.5 0.5],'color',line_color{1})
-        set(gca,'xlim',[0 1],'ylim',[0 1],'xtick',[],'ytick',[])
-        text(0.25,0.5,'log-post')
-        text(0.69,0.5,'log-lik kernel')
+        plot([0.48 0.68],[0.5 0.5],'color',line_color{2});
+        hold on;
+        plot([0.04 0.24],[0.5 0.5],'color',line_color{1});
+        set(gca,'xlim',[0 1],'ylim',[0 1],'xtick',[],'ytick',[]);
+        if isMinimum
+            text(0.25,0.5,'log-post');
+            text(0.69,0.5,'log-dist kernel');
+        else
+            text(0.25,0.5,'log-post');
+            text(0.69,0.5,'log-lik kernel');
+        end
     end
-    dyn_saveas(hh,[Model.dname, '/graphs/', Model.fname '_CheckPlots' int2str(plt) ],DynareOptions.nodisplay,DynareOptions.graph_format);
-    if TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
+    dyn_saveas(hh_fig,[graphsFolder filesep M_.fname '_CheckPlots' int2str(plt) ],options_.nodisplay,options_.graph_format);
+    if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
         % TeX eps loader file
         fprintf(fidTeX,'\\begin{figure}[H]\n');
         fprintf(fidTeX,'\\centering \n');
-        fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_CheckPlots%s}\n',DynareOptions.figures.textwidth*min(k/nc,1),[Model.dname, '/graphs/',Model.fname],int2str(plt));
+        fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_CheckPlots%s}\n',options_.figures.textwidth*min(k/nc,1),[graphsFolder filesep M_.fname],int2str(plt));
         fprintf(fidTeX,'\\caption{Check plots.}');
         fprintf(fidTeX,'\\label{Fig:CheckPlots:%s}\n',int2str(plt));
         fprintf(fidTeX,'\\end{figure}\n');
         fprintf(fidTeX,' \n');
     end
 end
-if TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
+if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
     fclose(fidTeX);
 end
 
-OutputDirectoryName = CheckPath('modecheck',Model.dname);
-save([OutputDirectoryName '/check_plot_data.mat'],'mcheck');
+save([graphsFolder filesep M_.fname '_check_plot_data.mat'],'mcheck');
\ No newline at end of file
diff --git a/matlab/nonlinear-filters/online_auxiliary_filter.m b/matlab/nonlinear-filters/online_auxiliary_filter.m
index bbfb21e3e5f9c6b1059f9c93207d2584d4ae01bd..f81469e6c00d83ef48bf175d4a2d008087caa7a5 100644
--- a/matlab/nonlinear-filters/online_auxiliary_filter.m
+++ b/matlab/nonlinear-filters/online_auxiliary_filter.m
@@ -21,7 +21,7 @@ function [pmean, pmode, pmedian, pstdev, p025, p975, covariance] = online_auxili
 % - p975                     [double]    n×1 vector, 97.5 percent of the particles are below p975(i) for i=1,…,n.
 % - covariance               [double]    n×n matrix, covariance of the particles at the end of the sample.
 
-% Copyright © 2013-2022 Dynare Team
+% Copyright © 2013-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -386,7 +386,7 @@ if TeX
 end
 
 for plt = 1:nbplt
-    hh = dyn_figure(DynareOptions.nodisplay,'Name','Parameters Trajectories');
+    hh_fig = dyn_figure(DynareOptions.nodisplay,'Name','Parameters Trajectories');
     for k=1:length(pmean)
         subplot(nr,nc,k)
         [name,texname] = get_the_name(k,TeX,Model,EstimatedParameters,DynareOptions);
@@ -405,7 +405,7 @@ for plt = 1:nbplt
         axis tight
         drawnow
     end
-    dyn_saveas(hh, [Model.fname '_param_traj' int2str(plt)], DynareOptions.nodisplay, DynareOptions.graph_format);
+    dyn_saveas(hh_fig, [Model.fname '_param_traj' int2str(plt)], DynareOptions.nodisplay, DynareOptions.graph_format);
     if TeX
         % TeX eps loader file
         fprintf(fidTeX,'\\begin{figure}[H]\n');
@@ -423,7 +423,7 @@ number_of_grid_points = 2^9;      % 2^9 = 512 !... Must be a power of two.
 bandwidth = 0;                    % Rule of thumb optimal bandwidth parameter.
 kernel_function = 'gaussian';     % Gaussian kernel for Fast Fourier Transform approximation.
 for plt = 1:nbplt
-    hh = dyn_figure(DynareOptions.nodisplay,'Name','Parameters Densities');
+    hh_fig = dyn_figure(DynareOptions.nodisplay,'Name','Parameters Densities');
     for k=1:length(pmean)
         subplot(nr,nc,k)
         [name,texname] = get_the_name(k,TeX,Model,EstimatedParameters,DynareOptions);
@@ -441,7 +441,7 @@ for plt = 1:nbplt
         axis tight
         drawnow
     end
-    dyn_saveas(hh,[ Model.fname '_param_density' int2str(plt) ],DynareOptions.nodisplay,DynareOptions.graph_format);
+    dyn_saveas(hh_fig,[ Model.fname '_param_density' int2str(plt) ],DynareOptions.nodisplay,DynareOptions.graph_format);
     if TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
         % TeX eps loader file
         fprintf(fidTeX, '\\begin{figure}[H]\n');
diff --git a/matlab/olsgibbs.m b/matlab/olsgibbs.m
index 66fce0ea87d533a59af2405e9b87ef54b02e1e09..6d1590cb70abe7e738f4853b3e147c5193997008 100644
--- a/matlab/olsgibbs.m
+++ b/matlab/olsgibbs.m
@@ -30,7 +30,7 @@ function ds = olsgibbs(ds, eqtag, BetaPriorExpectation, BetaPriorVariance, s2, n
 % SPECIAL REQUIREMENTS
 %   dynare must have been run with the option: json=compute
 
-% Copyright © 2018-2021 Dynare Team
+% Copyright © 2018-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -183,11 +183,11 @@ for i=1:discarddraws
     h = gamrnd(PosteriorDegreesOfFreedom/2.0, 2.0/(PosteriorDegreesOfFreedom*s2_));
 end
 
-hh = dyn_waitbar(0,'Please wait. Gibbs sampler...');
-set(hh,'Name','Olsgibbs estimation.');
+hh_fig = dyn_waitbar(0,'Please wait. Gibbs sampler...');
+set(hh_fig,'Name','Olsgibbs estimation.');
 for i = discarddraws+1:ndraws
     if ~mod(i,10)
-        dyn_waitbar((i-discarddraws)/(ndraws-discarddraws),hh,'Please wait. Gibbs sampler...');
+        dyn_waitbar((i-discarddraws)/(ndraws-discarddraws),hh_fig,'Please wait. Gibbs sampler...');
     end
     % Set conditional distribution of β
     InverseConditionalPoseriorVariance = BetaInversePriorVariance + h*(X'*X);
@@ -211,7 +211,7 @@ for i = discarddraws+1:ndraws
         periods = periods+1;
     end
 end
-dyn_waitbar_close(hh);
+dyn_waitbar_close(hh_fig);
 
 %% Save posterior moments.
 oo_.olsgibbs.(model_name).posterior.mean.beta = mean(oo_.olsgibbs.(model_name).draws(:,1:n))';
diff --git a/matlab/optimization/gmhmaxlik_core.m b/matlab/optimization/gmhmaxlik_core.m
index 805516f1d1c14ae37ec38496e4afc97f8813f78e..c75a946eb78e4a90d07abebd84f086798182ff36 100644
--- a/matlab/optimization/gmhmaxlik_core.m
+++ b/matlab/optimization/gmhmaxlik_core.m
@@ -56,7 +56,7 @@ function [PostMod,PostVar,Scale,PostMean] = gmhmaxlik_core(ObjFun,xparam1,mh_bou
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright © 2006-2017 Dynare Team
+% Copyright © 2006-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -87,8 +87,8 @@ CovJump = VarCov;
 ModePar = xparam1;
 
 %% [1] I tune the scale parameter.
-hh = dyn_waitbar(0,'Tuning of the scale parameter...');
-set(hh,'Name','Tuning of the scale parameter.');
+hh_fig = dyn_waitbar(0,'Tuning of the scale parameter...');
+set(hh_fig,'Name','Tuning of the scale parameter.');
 j = 1; jj  = 1;
 isux = 0; jsux = 0; test = 0;
 ix2 = ModePar;% initial condition!
@@ -119,7 +119,7 @@ while j<=MaxNumberOfTuningSimulations
     end % ... otherwise I don't move.
     prtfrc = j/MaxNumberOfTuningSimulations;
     if mod(j, 10)==0
-        dyn_waitbar(prtfrc,hh,sprintf('Acceptance ratio [during last 500]: %f [%f]',isux/j,jsux/jj));
+        dyn_waitbar(prtfrc,hh_fig,sprintf('Acceptance ratio [during last 500]: %f [%f]',isux/j,jsux/jj));
     end
     if  j/500 == round(j/500)
         test1 = jsux/jj;
@@ -141,10 +141,10 @@ while j<=MaxNumberOfTuningSimulations
     jj = jj + 1;
 end
 
-dyn_waitbar_close(hh);
+dyn_waitbar_close(hh_fig);
 %% [2] One block metropolis, I update the covariance matrix of the jumping distribution
-hh = dyn_waitbar(0,'Metropolis-Hastings...');
-set(hh,'Name','Estimation of the posterior covariance...'),
+hh_fig = dyn_waitbar(0,'Metropolis-Hastings...');
+set(hh_fig,'Name','Estimation of the posterior covariance...'),
 j = 1;
 isux = 0;
 ilogpo2 = - feval(ObjFun,ix2,varargin{:});
@@ -169,7 +169,7 @@ while j<= NumberOfIterations
     end % ... otherwise I don't move.
     prtfrc = j/NumberOfIterations;
     if mod(j, 10)==0
-        dyn_waitbar(prtfrc,hh,sprintf('Acceptance ratio: %f',isux/j));
+        dyn_waitbar(prtfrc,hh_fig,sprintf('Acceptance ratio: %f',isux/j));
     end
     % I update the covariance matrix and the mean:
     oldMeanPar = MeanPar;
@@ -177,7 +177,7 @@ while j<= NumberOfIterations
     CovJump = CovJump + oldMeanPar*oldMeanPar' - MeanPar*MeanPar' + ...
               (1/j)*(ix2*ix2' - CovJump - oldMeanPar*oldMeanPar');
 end
-dyn_waitbar_close(hh);
+dyn_waitbar_close(hh_fig);
 PostVar = CovJump;
 PostMean = MeanPar;
 %% [3 & 4] I tune the scale parameter (with the new covariance matrix) if
@@ -185,8 +185,8 @@ PostMean = MeanPar;
 %% updating the covariance matrix)...
 if strcmpi(info,'LastCall')
 
-    hh = dyn_waitbar(0,'Tuning of the scale parameter...');
-    set(hh,'Name','Tuning of the scale parameter.'),
+    hh_fig = dyn_waitbar(0,'Tuning of the scale parameter...');
+    set(hh_fig,'Name','Tuning of the scale parameter.'),
     j = 1; jj  = 1;
     isux = 0; jsux = 0;
     test = 0;
@@ -212,7 +212,7 @@ if strcmpi(info,'LastCall')
         end % ... otherwise I don't move.
         prtfrc = j/MaxNumberOfTuningSimulations;
         if mod(j, 10)==0
-            dyn_waitbar(prtfrc,hh,sprintf('Acceptance ratio [during last 1000]: %f [%f]',isux/j,jsux/jj));
+            dyn_waitbar(prtfrc,hh_fig,sprintf('Acceptance ratio [during last 1000]: %f [%f]',isux/j,jsux/jj));
         end
         if j/1000 == round(j/1000)
             test1 = jsux/jj;
@@ -229,14 +229,14 @@ if strcmpi(info,'LastCall')
         j = j+1;
         jj = jj + 1;
     end
-    dyn_waitbar_close(hh);
+    dyn_waitbar_close(hh_fig);
     Scale = iScale;
     %%
     %% Now I climb the hill
     %%
     if options.nclimb
-        hh = dyn_waitbar(0,' ');
-        set(hh,'Name','Now I am climbing the hill...'),
+        hh_fig = dyn_waitbar(0,' ');
+        set(hh_fig,'Name','Now I am climbing the hill...'),
         j = 1; jj  = 1;
         jsux = 0;
         test = 0;
@@ -254,7 +254,7 @@ if strcmpi(info,'LastCall')
             end % otherwise I don't move...
             prtfrc = j/MaxNumberOfClimbingSimulations;
             if mod(j, 10)==0
-                dyn_waitbar(prtfrc,hh,sprintf('%f Jumps / MaxStepSize %f',jsux,sqrt(max(diag(iScale*CovJump)))));
+                dyn_waitbar(prtfrc,hh_fig,sprintf('%f Jumps / MaxStepSize %f',jsux,sqrt(max(diag(iScale*CovJump)))));
             end
             if  j/200 == round(j/200)
                 if jsux<=1
@@ -275,7 +275,7 @@ if strcmpi(info,'LastCall')
             j = j+1;
             jj = jj + 1;
         end
-        dyn_waitbar_close(hh);
+        dyn_waitbar_close(hh_fig);
     end %climb
 else
     Scale = iScale;
diff --git a/matlab/plot_icforecast.m b/matlab/plot_icforecast.m
index 547272a7f3affd41b9af207720954165cf979292..da4d88ebbd9eb576597a16231ec5c5883f9afb91 100644
--- a/matlab/plot_icforecast.m
+++ b/matlab/plot_icforecast.m
@@ -13,7 +13,7 @@ function plot_icforecast(Variables,periods,options_,oo_)
 % SPECIAL REQUIREMENTS
 %  This routine has to be called after imcforecast.m.
 
-% Copyright © 2006-2019 Dynare Team
+% Copyright © 2006-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -59,7 +59,7 @@ for i=1:length(Variables)
 end
 
 function build_figure(name,cci1,cci2,mm1,mm2,options_,graphoptions)
-hh = dyn_figure(options_.nodisplay,'Name',['Conditional forecast (' graphoptions.title ,'): ' name '.']);
+hh_fig = dyn_figure(options_.nodisplay,'Name',['Conditional forecast (' graphoptions.title ,'): ' name '.']);
 H = length(mm1);
 h1 = area(1:H,cci1(2,1:H),'BaseValue',min([min(cci1(1,:)),min(cci2(1,:))]),'FaceColor',[.9 .9 .9]);
 hold on
@@ -70,4 +70,4 @@ plot(1:H,cci2(1,:),'--k','linewidth',1)
 plot(1:H,cci2(2,:),'--k','linewidth',1)
 axis tight
 hold off
-dyn_saveas(hh,[graphoptions.OutputDirectoryName '/Conditional_forecast_',strrep(deblank(graphoptions.title),' ','_'),'_',name],options_.nodisplay,options_.graph_format)
\ No newline at end of file
+dyn_saveas(hh_fig,[graphoptions.OutputDirectoryName '/Conditional_forecast_',strrep(deblank(graphoptions.title),' ','_'),'_',name],options_.nodisplay,options_.graph_format)
\ No newline at end of file
diff --git a/matlab/plot_identification.m b/matlab/plot_identification.m
index 2d9e5a3ef349e6e742b2ae019bd9f02f1c083ee5..688f177a9833b539d7ef098ab226b00605df4377 100644
--- a/matlab/plot_identification.m
+++ b/matlab/plot_identification.m
@@ -19,7 +19,7 @@ function plot_identification(params, idemoments, idehess, idemodel, idelre, adva
 % SPECIAL REQUIREMENTS
 %    None
 
-% Copyright © 2008-2021 Dynare Team
+% Copyright © 2008-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -55,7 +55,7 @@ tittxt1=regexprep(tittxt, ' ', '_');
 tittxt1=strrep(tittxt1, '.', '');
 if SampleSize == 1
     si_dMOMENTS = idemoments.si_dMOMENTS;
-    hh = dyn_figure(options_.nodisplay,'Name',[tittxt, ' - Identification using info from observables']);
+    hh_fig = dyn_figure(options_.nodisplay,'Name',[tittxt, ' - Identification using info from observables']);
     subplot(211)
     mmm = (idehess.ide_strength_dMOMENTS);
     [ss, is] = sort(mmm);
@@ -156,7 +156,7 @@ if SampleSize == 1
         fprintf(fidTeX,'%% End Of TeX file. \n');
         fclose(fidTeX);
     end
-    dyn_saveas(hh,[IdentifDirectoryName '/' M_.fname '_ident_strength_' tittxt1],options_.nodisplay,options_.graph_format);
+    dyn_saveas(hh_fig,[IdentifDirectoryName '/' M_.fname '_ident_strength_' tittxt1],options_.nodisplay,options_.graph_format);
 
     if advanced
         if ~options_.nodisplay
@@ -166,7 +166,7 @@ if SampleSize == 1
         if all(isnan([si_dMOMENTSnorm';si_dTAUnorm';si_dLREnorm']))
             fprintf('\nIDENTIFICATION: Skipping sensitivity plot, because standard deviation of parameters is NaN, possibly due to the use of ML.\n')
         else
-            hh = dyn_figure(options_.nodisplay,'Name',[tittxt, ' - Sensitivity plot']);
+            hh_fig = dyn_figure(options_.nodisplay,'Name',[tittxt, ' - Sensitivity plot']);
             subplot(211)
             mmm = (si_dMOMENTSnorm)'./max(si_dMOMENTSnorm);
             mmm1 = (si_dTAUnorm)'./max(si_dTAUnorm);
@@ -185,7 +185,7 @@ if SampleSize == 1
             end
             legend('Moments','Model','LRE model','Location','Best')
             title('Sensitivity bars using derivatives (log-scale)')
-            dyn_saveas(hh,[IdentifDirectoryName '/' M_.fname '_sensitivity_' tittxt1 ],options_.nodisplay,options_.graph_format);
+            dyn_saveas(hh_fig,[IdentifDirectoryName '/' M_.fname '_sensitivity_' tittxt1 ],options_.nodisplay,options_.graph_format);
             if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                 fidTeX = fopen([IdentifDirectoryName '/' M_.fname '_sensitivity_' tittxt1,'.tex'],'w');
                 fprintf(fidTeX,'%% TeX eps-loader file generated by plot_identification.m (Dynare).\n');
@@ -219,7 +219,7 @@ if SampleSize == 1
                 end
                 %                 fprintf('%-15s [%s] %10.3f\n',name{i},namx,idemoments.cosndMOMENTS(i,j))
             end
-            hh = dyn_figure(options_.nodisplay,'Name',[tittxt,' - Collinearity patterns with ', int2str(j) ,' parameter(s)']);
+            hh_fig = dyn_figure(options_.nodisplay,'Name',[tittxt,' - Collinearity patterns with ', int2str(j) ,' parameter(s)']);
             imagesc(pax,[0 1]);
             set(gca,'xticklabel','')
             set(gca,'yticklabel','')
@@ -239,7 +239,7 @@ if SampleSize == 1
             set(gca,'xgrid','on')
             set(gca,'ygrid','on')
             xlabel([tittxt,' - Collinearity patterns with ', int2str(j) ,' parameter(s)'],'interpreter','none')
-            dyn_saveas(hh,[ IdentifDirectoryName '/' M_.fname '_ident_collinearity_' tittxt1 '_' int2str(j) ],options_.nodisplay,options_.graph_format);
+            dyn_saveas(hh_fig,[ IdentifDirectoryName '/' M_.fname '_ident_collinearity_' tittxt1 '_' int2str(j) ],options_.nodisplay,options_.graph_format);
             if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                 fidTeX = fopen([ IdentifDirectoryName '/' M_.fname '_ident_collinearity_' tittxt1 '_' int2str(j),'.tex'],'w');
                 fprintf(fidTeX,'%% TeX eps-loader file generated by plot_identification.m (Dynare).\n');
@@ -337,7 +337,7 @@ if SampleSize == 1
     end
 
 else
-    hh = dyn_figure(options_.nodisplay,'Name',['MC sensitivities']);
+    hh_fig = dyn_figure(options_.nodisplay,'Name',['MC sensitivities']);
     subplot(211)
     mmm = (idehess.ide_strength_dMOMENTS);
     [ss, is] = sort(mmm);
@@ -363,7 +363,7 @@ else
         legend('Moments','Model','LRE model','Location','Best')
     end
     title('MC mean of sensitivity measures')
-    dyn_saveas(hh,[ IdentifDirectoryName '/' M_.fname '_MC_sensitivity' ],options_.nodisplay,options_.graph_format);
+    dyn_saveas(hh_fig,[ IdentifDirectoryName '/' M_.fname '_MC_sensitivity' ],options_.nodisplay,options_.graph_format);
     if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
         fidTeX = fopen([ IdentifDirectoryName '/' M_.fname '_MC_sensitivity.tex'],'w');
         fprintf(fidTeX,'%% TeX eps-loader file generated by plot_identification.m (Dynare).\n');
@@ -384,7 +384,7 @@ else
             disp('Displaying advanced diagnostics')
         end
         %         options_.nograph=1;
-        hh = dyn_figure(options_.nodisplay,'Name','MC Condition Number');
+        hh_fig = dyn_figure(options_.nodisplay,'Name','MC Condition Number');
         subplot(221)
         hist(log10(idemodel.cond))
         title('log10 of Condition number in the model')
@@ -394,7 +394,7 @@ else
         subplot(223)
         hist(log10(idelre.cond))
         title('log10 of Condition number in the LRE model')
-        dyn_saveas(hh,[IdentifDirectoryName '/' M_.fname '_ident_COND' ],options_.nodisplay,options_.graph_format);
+        dyn_saveas(hh_fig,[IdentifDirectoryName '/' M_.fname '_ident_COND' ],options_.nodisplay,options_.graph_format);
         options_mcf.pvalue_ks = 0.1;
         options_mcf.pvalue_corr = 0.001;
         options_mcf.alpha2 = 0;
diff --git a/matlab/plot_priors.m b/matlab/plot_priors.m
index 35759f3093fb00de7e69264f4e4dc395a2f6bbec..9cfa5385ee37dfa25f4774665023c599e3c5933c 100644
--- a/matlab/plot_priors.m
+++ b/matlab/plot_priors.m
@@ -15,7 +15,7 @@ function plot_priors(bayestopt_,M_,estim_params_,options_,optional_title)
 % SPECIAL REQUIREMENTS
 %    None
 
-% Copyright © 2004-2020 Dynare Team
+% Copyright © 2004-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -31,6 +31,8 @@ function plot_priors(bayestopt_,M_,estim_params_,options_,optional_title)
 %
 % 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);
 
 TeX = options_.TeX;
 if nargin<5
@@ -41,17 +43,14 @@ end
 npar = length(bayestopt_.p1);
 [nbplt,nr,nc,lr,lc,nstar] = pltorg(npar);
 
-if ~exist([M_.dname '/graphs'],'dir')
-    mkdir(M_.dname,'graphs');
-end
 if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
-    fidTeX = fopen([M_.dname, '/graphs/' M_.fname '_Priors.tex'],'w');
+    fidTeX = fopen([latexDirectoryName filesep M_.fname '_Priors.tex'],'w');
     fprintf(fidTeX,'%% TeX eps-loader file generated by plot_priors.m (Dynare).\n');
     fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
     fprintf(fidTeX,' \n');
 end
 for plt = 1:nbplt
-    hplt = dyn_figure(options_.nodisplay,'Name',figurename);
+    hh_fig = dyn_figure(options_.nodisplay,'Name',figurename);
     if TeX
         TeXNAMES = [];
         NAMES    = [];
@@ -63,8 +62,8 @@ for plt = 1:nbplt
         [x,f,abscissa,dens,binf,bsup] = draw_prior_density(i,bayestopt_);
         [nam,texnam] = get_the_name(i,TeX,M_,estim_params_,options_);
         subplot(nr,nc,index)
-        hh = plot(x,f,'-k','linewidth',2);
-        set(hh,'color',[0.7 0.7 0.7]);
+        hh_plt = plot(x,f,'-k','linewidth',2);
+        set(hh_plt,'color',[0.7 0.7 0.7]);
         box on
         if TeX
             title(texnam,'Interpreter','latex')
@@ -73,11 +72,11 @@ for plt = 1:nbplt
         end
         drawnow
     end
-    dyn_saveas(hplt,[M_.dname, '/graphs/' M_.fname '_Priors' int2str(plt)],options_.nodisplay,options_.graph_format);
+    dyn_saveas(hh_fig,[graphDirectoryName filesep M_.fname '_Priors' int2str(plt)],options_.nodisplay,options_.graph_format);
     if 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_Priors%s}\n',options_.figures.textwidth*min(index/nc,1),[M_.dname, '/graphs/' M_.fname],int2str(plt));
+        fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_Priors%s}\n',options_.figures.textwidth*min(index/nc,1),[graphDirectoryName filesep M_.fname],int2str(plt));
         fprintf(fidTeX,'\\caption{Priors.}');
         fprintf(fidTeX,'\\label{Fig:Priors:%s}\n',int2str(plt));
         fprintf(fidTeX,'\\end{figure}\n');
diff --git a/matlab/pm3.m b/matlab/pm3.m
index 658a58eb71361aea98f516875babd2576c735ac1..3800cd51565f68f7cee9162332b06f7b84051adf 100644
--- a/matlab/pm3.m
+++ b/matlab/pm3.m
@@ -1,4 +1,4 @@
-function pm3(n1,n2,ifil,B,tit1,tit2,tit3,tit_tex,names1,names2,name3,DirectoryName,var_type)
+function pm3(n1,n2,ifil,B,tit1,tit2,tit3,tit_tex,names1,names2,name3,DirectoryName,var_type,dispString)
 
 % Computes, stores and plots the posterior moment statistics.
 %
@@ -19,6 +19,7 @@ function pm3(n1,n2,ifil,B,tit1,tit2,tit3,tit_tex,names1,names2,name3,DirectoryNa
 %                       where to read
 %  var_type     [string] suffix of the filename from which to load moment
 %                   matrix
+%  dispString   [string] string to be displayes in the command window
 
 % PARALLEL CONTEXT
 % See also the comment in posterior_sampler.m funtion.
@@ -43,8 +44,6 @@ function pm3(n1,n2,ifil,B,tit1,tit2,tit3,tit_tex,names1,names2,name3,DirectoryNa
 
 global options_ M_ oo_
 
-dispString = 'Estimation::mcmc';
-
 nn = 3;
 MaxNumberOfPlotsPerFigure = nn^2; % must be square
 varlist = names2;
diff --git a/matlab/pm3_core.m b/matlab/pm3_core.m
index 0d6ef4991eca9bcf6991c34430837ef5cbb6d960..343c708975b35b25242a3d90d407e0ece740f638 100644
--- a/matlab/pm3_core.m
+++ b/matlab/pm3_core.m
@@ -13,7 +13,7 @@ function myoutput=pm3_core(myinputs,fpar,nvar,whoiam, ThisMatlab)
 % SPECIAL REQUIREMENTS.
 %   None.
 
-% Copyright © 2007-2018 Dynare Team
+% Copyright © 2007-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -68,7 +68,7 @@ end
 
 figunumber = 0;
 subplotnum = 0;
-hh = dyn_figure(options_.nodisplay,'Name',[tit1 ' ' int2str(figunumber+1)]);
+hh_fig = dyn_figure(options_.nodisplay,'Name',[tit1 ' ' int2str(figunumber+1)]);
 RemoteFlag = 0;
 if whoiam
     if Parallel(ThisMatlab).Local ==0
@@ -81,7 +81,7 @@ OutputFileName = {};
 for i=fpar:nvar
     if max(abs(Mean(:,i))) > 10^(-6)
         subplotnum = subplotnum+1;
-        set(0,'CurrentFigure',hh);
+        set(0,'CurrentFigure',hh_fig);
         subplot(nn,nn,subplotnum);
         if ~(all(all(Distrib(:,:,i)))>0 || ~all(all(Distrib(:,:,i)))<0)
             plot([1 n2],[0 0],'-r','linewidth',0.5);
@@ -115,14 +115,14 @@ for i=fpar:nvar
     end
 
     if subplotnum == MaxNumberOfPlotsPerFigure || i == nvar
-        dyn_saveas(hh,[M_.dname '/Output/'  M_.fname '_' name3 '_' tit3{i}],options_.nodisplay,options_.graph_format);
+        dyn_saveas(hh_fig,[M_.dname '/Output/'  M_.fname '_' name3 '_' tit3{i}],options_.nodisplay,options_.graph_format);
         if RemoteFlag==1
             OutputFileName = [OutputFileName; {[M_.dname, filesep, 'Output',filesep], [M_.fname '_' name3 '_' deblank(tit3(i,:)) '.*']}];
         end
         subplotnum = 0;
         figunumber = figunumber+1;
         if (i ~= nvar)
-            hh = dyn_figure(options_.nodisplay,'Name',[name3 ' ' int2str(figunumber+1)]);
+            hh_fig = dyn_figure(options_.nodisplay,'Name',[name3 ' ' int2str(figunumber+1)]);
         end
     end
 
diff --git a/matlab/posterior_sampler.m b/matlab/posterior_sampler.m
index 8a98bfc24dce99e591c9d38b5c76526d7d8fc538..37d9ee19e3175b8b45d6419023ebdc036e691951 100644
--- a/matlab/posterior_sampler.m
+++ b/matlab/posterior_sampler.m
@@ -1,5 +1,5 @@
-function posterior_sampler(TargetFun,ProposalFun,xparam1,sampler_options,mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_)
-% function posterior_sampler(TargetFun,ProposalFun,xparam1,sampler_options,mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_)
+function posterior_sampler(TargetFun,ProposalFun,xparam1,sampler_options,mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_,dispString)
+% function posterior_sampler(TargetFun,ProposalFun,xparam1,sampler_options,mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_,dispString)
 % Random Walk Metropolis-Hastings algorithm.
 %
 % INPUTS
@@ -17,6 +17,7 @@ function posterior_sampler(TargetFun,ProposalFun,xparam1,sampler_options,mh_boun
 %   o estim_params_     [structure] estimated parameters structure
 %   o bayestopt_        [structure] prior specification structure
 %   o oo_               [structure] output structure
+%   o dispString        [string]    string prependening the messages printed to the command window
 %
 % SPECIAL REQUIREMENTS
 %   None.
@@ -53,12 +54,10 @@ function posterior_sampler(TargetFun,ProposalFun,xparam1,sampler_options,mh_boun
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
 
-dispString = 'Estimation::mcmc';
-
 vv = sampler_options.invhess;
 % Initialization of the sampler
 [ ix2, ilogpo2, ModelName, MetropolisFolder, fblck, fline, npar, nblck, nruns, NewFile, MAX_nruns, d, bayestopt_] = ...
-    posterior_sampler_initialization(TargetFun, xparam1, vv, mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_);
+    posterior_sampler_initialization(TargetFun, xparam1, vv, mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_, dispString);
 
 InitSizeArray = min([repmat(MAX_nruns,nblck,1) fline+nruns-1],[],2);
 
diff --git a/matlab/posterior_sampler_core.m b/matlab/posterior_sampler_core.m
index 0722858c4cdfa9a91d5c829a0fb322f1f7b315ea..4e3379a6443a26a1c9bf14240b75741ebec77d41 100644
--- a/matlab/posterior_sampler_core.m
+++ b/matlab/posterior_sampler_core.m
@@ -174,12 +174,12 @@ for curr_block = fblck:nblck
         refresh_rate = sampler_options.parallel_bar_refresh_rate;
         bar_title = sampler_options.parallel_bar_title;
         prc0=(curr_block-fblck)/(nblck-fblck+1)*(isoctave || options_.console_mode);
-        hh = dyn_waitbar({prc0,whoiam,options_.parallel(ThisMatlab)},[bar_title ' (' int2str(curr_block) '/' int2str(options_.mh_nblck) ')...']);
+        hh_fig = dyn_waitbar({prc0,whoiam,options_.parallel(ThisMatlab)},[bar_title ' (' int2str(curr_block) '/' int2str(options_.mh_nblck) ')...']);
     else
         refresh_rate = sampler_options.serial_bar_refresh_rate;
         bar_title = sampler_options.serial_bar_title;
-        hh = dyn_waitbar(0,[bar_title ' (' int2str(curr_block) '/' int2str(options_.mh_nblck) ')...']);
-        set(hh,'Name',bar_title);
+        hh_fig = dyn_waitbar(0,[bar_title ' (' int2str(curr_block) '/' int2str(options_.mh_nblck) ')...']);
+        set(hh_fig,'Name',bar_title);
     end
     if mh_recover_flag==0
         accepted_draws_this_chain = 0;
@@ -207,9 +207,9 @@ for curr_block = fblck:nblck
         prtfrc = draw_iter/nruns(curr_block);
         if mod(draw_iter, refresh_rate)==0
             if accepted_draws_this_chain/draw_iter==1 && sum(neval)>1
-                dyn_waitbar(prtfrc,hh,[bar_title ' (' int2str(curr_block) '/' int2str(options_.mh_nblck) ') ' sprintf('Function eval per draw %4.3f', feval_this_chain/draw_iter)]);
+                dyn_waitbar(prtfrc,hh_fig,[bar_title ' (' int2str(curr_block) '/' int2str(options_.mh_nblck) ') ' sprintf('Function eval per draw %4.3f', feval_this_chain/draw_iter)]);
             else
-                dyn_waitbar(prtfrc,hh,[bar_title ' (' int2str(curr_block) '/' int2str(options_.mh_nblck) ') ' sprintf('Current acceptance ratio %4.3f', accepted_draws_this_chain/draw_iter)]);
+                dyn_waitbar(prtfrc,hh_fig,[bar_title ' (' int2str(curr_block) '/' int2str(options_.mh_nblck) ') ' sprintf('Current acceptance ratio %4.3f', accepted_draws_this_chain/draw_iter)]);
             end
             if save_tmp_file
                 [LastSeeds.(['file' int2str(NewFile(curr_block))]).Unifor, LastSeeds.(['file' int2str(NewFile(curr_block))]).Normal] = get_dynare_random_generator_state();
@@ -265,7 +265,7 @@ for curr_block = fblck:nblck
         draw_iter=draw_iter+1;
         draw_index_current_file = draw_index_current_file + 1;
     end % End of the simulations for one mh-block.
-    dyn_waitbar_close(hh);
+    dyn_waitbar_close(hh_fig);
     if nruns(curr_block)
         record.AcceptanceRatio(curr_block) = accepted_draws_this_chain/(draw_iter-1);
         record.FunctionEvalPerIteration(curr_block) = feval_this_chain/(draw_iter-1);
diff --git a/matlab/posterior_sampler_initialization.m b/matlab/posterior_sampler_initialization.m
index 36c3087771699a71dd3a65fc208e046f051ac533..ab9ffe063af0195e52daaa37744c1dadf1179449 100644
--- a/matlab/posterior_sampler_initialization.m
+++ b/matlab/posterior_sampler_initialization.m
@@ -1,7 +1,7 @@
 function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npar, NumberOfBlocks, nruns, NewFile, MAX_nruns, d, bayestopt_] = ...
-    posterior_sampler_initialization(TargetFun, xparam1, vv, mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_)
+    posterior_sampler_initialization(TargetFun, xparam1, vv, mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_, dispString)
 % function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npar, NumberOfBlocks, nruns, NewFile, MAX_nruns, d, bayestopt_] = ...
-%     metropolis_hastings_initialization(TargetFun, xparam1, vv, mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_)
+%     metropolis_hastings_initialization(TargetFun, xparam1, vv, mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_, dispString)
 % Metropolis-Hastings initialization.
 %
 % INPUTS
@@ -17,6 +17,7 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa
 %   o estim_params_         estimated parameters structure
 %   o bayestopt_            estimation options structure
 %   o oo_                   outputs structure
+%   o dispString            string to be displayed in the command window
 %
 % OUTPUTS
 %   o ix2                   [double]   (NumberOfBlocks*npar) vector of starting points for different chains
@@ -55,8 +56,6 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, FirstBlock, FirstLine, npa
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
 
-dispString = 'Estimation::mcmc';
-
 %Initialize outputs
 ix2 = [];
 ilogpo2 = [];
diff --git a/matlab/posterior_sampler_iteration.m b/matlab/posterior_sampler_iteration.m
index 185e990ddf696bff8c51a2d24350ba17a363858f..65e44ed67f364fa7d4436853966b519961eda2e1 100644
--- a/matlab/posterior_sampler_iteration.m
+++ b/matlab/posterior_sampler_iteration.m
@@ -26,7 +26,7 @@ function  [par, logpost, accepted, neval] = posterior_sampler_iteration(TargetFu
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright © 2015-18 Dynare Team
+% Copyright © 2015-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/prior_posterior_statistics.m b/matlab/prior_posterior_statistics.m
index 51ab6f02d35746082d361279b25924059a7677bd..4bdddfd2d8182a43f4dab2330b7d26ca0e5edf9e 100644
--- a/matlab/prior_posterior_statistics.m
+++ b/matlab/prior_posterior_statistics.m
@@ -1,5 +1,5 @@
-function prior_posterior_statistics(type,dataset,dataset_info)
-% function prior_posterior_statistics(type,dataset,dataset_info)
+function prior_posterior_statistics(type,dataset,dataset_info,dispString)
+% function prior_posterior_statistics(type,dataset,dataset_info,dispString)
 % Computes Monte Carlo filter smoother and forecasts
 %
 % INPUTS
@@ -8,6 +8,7 @@ function prior_posterior_statistics(type,dataset,dataset_info)
 %                  gsa
 %    dataset:      data structure
 %    dataset_info: dataset structure
+%    dispString:   string to display in the command window
 %
 % OUTPUTS
 %    none
@@ -36,6 +37,10 @@ function prior_posterior_statistics(type,dataset,dataset_info)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
 
+if nargin < 4
+    dispString = 'prior_posterior_statistics';
+end
+
 global options_ estim_params_ oo_ M_ bayestopt_
 
 localVars=[];
@@ -218,9 +223,9 @@ if strcmpi(type,'posterior')
     mh_nblck = options_.mh_nblck;
     if B==NumberOfDraws*mh_nblck
         % we load all retained MH runs !
-        logpost=GetAllPosteriorDraws(0, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, nblck);
+        logpost=GetAllPosteriorDraws(M_.dname, M_.fname, 0, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, nblck);
         for column=1:npar
-            x(:,column) = GetAllPosteriorDraws(column, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, nblck);
+            x(:,column) = GetAllPosteriorDraws(M_.dname, M_.fname, column, FirstMhFile, FirstLine, TotalNumberOfMhFiles, NumberOfDraws, nblck);
         end
     else
         logpost=NaN(B,1);
@@ -327,27 +332,27 @@ end
 if options_.smoother
     pm3(endo_nbr,gend,ifil(1),B,'Smoothed variables',...
         '',varlist, M_.endo_names_tex,M_.endo_names,...
-        varlist,'SmoothedVariables',DirectoryName,'_smooth');
+        varlist,'SmoothedVariables',DirectoryName,'_smooth',dispString);
     pm3(exo_nbr,gend,ifil(2),B,'Smoothed shocks',...
         '',M_.exo_names,M_.exo_names_tex,M_.exo_names,...
-        M_.exo_names,'SmoothedShocks',DirectoryName,'_inno');
+        M_.exo_names,'SmoothedShocks',DirectoryName,'_inno',dispString);
     pm3(endo_nbr,1,ifil(9),B,'Trend_coefficients',...
         '',varlist,M_.endo_names_tex,M_.endo_names,...
-        varlist,'TrendCoeff',DirectoryName,'_trend_coeff');
+        varlist,'TrendCoeff',DirectoryName,'_trend_coeff',dispString);
     pm3(endo_nbr,gend,ifil(10),B,'Smoothed constant',...
         '',varlist,M_.endo_names_tex,M_.endo_names,...
-        varlist,'Constant',DirectoryName,'_smoothed_constant');
+        varlist,'Constant',DirectoryName,'_smoothed_constant',dispString);
     pm3(endo_nbr,gend,ifil(11),B,'Smoothed trend',...
         '',varlist,M_.endo_names_tex,M_.endo_names,...
-        varlist,'Trend',DirectoryName,'_smoothed_trend');
+        varlist,'Trend',DirectoryName,'_smoothed_trend',dispString);
     pm3(endo_nbr,gend,ifil(1),B,'Updated Variables',...
         '',varlist,M_.endo_names_tex,M_.endo_names,...
         varlist,'UpdatedVariables',DirectoryName, ...
-        '_update');
+        '_update',dispString);
     if smoothed_state_uncertainty
         pm3(endo_nbr,endo_nbr,ifil(13),B,'State Uncertainty',...
             '',varlist,M_.endo_names_tex,M_.endo_names,...
-            varlist,'StateUncertainty',DirectoryName,'_state_uncert');
+            varlist,'StateUncertainty',DirectoryName,'_state_uncert',dispString);
     end
 
     if nvn
@@ -357,23 +362,23 @@ if options_.smoother
         end
         pm3(meas_err_nbr,gend,ifil(3),B,'Smoothed measurement errors',...
             '',meas_error_names,texnames,meas_error_names,...
-            meas_error_names,'SmoothedMeasurementErrors',DirectoryName,'_error')
+            meas_error_names,'SmoothedMeasurementErrors',DirectoryName,'_error',dispString)
     end
 end
 
 if options_.filtered_vars
     pm3(endo_nbr,gend,ifil(4),B,'One step ahead forecast (filtered variables)',...
         '',varlist,M_.endo_names_tex,M_.endo_names,...
-        varlist,'FilteredVariables',DirectoryName,'_filter_step_ahead');
+        varlist,'FilteredVariables',DirectoryName,'_filter_step_ahead',dispString);
 end
 
 if options_.forecast
     pm3(endo_nbr,horizon,ifil(6),B,'Forecasted variables (mean)',...
         '',varlist,M_.endo_names_tex,M_.endo_names,...
-        varlist,'MeanForecast',DirectoryName,'_forc_mean');
+        varlist,'MeanForecast',DirectoryName,'_forc_mean',dispString);
     pm3(endo_nbr,horizon,ifil(7),B,'Forecasted variables (point)',...
         '',varlist,M_.endo_names_tex,M_.endo_names,...
-        varlist,'PointForecast',DirectoryName,'_forc_point');
+        varlist,'PointForecast',DirectoryName,'_forc_point',dispString);
     if ~isequal(M_.H,0) && ~isempty(intersect(options_.varobs,varlist))
         texnames = cell(length(options_.varobs), 1);
         obs_names = cell(length(options_.varobs), 1);
@@ -384,14 +389,14 @@ if options_.forecast
         varlist_forecast_ME=intersect(options_.varobs,varlist);
         pm3(meas_err_nbr,horizon,ifil(12),B,'Forecasted variables (point) with ME',...
             '',varlist_forecast_ME,texnames,obs_names,...
-            varlist_forecast_ME,'PointForecastME',DirectoryName,'_forc_point_ME')
+            varlist_forecast_ME,'PointForecastME',DirectoryName,'_forc_point_ME',dispString)
     end
 end
 
 if options_.filter_covariance
     pm3(endo_nbr,endo_nbr,ifil(8),B,'Filtered covariances',...
         '',varlist,M_.endo_names_tex,M_.endo_names,...
-        varlist,'FilterCovariance',DirectoryName,'_filter_covar');
+        varlist,'FilterCovariance',DirectoryName,'_filter_covar',dispString);
 end
 
 
diff --git a/matlab/prior_sampler.m b/matlab/prior_sampler.m
index 1303cbcf02784a45d506f4f30e83aa26b3787263..3ef74fd45bda8292f4059a643c2ebaa8fcb4ce37 100644
--- a/matlab/prior_sampler.m
+++ b/matlab/prior_sampler.m
@@ -85,13 +85,13 @@ file_indx_number = 0;
 
 oo_.dr=set_state_space(oo_.dr,M_,options_);
 
-hh = dyn_waitbar(0,'Please wait. Prior sampler...');
-set(hh,'Name','Prior sampler.');
+hh_fig = dyn_waitbar(0,'Please wait. Prior sampler...');
+set(hh_fig,'Name','Prior sampler.');
 
 % Simulations.
 while iteration < NumberOfSimulations
     if ~mod(iteration,10)
-        dyn_waitbar(iteration/NumberOfSimulations,hh,'Please wait. Prior sampler...');
+        dyn_waitbar(iteration/NumberOfSimulations,hh_fig,'Please wait. Prior sampler...');
     end
     loop_indx = loop_indx+1;
     params = Prior.draw();
@@ -162,7 +162,7 @@ while iteration < NumberOfSimulations
     end
 end
 
-dyn_waitbar_close(hh);
+dyn_waitbar_close(hh_fig);
 
 % Get informations about BK conditions and other things...
 results.bk.indeterminacy_share = count_bk_indeterminacy/loop_indx;
diff --git a/matlab/rplot.m b/matlab/rplot.m
index 6c54fc879177468621190f443d4c876868c60f5b..53abb116de3340f7d8e02cac391d27ac64eab8a2 100644
--- a/matlab/rplot.m
+++ b/matlab/rplot.m
@@ -14,7 +14,7 @@ function rplot(s1)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright © 2001-2021 Dynare Team
+% Copyright © 2001-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -75,7 +75,7 @@ if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
 end
 
 if options_.rplottype == 0 %all in one plot
-    hh=dyn_figure(options_.nodisplay,'Name', 'Simulated Trajectory');
+    hh_fig=dyn_figure(options_.nodisplay,'Name', 'Simulated Trajectory');
     plot(ix(i),y(:,i)) ;
     if options_.TeX
         title (['Plot of $' strjoin(s1_TeX', '~') '$'],'Interpreter','latex') ;
@@ -94,13 +94,13 @@ if options_.rplottype == 0 %all in one plot
             legend(s1,'interpreter','none');
         end
     end
-    dyn_saveas(hh,[M_.dname, filesep, 'graphs', filesep, 'SimulatedTrajectory_' s1{1}],options_.nodisplay,options_.graph_format)
+    dyn_saveas(hh_fig,[M_.dname, filesep, 'graphs', filesep, 'SimulatedTrajectory_' s1{1}],options_.nodisplay,options_.graph_format)
     if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
         create_TeX_loader(fidTeX,[M_.dname, '/graphs/', 'SimulatedTrajectory_' s1{1}],'Simulated trajectories','SimulatedTrajectory_',s1{1},1)
     end
 elseif options_.rplottype == 1 %separate figures each
     for j = 1:size(y,1)
-        hh=dyn_figure(options_.nodisplay,'Name', 'Simulated Trajectory');
+        hh_fig=dyn_figure(options_.nodisplay,'Name', 'Simulated Trajectory');
         plot(ix(i),y(j,i)) ;
         xlim([min(ix(i)) max(ix(i))])
         if options_.TeX
@@ -109,13 +109,13 @@ elseif options_.rplottype == 1 %separate figures each
             title(['Plot of ' s1{j}],'Interpreter','none') ;
         end
         xlabel('Periods') ;
-        dyn_saveas(hh,[M_.dname, filesep, 'graphs', filesep, 'SimulatedTrajectory_' s1{j}],options_.nodisplay,options_.graph_format)
+        dyn_saveas(hh_fig,[M_.dname, filesep, 'graphs', filesep, 'SimulatedTrajectory_' s1{j}],options_.nodisplay,options_.graph_format)
         if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
             create_TeX_loader(fidTeX,[M_.dname, '/graphs/', 'SimulatedTrajectory_' s1{j}],'Simulated trajectories','SimulatedTrajectory_',s1{j},1);
         end
     end
 elseif options_.rplottype == 2 %different subplots
-    hh=dyn_figure(options_.nodisplay,'Name', 'Simulated Trajectory');
+    hh_fig=dyn_figure(options_.nodisplay,'Name', 'Simulated Trajectory');
     nl = max(1,fix(size(y,1)/4)) ;
     nc = ceil(size(y,1)/nl) ;
     for j = 1:size(y,1)
@@ -137,7 +137,7 @@ elseif options_.rplottype == 2 %different subplots
         end
         axis tight;
     end
-    dyn_saveas(hh,[M_.dname, filesep, 'graphs', filesep, 'SimulatedTrajectory_' s1{1}],options_.nodisplay,options_.graph_format)
+    dyn_saveas(hh_fig,[M_.dname, filesep, 'graphs', filesep, 'SimulatedTrajectory_' s1{1}],options_.nodisplay,options_.graph_format)
     if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
         create_TeX_loader(fidTeX,[M_.dname, '/graphs/', 'SimulatedTrajectory_' s1{1}],'Simulated trajectories','SimulatedTrajectory_', s1{1},min(j/nc,1));
     end
diff --git a/matlab/stoch_simul.m b/matlab/stoch_simul.m
index 06a1f7eb473a40770d5c4074c2917cd2504b5449..0742ddc47ab24598b9fd2ad54d0ea033c5ff5e5e 100644
--- a/matlab/stoch_simul.m
+++ b/matlab/stoch_simul.m
@@ -310,10 +310,10 @@ if options_.irf
                 if nbplt == 0
                 elseif nbplt == 1
                     if options_.relative_irf
-                        hh = dyn_figure(options_.nodisplay,'Name',['Relative response to' ...
+                        hh_fig = dyn_figure(options_.nodisplay,'Name',['Relative response to' ...
                                             ' orthogonalized shock to ' tit{i}]);
                     else
-                        hh = dyn_figure(options_.nodisplay,'Name',['Orthogonalized shock to' ...
+                        hh_fig = dyn_figure(options_.nodisplay,'Name',['Orthogonalized shock to' ...
                                             ' ' tit{i}]);
                     end
                     for j = 1:number_of_plots_to_draw
@@ -330,7 +330,7 @@ if options_.irf
                             title(deblank(mylist(j,:)),'Interpreter','none');
                         end
                     end
-                    dyn_saveas(hh,[M_.dname, '/graphs/' M_.fname '_IRF_' tit{i}],options_.nodisplay,options_.graph_format);
+                    dyn_saveas(hh_fig,[M_.dname, '/graphs/' M_.fname '_IRF_' tit{i}],options_.nodisplay,options_.graph_format);
                     if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                         fprintf(fidTeX,'\\begin{figure}[H]\n');
                         fprintf(fidTeX,'\\centering \n');
@@ -343,10 +343,10 @@ if options_.irf
                 else
                     for fig = 1:nbplt-1
                         if options_.relative_irf
-                            hh = dyn_figure(options_.nodisplay,'Name',['Relative response to orthogonalized shock' ...
+                            hh_fig = dyn_figure(options_.nodisplay,'Name',['Relative response to orthogonalized shock' ...
                                                 ' to ' tit{i} ' figure ' int2str(fig)]);
                         else
-                            hh = dyn_figure(options_.nodisplay,'Name',['Orthogonalized shock to ' tit{i} ...
+                            hh_fig = dyn_figure(options_.nodisplay,'Name',['Orthogonalized shock to ' tit{i} ...
                                                 ' figure ' int2str(fig)]);
                         end
                         for plt = 1:nstar
@@ -363,7 +363,7 @@ if options_.irf
                                 title(deblank(mylist((fig-1)*nstar+plt,:)),'Interpreter','none');
                             end
                         end
-                        dyn_saveas(hh,[M_.dname, '/graphs/'  M_.fname '_IRF_' tit{i} int2str(fig)],options_.nodisplay,options_.graph_format);
+                        dyn_saveas(hh_fig,[M_.dname, '/graphs/'  M_.fname '_IRF_' tit{i} int2str(fig)],options_.nodisplay,options_.graph_format);
                         if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                             fprintf(fidTeX,'\\begin{figure}[H]\n');
                             fprintf(fidTeX,'\\centering \n');
@@ -378,7 +378,7 @@ if options_.irf
                             fprintf(fidTeX,' \n');
                         end
                     end
-                    hh = dyn_figure(options_.nodisplay,'Name',['Orthogonalized shock to ' tit{i} ' figure ' int2str(nbplt) '.']);
+                    hh_fig = dyn_figure(options_.nodisplay,'Name',['Orthogonalized shock to ' tit{i} ' figure ' int2str(nbplt) '.']);
                     m = 0;
                     for plt = 1:number_of_plots_to_draw-(nbplt-1)*nstar
                         m = m+1;
@@ -395,7 +395,7 @@ if options_.irf
                                 title(deblank(mylist((nbplt-1)*nstar+plt,:)),'Interpreter','none');
                             end
                     end
-                    dyn_saveas(hh,[M_.dname, '/graphs/' M_.fname '_IRF_' tit{i} int2str(nbplt) ],options_.nodisplay,options_.graph_format);
+                    dyn_saveas(hh_fig,[M_.dname, '/graphs/' M_.fname '_IRF_' tit{i} int2str(nbplt) ],options_.nodisplay,options_.graph_format);
                     if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                         fprintf(fidTeX,'\\begin{figure}[H]\n');
                         fprintf(fidTeX,'\\centering \n');
diff --git a/matlab/surgibbs.m b/matlab/surgibbs.m
index 199f9bca2820ca283b9f580b49ab852c99ddec82..17b9d6c9d638de7c27ea8b390dce81d8104a13bf 100644
--- a/matlab/surgibbs.m
+++ b/matlab/surgibbs.m
@@ -27,7 +27,7 @@ function ds = surgibbs(ds, param_names, beta0, A, ndraws, discarddraws, thin, eq
 %   Combination of Direct Monte Carlo and Importance Sampling Techniques.
 %   Bayesian Analysis Volume 5, Number 1, pp. 65-96.
 
-% Copyright © 2017-2021 Dynare Team
+% Copyright © 2017-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -106,12 +106,12 @@ if ~options_.noprint
     disp('surgibbs: estimating, please wait...')
 end
 
-hh = dyn_waitbar(0,'Please wait. Gibbs sampler...');
-set(hh,'Name','Surgibbs estimation.');
+hh_fig = dyn_waitbar(0,'Please wait. Gibbs sampler...');
+set(hh_fig,'Name','Surgibbs estimation.');
 residdraws = zeros(floor((ndraws-discarddraws)/thin), nobs, m);
 for i = 1:ndraws
     if ~mod(i,10)
-        dyn_waitbar(i/ndraws,hh,'Please wait. Gibbs sampler...');
+        dyn_waitbar(i/ndraws,hh_fig,'Please wait. Gibbs sampler...');
     end
     % Draw Omega, given X, Y, Beta
     resid = reshape(Y - X*beta, nobs, m);
@@ -135,7 +135,7 @@ for i = 1:ndraws
         end
     end
 end
-dyn_waitbar_close(hh);
+dyn_waitbar_close(hh_fig);
 
 %
 % Save results.
diff --git a/matlab/trace_plot.m b/matlab/trace_plot.m
index 369f9adf56864b4534160e3999628e4047601d33..a90485ae568753066749a00dc1e162835f937b9a 100644
--- a/matlab/trace_plot.m
+++ b/matlab/trace_plot.m
@@ -67,7 +67,7 @@ n_nblocks_to_plot=length(blck);
 
 if n_nblocks_to_plot==1
 % Get all the posterior draws:
-PosteriorDraws = GetAllPosteriorDraws(column, FirstMhFile, FirstLine, TotalNumberOfMhFiles, TotalNumberOfMhDraws, mh_nblck, blck);
+PosteriorDraws = GetAllPosteriorDraws(M_.dname,M_.fname,column, FirstMhFile, FirstLine, TotalNumberOfMhFiles, TotalNumberOfMhDraws, mh_nblck, blck);
 else
     PosteriorDraws=NaN(TotalNumberOfMhDraws,n_nblocks_to_plot);
     save_string='';
@@ -75,7 +75,7 @@ else
         title_string_tex='';
     end
     for block_iter=1:n_nblocks_to_plot
-        PosteriorDraws(:,block_iter) = GetAllPosteriorDraws(column, FirstMhFile, FirstLine, TotalNumberOfMhFiles, TotalNumberOfMhDraws, mh_nblck, blck(block_iter));
+        PosteriorDraws(:,block_iter) = GetAllPosteriorDraws(M_.dname, M_.fname, column, FirstMhFile, FirstLine, TotalNumberOfMhFiles, TotalNumberOfMhDraws, mh_nblck, blck(block_iter));
         save_string=[save_string,'_',num2str(blck(block_iter))];
         if options_.TeX
             title_string_tex=[title_string_tex, ', ' num2str(blck(block_iter))];
@@ -118,7 +118,7 @@ if n_nblocks_to_plot==1
     if options_.mh_nblck>1
         FigureName = [ FigureName , ' (block number ' int2str(blck)  ').'];
     end
-    hh=dyn_figure(options_.nodisplay,'Name',FigureName);
+    hh_fig=dyn_figure(options_.nodisplay,'Name',FigureName);
     plot(1:TotalNumberOfMhDraws,PosteriorDraws,'Color',[.7 .7 .7]);
 
     % Compute the moving average of the posterior draws:
@@ -137,7 +137,7 @@ if n_nblocks_to_plot==1
     axis tight
     legend({'MCMC draw';[num2str(N) ' period moving average']},'Location','NorthEast')
 else
-    hh=dyn_figure(options_.nodisplay,'Name',FigureName);
+    hh_fig=dyn_figure(options_.nodisplay,'Name',FigureName);
     pp=plot(1:TotalNumberOfMhDraws,PosteriorDraws);
     legend(pp,strcat(repmat({'Chain '},n_nblocks_to_plot,1),num2str(blck(:))));
 end
@@ -160,7 +160,7 @@ if n_nblocks_to_plot==1
 else
     plot_name=[plot_name,'_blck_',save_string];
 end
-dyn_saveas(hh,[M_.dname, filesep, 'graphs', filesep, 'TracePlot_' plot_name],options_.nodisplay,options_.graph_format)
+dyn_saveas(hh_fig,[M_.dname, filesep, 'graphs', filesep, 'TracePlot_' plot_name],options_.nodisplay,options_.graph_format)
 
 if options_.TeX
     fid=fopen([M_.dname,'/graphs/',M_.fname,'_TracePlot_' plot_name,'.tex'],'w+');
diff --git a/matlab/update_last_mh_history_file.m b/matlab/update_last_mh_history_file.m
index da75ca2759134730fbde58aee0f9a4baf8f8f61c..781290cb9150c9dd4b0bd4b1ab0332929883e5fb 100644
--- a/matlab/update_last_mh_history_file.m
+++ b/matlab/update_last_mh_history_file.m
@@ -7,7 +7,7 @@ function update_last_mh_history_file(MetropolisFolder, ModelName, record)
 %   record              [structure] structure storing the MH history
 % Outputs:  none
 
-% Copyright © 2013-2017 Dynare Team
+% Copyright © 2013-2023 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -31,7 +31,7 @@ mh_history_files = dir([BaseName '_mh_history_*.mat']);
 
 % Check the existence of mh-files (assuming version 2, ie dynare version greater than 4.3.x).
 if isequal(length(mh_history_files),0)
-    error(['Estimation::update_mh_file: I cannot find any mh-history file in ' MetropolisFolder '!'])
+    error(['update_last_mh_history_file: I cannot find any mh-history file in ' MetropolisFolder '!'])
 end
 
 BaseName = [BaseName '_mh_history_'];
diff --git a/matlab/utilities/estimation/check_hessian_at_the_mode.m b/matlab/utilities/estimation/check_hessian_at_the_mode.m
index 8fa880253fcc8555590b572b75cc5c8a62640eb6..1e91bf6661a26b93d531a8d0c4000729b4c8c9d2 100644
--- a/matlab/utilities/estimation/check_hessian_at_the_mode.m
+++ b/matlab/utilities/estimation/check_hessian_at_the_mode.m
@@ -2,7 +2,7 @@ function check_hessian_at_the_mode(hessian_xparam1, xparam1, M_, estim_params_,
 % check_hessian_at_the_mode(hessian_xparam1, xparam1, M_, estim_params_, options_, bounds)
 % -------------------------------------------------------------------------
 % This function checks whether the hessian matrix at the mode is positive definite.
-% =========================================================================
+% -------------------------------------------------------------------------
 % INPUTS
 %  o hessian_xparam1:        [matrix] hessian matrix at the mode
 %  o xparam1:                [vector] vector of parameter values at the mode
@@ -17,6 +17,7 @@ function check_hessian_at_the_mode(hessian_xparam1, xparam1, M_, estim_params_,
 % This function is called by
 %  o dynare_estimation_1.m
 % -------------------------------------------------------------------------
+
 % Copyright © 2023 Dynare Team
 %
 % This file is part of Dynare.
@@ -33,7 +34,6 @@ function check_hessian_at_the_mode(hessian_xparam1, xparam1, M_, estim_params_,
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
-% =========================================================================
 
 try
     chol(hessian_xparam1);
diff --git a/matlab/utilities/estimation/check_mode_file.m b/matlab/utilities/estimation/check_mode_file.m
index 29ddb1e84690817d6d94d34daf3711ece75449f5..040c74a80e787c092cb4da3d81d708c2afe5cd5a 100644
--- a/matlab/utilities/estimation/check_mode_file.m
+++ b/matlab/utilities/estimation/check_mode_file.m
@@ -2,7 +2,7 @@ function [xparam1, hh] = check_mode_file(xparam1, hh, options_, bayestopt_)
 % function [xparam1, hh] = check_mode_file(xparam1, hh, options_, bayestopt_)
 % -------------------------------------------------------------------------
 % Check that the provided mode_file is compatible with the current estimation settings.
-% =========================================================================
+% -------------------------------------------------------------------------
 % INPUTS
 %  o xparam1:                [vector] current vector of parameter values at the mode
 %  o hh:                     [matrix] current hessian matrix at the mode
@@ -16,6 +16,7 @@ function [xparam1, hh] = check_mode_file(xparam1, hh, options_, bayestopt_)
 % This function is called by
 %  o dynare_estimation_init.m
 % -------------------------------------------------------------------------
+
 % Copyright © 2023 Dynare Team
 %
 % This file is part of Dynare.
@@ -32,7 +33,6 @@ function [xparam1, hh] = check_mode_file(xparam1, hh, options_, bayestopt_)
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
-% =========================================================================
 
 number_of_estimated_parameters = length(xparam1);
 mode_file = load(options_.mode_file);
diff --git a/matlab/utilities/estimation/check_prior_stderr_corr.m b/matlab/utilities/estimation/check_prior_stderr_corr.m
index 0cdc7b71c1b6c6a8d9b74c1a1349331102f5304c..867e0ba7cd4876dc1c53f4ae5f72b01dda6305a0 100644
--- a/matlab/utilities/estimation/check_prior_stderr_corr.m
+++ b/matlab/utilities/estimation/check_prior_stderr_corr.m
@@ -3,7 +3,7 @@ function check_prior_stderr_corr(estim_params_,bayestopt_)
 % -------------------------------------------------------------------------
 % Check if the prior allows for negative standard deviations and
 % correlations larger than +-1. If so, issue a warning.
-% =========================================================================
+% -------------------------------------------------------------------------
 % INPUTS
 %  o estim_params_:           [struct] information on estimated parameters
 %  o bayestopt_:              [struct] information on priors
@@ -14,6 +14,7 @@ function check_prior_stderr_corr(estim_params_,bayestopt_)
 % This function is called by
 %  o initial_estimation_checks.m
 % -------------------------------------------------------------------------
+
 % Copyright © 2023 Dynare Team
 %
 % This file is part of Dynare.
@@ -30,7 +31,6 @@ function check_prior_stderr_corr(estim_params_,bayestopt_)
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
-% =========================================================================
 
 nvx = estim_params_.nvx; % number of stderr parameters for structural shocks
 if nvx && any(bayestopt_.p3(1:nvx)<0)
diff --git a/matlab/utilities/estimation/check_steady_state_changes_parameters.m b/matlab/utilities/estimation/check_steady_state_changes_parameters.m
index 1cd40b29306dff4467daf6f09dc924c6c519a54f..9f6bdfcea0d9a43b1e224eb2e38a5facdaa9b052 100644
--- a/matlab/utilities/estimation/check_steady_state_changes_parameters.m
+++ b/matlab/utilities/estimation/check_steady_state_changes_parameters.m
@@ -2,7 +2,7 @@ function [steady_state, info, steady_state_changes_parameters] = check_steady_st
 % function [steady_state, info, steady_state_changes_parameters] = check_steady_state_changes_parameters(M_,estim_params_,oo_,options_,steadystate_check_flag_vec)
 % -------------------------------------------------------------------------
 % Check if steady-state solves static model and if it changes estimated parameters
-% =========================================================================
+% -------------------------------------------------------------------------
 % INPUTS
 %  o M_:                         [struct] information on the model
 %  o estim_params_:              [struct] information on estimated parameters
@@ -18,6 +18,7 @@ function [steady_state, info, steady_state_changes_parameters] = check_steady_st
 % This function is called by
 %  o initial_estimation_checks.m
 % -------------------------------------------------------------------------
+
 % Copyright © 2023 Dynare Team
 %
 % This file is part of Dynare.
@@ -34,7 +35,6 @@ function [steady_state, info, steady_state_changes_parameters] = check_steady_st
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
-% =========================================================================
 
 value_parameter_change = 1.01; % value with which parameters are slightly changed.
 steady_state_changes_parameters = false; % initialize
diff --git a/matlab/utilities/estimation/check_varobs_are_endo_and_declared_once.m b/matlab/utilities/estimation/check_varobs_are_endo_and_declared_once.m
index 75daffc917c77c61fa165bbe683300576b829f9b..1cb92635da33eadc8f8e08fed45c1601a3a8ed71 100644
--- a/matlab/utilities/estimation/check_varobs_are_endo_and_declared_once.m
+++ b/matlab/utilities/estimation/check_varobs_are_endo_and_declared_once.m
@@ -4,7 +4,7 @@ function check_varobs_are_endo_and_declared_once(varobs,endo_names)
 % Check that each declared observed variable:
 % - is also an endogenous variable
 % - is declared only once
-% =========================================================================
+% -------------------------------------------------------------------------
 % INPUTS
 %  o varobs:                 [cell] list of observed variables
 %  o endo_names:             [cell] list of endogenous variables
@@ -15,6 +15,7 @@ function check_varobs_are_endo_and_declared_once(varobs,endo_names)
 % This function is called by
 %  o dynare_estimation_init.m
 % -------------------------------------------------------------------------
+
 % Copyright © 2023 Dynare Team
 %
 % This file is part of Dynare.
@@ -31,7 +32,6 @@ function check_varobs_are_endo_and_declared_once(varobs,endo_names)
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
-% =========================================================================
 
 number_of_observed_variables = length(varobs);
 for i = 1:number_of_observed_variables    
diff --git a/matlab/utilities/estimation/set_mcmc_jumping_covariance.m b/matlab/utilities/estimation/set_mcmc_jumping_covariance.m
index b0cb99d49852e79a0dfee3e685138d4722668150..6902d509fe41930c2a41c46bccdfc8a5119d828f 100644
--- a/matlab/utilities/estimation/set_mcmc_jumping_covariance.m
+++ b/matlab/utilities/estimation/set_mcmc_jumping_covariance.m
@@ -2,7 +2,7 @@ function invhess = set_mcmc_jumping_covariance(invhess, xparam_nbr, MCMC_jumping
 % function invhess = set_mcmc_jumping_covariance(invhess, xparam_nbr, MCMC_jumping_covariance, bayestopt_, stringForErrors)
 % -------------------------------------------------------------------------
 % sets the jumping covariance matrix for the MCMC algorithm
-% =========================================================================
+% -------------------------------------------------------------------------
 % INPUTS
 %  o invhess:                 [matrix] already computed inverse of the hessian matrix
 %  o xparam_nbr:              [integer] number of estimated parameters
@@ -16,6 +16,7 @@ function invhess = set_mcmc_jumping_covariance(invhess, xparam_nbr, MCMC_jumping
 % This function is called by
 %  o dynare_estimation_1.m
 % -------------------------------------------------------------------------
+
 % Copyright © 2023 Dynare Team
 %
 % This file is part of Dynare.
@@ -32,7 +33,6 @@ function invhess = set_mcmc_jumping_covariance(invhess, xparam_nbr, MCMC_jumping
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
-% =========================================================================
 
 switch MCMC_jumping_covariance
     case 'hessian' % do nothing and use hessian from previous mode optimization
diff --git a/matlab/utilities/estimation/set_mcmc_prior_bounds.m b/matlab/utilities/estimation/set_mcmc_prior_bounds.m
index 76bbf09ca47f0c213f0d0b7fcd7b2611a02a6741..a94b7b9c6d296981298cc3e733850ce673e8258c 100644
--- a/matlab/utilities/estimation/set_mcmc_prior_bounds.m
+++ b/matlab/utilities/estimation/set_mcmc_prior_bounds.m
@@ -15,6 +15,7 @@ function bounds = set_mcmc_prior_bounds(xparam, bayestopt_, options_, stringForE
 % This function is called by
 %  o dynare_estimation_1.m
 % -------------------------------------------------------------------------
+
 % Copyright © 2023 Dynare Team
 %
 % This file is part of Dynare.
@@ -31,7 +32,6 @@ function bounds = set_mcmc_prior_bounds(xparam, bayestopt_, options_, stringForE
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
-% =========================================================================
 
 bounds = prior_bounds(bayestopt_, options_.prior_trunc);
 outside_bound_pars = find(xparam < bounds.lb | xparam > bounds.ub);
diff --git a/matlab/utilities/estimation/tune_mcmc_mh_jscale_wrapper.m b/matlab/utilities/estimation/tune_mcmc_mh_jscale_wrapper.m
index d0be1e6e87ba0a1f49e9ab5c81eb7f2bf74c6408..0da796f513cd6ebbf74e77a49be771094ff4eb35 100644
--- a/matlab/utilities/estimation/tune_mcmc_mh_jscale_wrapper.m
+++ b/matlab/utilities/estimation/tune_mcmc_mh_jscale_wrapper.m
@@ -3,7 +3,7 @@ function mh_jscale = tune_mcmc_mh_jscale_wrapper(invhess, options_, M_, objectiv
 % -------------------------------------------------------------------------
 % Wrapper to call the algorithm to tune the jumping scale parameter for the
 % Metropolis-Hastings algorithm; currently only supports RW-MH algorithm.
-% =========================================================================
+% -------------------------------------------------------------------------
 % INPUTS
 %  o invhess:                 [matrix] jumping covariance matrix
 %  o options_:                [struct] Dynare options
@@ -17,8 +17,9 @@ function mh_jscale = tune_mcmc_mh_jscale_wrapper(invhess, options_, M_, objectiv
 %  o mh_jscale:               [double] tuned jumping scale parameter
 % -------------------------------------------------------------------------
 % This function is called by
-%  o dynare_estimation_1.m
+%  o dynare_estimation_1
 % -------------------------------------------------------------------------
+
 % Copyright © 2023 Dynare Team
 %
 % This file is part of Dynare.
@@ -35,9 +36,7 @@ function mh_jscale = tune_mcmc_mh_jscale_wrapper(invhess, options_, M_, objectiv
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <https://www.gnu.org/licenses/>.
-% =========================================================================
 
-% get invhess in case of use_mh_covariance_matrix
 posterior_sampler_options_temp = options_.posterior_sampler_options.current_options;
 posterior_sampler_options_temp.invhess = invhess;
 posterior_sampler_options_temp = check_posterior_sampler_options(posterior_sampler_options_temp, M_.fname, M_.dname, options_);
diff --git a/tests/estimation/system_prior_restriction/Gali_2015.mod b/tests/estimation/system_prior_restriction/Gali_2015.mod
index 834b211e5cbadff46d62fb0f9fe21c79e247f994..007a4db24a08828d858bcdec4d39a1346f63945f 100644
--- a/tests/estimation/system_prior_restriction/Gali_2015.mod
+++ b/tests/estimation/system_prior_restriction/Gali_2015.mod
@@ -147,13 +147,13 @@ end;
 varobs yhat;
 
 % Run prior function to get prior slope of the PC based on independent priors
-hh=figure('Name','Slope of the Phillips Curve');
+hh_fig=figure('Name','Slope of the Phillips Curve');
 prior_function(function='Gali_2015_PC_slope');
 PC_slope_vec=cell2mat(oo_.prior_function_results(:,1));
 
 optimal_bandwidth = mh_optimal_bandwidth(PC_slope_vec,length(PC_slope_vec),0,'gaussian');
 [density(:,1),density(:,2)] = kernel_density_estimate(PC_slope_vec,512,length(PC_slope_vec),optimal_bandwidth,'gaussian');
-figure(hh)
+figure(hh_fig)
 subplot(3,1,1)
 plot(density(:,1),density(:,2));
 title('Prior')
@@ -165,7 +165,7 @@ posterior_function(function='Gali_2015_PC_slope');
 PC_slope_vec=cell2mat(oo_.posterior_function_results(:,1));
 optimal_bandwidth = mh_optimal_bandwidth(PC_slope_vec,length(PC_slope_vec),0,'gaussian');
 [density(:,1),density(:,2)] = kernel_density_estimate(PC_slope_vec,512,length(PC_slope_vec),optimal_bandwidth,'gaussian');
-figure(hh)
+figure(hh_fig)
 subplot(3,1,2)
 plot(density(:,1),density(:,2));
 title('Updated Prior')
@@ -178,7 +178,7 @@ posterior_function(function='Gali_2015_PC_slope');
 PC_slope_vec=cell2mat(oo_.posterior_function_results(:,1));
 optimal_bandwidth = mh_optimal_bandwidth(PC_slope_vec,length(PC_slope_vec),0,'gaussian');
 [density(:,1),density(:,2)] = kernel_density_estimate(PC_slope_vec,512,length(PC_slope_vec),optimal_bandwidth,'gaussian');
-figure(hh)
+figure(hh_fig)
 subplot(3,1,3)
 plot(density(:,1),density(:,2));
 title('Posterior')