diff --git a/.gitignore b/.gitignore
index 5163c3a66c8772f4691b61f2f646cde5df866472..d5aefb1d2c00323f642f0756809e3b4444b85709 100644
--- a/.gitignore
+++ b/.gitignore
@@ -70,12 +70,9 @@ doc/internals/*.html
 doc/internals/ltxpng
 
 # MATLAB dir
-/matlab/preprocessor*
+/matlab/preprocessor64/
 /matlab/dynare_version.m
 
-# JULIA dir
-/julia/preprocessor*
-
 # DLL rules
 *.mex
 *.oct
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index b06bfa7685b3c3094af19bcc89e0eb909e478c1c..65806de01fcb71354b840b0e85d3ec33cba5542b 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -33,7 +33,7 @@ build_binaries:
     - make -j $(nproc) LN_S="cp -p"
   artifacts:
     paths:
-      - matlab/preprocessor*/*
+      - preprocessor/dynare-preprocessor
       - mex/octave/
       - mex/matlab/
       - dynare++/parser/cc/*_tab.cc
diff --git a/Makefile.am b/Makefile.am
index 410ca9a22ef1ec784246b9c353bab502f2c929b7..5433c26a0a3a9bfaee12080e184488f9a313a742 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -27,25 +27,29 @@ EXTRA_DIST = \
 	scripts \
 	.dir-locals.el
 
-all-local: preprocessor/src/dynare_m$(EXEEXT)
-	if file preprocessor/src/dynare_m$(EXEEXT) | grep -q x86.64; then \
-	  ARCH="64"; \
-	else \
-	  ARCH="32"; \
-	fi; \
-	mkdir -p $(abs_srcdir)/matlab/preprocessor$$ARCH && \
-	$(LN_S) -f $(abs_builddir)/preprocessor/src/dynare_m$(EXEEXT) $(abs_srcdir)/matlab/preprocessor$$ARCH
+all-local:
+# Create top-level preprocessor symlink needed by matlab/dynare.m (when Dynare is run
+# from the locally-built copy)
+	$(LN_S) -f $(abs_builddir)/preprocessor/src/dynare-preprocessor$(EXEEXT) $(abs_builddir)/preprocessor/dynare-preprocessor$(EXEEXT)
+# Create backward-compatibility symlink for old location of preprocessor
+	$(MKDIR_P) matlab/preprocessor64/
+	$(LN_S) -f $(abs_builddir)/preprocessor/src/dynare-preprocessor$(EXEEXT) $(abs_srcdir)/matlab/preprocessor64/dynare_m$(EXEEXT)
 
 clean-local:
-	rm -rf $(abs_srcdir)/matlab/preprocessor32 $(abs_srcdir)/matlab/preprocessor64
+	rm -f preprocessor/dynare-preprocessor$(EXEEXT)
+	rm -rf matlab/preprocessor64/
 
 dist-hook:
 	rm -rf `find $(distdir)/matlab $(distdir)/examples -name *~`
-	rm -rf $(distdir)/matlab/preprocessor* $(distdir)/matlab/dynare_version.m
+	rm -f $(distdir)/matlab/dynare_version.m
+	rm -rf $(distdir)/matlab/preprocessor64/
 	$(MKDIR_P) $(distdir)/mex/matlab $(distdir)/mex/octave
 	rm -rf `find $(distdir) -name '.git*'`
 
 install-exec-local:
+	$(MKDIR_P) $(DESTDIR)$(pkglibdir)/preprocessor
+# The following will break under Windows, but we don’t use the install rule there
+	$(LN_S) -f $(bindir)/dynare-preprocessor$(EXEEXT) $(DESTDIR)$(pkglibdir)/preprocessor/dynare-preprocessor$(EXEEXT)
 	$(MKDIR_P) $(DESTDIR)$(pkglibdir)/contrib/ms-sbvar/TZcode
 	cp -r contrib/ms-sbvar/TZcode/MatlabFiles $(DESTDIR)$(pkglibdir)/contrib/ms-sbvar/TZcode
 	$(MKDIR_P) $(DESTDIR)$(pkglibdir)/contrib/jsonlab
@@ -53,14 +57,17 @@ install-exec-local:
 	cp -r examples $(DESTDIR)$(pkglibdir)
 	cp -r matlab $(DESTDIR)$(pkglibdir)
 	find $(DESTDIR)$(pkglibdir) -name LICENSE.md -delete
-	rm -rf $(DESTDIR)$(pkglibdir)/matlab/preprocessor*
-	if file preprocessor/src/dynare_m | grep -q x86.64; then \
-	  ARCH="64"; \
-	else \
-	  ARCH="32"; \
-	fi; \
-	mkdir -p $(DESTDIR)$(pkglibdir)/matlab/preprocessor$$ARCH && \
-	cp preprocessor/src/dynare_m $(DESTDIR)$(pkglibdir)/matlab/preprocessor$$ARCH
+# Recreate backward-compatibility symlink
+	rm -f $(DESTDIR)$(pkglibdir)/matlab/preprocessor64/dynare_m$(EXEEXT)
+	$(LN_S) -f $(bindir)/dynare-preprocessor$(EXEEXT) $(DESTDIR)$(pkglibdir)/matlab/preprocessor64/dynare_m$(EXEEXT)
+# We don’t fail over doc install rules, since the user may deliberately not have compiled them
+# (e.g. with the “nodoc” option under Debian)
+	$(MKDIR_P) $(docdir)
+	-cp doc/*.pdf doc/gsa/gsa.pdf doc/parallel/parallel.pdf doc/dseries-and-reporting/dseriesReporting.pdf preprocessor/doc/preprocessor/preprocessor.pdf preprocessor/doc/macroprocessor/macroprocessor.pdf doc/manual/build/latex/dynare-manual.pdf $(docdir)
+	-cp -r doc/manual/build/html $(docdir)/dynare-manual.html
+	$(MKDIR_P) $(docdir)/dynare++
+	-cp dynare++/doc/*.pdf $(docdir)/dynare++
 
 uninstall-local:
 	rm -rf $(DESTDIR)$(pkglibdir)
+	rm -rf $(DESTDIR)$(docdir)
diff --git a/NEWS.md b/NEWS.md
index 1e48180a19b411b5f71ec81ba584c2cfd1591926..bc938cc6c9fd269b91239fd5a155d3cd38b9aa97 100644
--- a/NEWS.md
+++ b/NEWS.md
@@ -1,3 +1,44 @@
+Announcement for Dynare 4.6.3 (on 2020-11-23)
+=============================================
+
+We are pleased to announce the release of Dynare 4.6.3.
+
+This maintenance release fixes various bugs.
+
+The Windows, macOS and source packages are already available for download at
+[the Dynare website](https://www.dynare.org/download/).
+
+All users are strongly encouraged to upgrade.
+
+This release is compatible with MATLAB versions ranging from 7.9 (R2009b) to
+9.9 (R2020b), and with GNU Octave versions 5.2.0 (under Windows) and 4.4.1
+(under macOS).
+
+Here is a list of the problems identified in version 4.6.2 and that have been
+fixed in version 4.6.3:
+
+* Using an unknown symbol in `irf_shocks` option of `stoch_simul` would lead to
+  a crash of the preprocessor
+* `identification` would crash for purely forward-looking models
+* The `endogenous_prior` option did not properly handle missing observations
+* The auxiliary particle filter with pruning and resampling would crash
+* Initialization of the state variance for particle filters was buggy
+* An `@#else` clause after an `@#ifndef` was not correctly interpreted
+* An `@#elseif` clause after an `@#ifdef` or an `@#ifndef` was not correctly
+  interpreted
+* Perfect foresight simulations of models with a single equation would crash
+  when using either the `lmmcp` option or the `linear_approximation`
+* Inequality constraints on endogenous variables (when using the `lmmcp`
+  option) were not enforced on purely backward or purely forward models
+* Perfect foresight simulations with `bytecode` and `block` options could crash
+  if there was a purely forward variable whose value in all periods could be
+  evaluated backward (typically a process of the form `y=a*y(+1)+e`)
+* `extended_path` was broken with `bytecode`
+* Under Windows, with Octave, the k-order perturbation and MS-SBVAR MEX files
+  could not be loaded
+* On Fedora (and possibly other GNU/Linux distributions), compilation from
+  source would fail against Octave 5
+
 Announcement for Dynare 4.6.2 (on 2020-09-07)
 =============================================
 
diff --git a/README.md b/README.md
index 37f72283cf2d6cd09a6e0f8f18d4b13466b4e85c..f9f2272ee3f8f31fe00384c0e46cc305491a9d76 100644
--- a/README.md
+++ b/README.md
@@ -56,6 +56,7 @@ a 32-bit Octave.
 
 1. [**General Instructions**](#general-instructions)
 1. [**Debian or Ubuntu**](#debian-or-ubuntu)
+1. [**Fedora, CentOS or RHEL**](#fedora-centos-or-rhel)
 1. [**Windows**](#windows)
 1. [**macOS**](#macos)
 
@@ -68,9 +69,12 @@ A number of tools and libraries are needed in order to recompile everything. You
 - A POSIX compliant shell and an implementation of Make (mandatory)
 - The [GNU Compiler Collection](http://gcc.gnu.org/), version 8 or later, with
   gcc, g++ and gfortran (mandatory)
-- MATLAB (if you want to compile the MEX for MATLAB)
-- [GNU Octave](http://www.octave.org), with the development headers (if you
-  want to compile the MEX for Octave)
+- [MATLAB](https://mathworks.com) (if you want to compile the MEX for MATLAB)
+- [GNU Octave](http://www.octave.org) with
+  - the development headers (if you want to compile the MEX for Octave)
+  - the development libraries corresponding to the [UMFPACK](https://people.engr.tamu.edu/davis/suitesparse.html) packaged with Octave
+  - Optionally, the [Control](https://wiki.octave.org/Control_package), [IO](https://wiki.octave.org/IO_package), [Optimization](https://wiki.octave.org/Optimization_package) and [Statistics](https://wiki.octave.org/Statistics_package) package either installed via your package manager or through [Octave Forge](https://wiki.octave.org/Category:Octave_Forge).
+
 - [Boost libraries](http://www.boost.org), version 1.36 or later
 - [Bison](http://www.gnu.org/software/bison/), version 3.2 or later (only if you get the source through Git)
 - [Flex](http://flex.sourceforge.net/), version 2.5.4 or later (only if you get the source through Git)
@@ -86,48 +90,35 @@ A number of tools and libraries are needed in order to recompile everything. You
   - [Sphinx](http://www.sphinx-doc.org/)
   - [MathJax](https://www.mathjax.org/)
 - [Doxygen](http://www.stack.nl/%7Edimitri/doxygen/) (if you want to build Dynare preprocessor source documentation)
-- For Octave, the development libraries corresponding to the UMFPACK packaged with Octave
+- [X-13ARIMA-SEATS Seasonal Adjustment Program](https://www.census.gov/srd/www/x13as/)
 
 ### Preparing the sources
 
 If you have downloaded the sources from an official source archive or the source snapshot, just unpack it.
 
 If you want to use Git, do the following from a terminal:
-
-    git clone --recurse-submodules https://git.dynare.org/Dynare/dynare.git
-    cd dynare
-    autoreconf -si
-
-The last line runs Autoconf and Automake in order to prepare the build environment (this is not necessary if you got the sources from an official source archive or the source snapshot).
+```sh
+git clone --recurse-submodules https://git.dynare.org/Dynare/dynare.git
+cd dynare
+autoreconf -si
+```
+The last line runs Autoconf and Automake in order to prepare the build environment (this is not necessary if you got the sources from an official source archive or the source snapshot). If you want a certain version (e.g. 4.6) , then add `--single-branch --branch 4.6` to the git clone command.
 
 ### Configuring the build tree
 
 Simply launch the configure script from a terminal:
+```sh
+./configure --with-matlab=<…>
 ```
-./configure
-```
-If you have MATLAB, you need to indicate both the MATLAB location. For example, on GNU/Linux:
-```
-./configure --with-matlab=/usr/local/MATLAB/R2019a
-```
+where the path to MATLAB is specified.
 
-Alternatively, you can disable the compilation of MEX files for MATLAB with the `--disable-matlab` flag, and MEX files for Octave with `--disable-octave`.
+Some important options:
 
-You may need to specify additional options to the configure script, see the
-output of the `--help` option, and also the platform specific instructions
-below.
+- `--disable-matlab`: skip the compilation of MEX files for MATLAB
+- `--disable-octave`: skip the compilation of MEX files for Octave
+- `--disable-doc`: skip the compilation of the documentation (PDF and HTML)
 
-Note that if you don't want to compile the C/C++ programs with debugging information, you can specify the `CFLAGS` and `CXXFLAGS` variables to the configure script, such as:
-```
-./configure CFLAGS="-O3" CXXFLAGS="-O3"
-```
-To remove debugging information for MATLAB MEX functions, the analogous call would be:
-```
-./configure MATLAB_MEX_CFLAGS="-O3" MATLAB_MEX_CXXFLAGS="-O3"
-```
-
-If the configuration goes well, the script will tell you which components are
-correctly configured and will be built.
+You may need to specify additional options to the configure script, see the output of the `--help` option, and also the platform specific instructions below. If the configuration goes well, the script will tell you which components are correctly configured and will be built. 
 
 Note that it is possible that some MEX files cannot be compiled, due to missing
 build dependencies. If you find no way of installing the missing dependencies,
@@ -143,70 +134,62 @@ addpath <DYNARE_ROOT>/matlab/missing/mex/gensylv
 
 ### Building
 
-Binaries and Info documentation are built with:
-```
+Binaries are built with:
+```sh
 make
 ```
 PDF and HTML documentation are respectively built with:
-```
+```sh
 make pdf
 make html
 ```
-The testsuites can be run with:
-```
-make check
-```
-
-Note that running the testsuite with Octave requires the additional packages
-`pstoedit`, `epstool`, `xfig`, and `gnuplot`.
 
 ### Check
 
 The Git source comes with unit tests (in the MATLAB functions) and integration tests (under the `tests` subfolder). All the tests can be run with:
-```
+```sh
 make check
 ```
-In the `tests` subfolder. If Dynare has been compiled against MATLAB and Octave, the tests will be run with MATLAB and Octave. Depending on
-the performance of your machine, this can take several hours. It is possible to run the tests only with MATLAB:
-```
+in the `tests` subfolder. If Dynare has been compiled against MATLAB and Octave, the tests will be run with both MATLAB and Octave. Depending on the performance of your machine, this can take several hours. It is possible to run the tests only with MATLAB:
+```sh
 make check-matlab
 ```
 or only with Octave:
-```
+```sh
 make check-octave
 ```
-A summary of the results is available in `tests/run_test_matlab_output.txt` or `tests/run_test_octave_output.txt`. Often, it does not make sense
-to run the complete testsuite. For instance, if you modify codes only related to the perfect foresight model solver, you can decide to run only a
-subset of the integration tests, with:
-```
+Note that running the testsuite with Octave requires the additional packages `pstoedit`, `epstool`, `xfig`, and `gnuplot`. 
+
+A summary of the results is available in `tests/run_test_matlab_output.txt` or `tests/run_test_octave_output.txt`. Often, it does not make sense to run the complete testsuite. For instance, if you modify codes only related to the perfect foresight model solver, you can decide to run only a subset of the integration tests, with:
+```sh
 make deterministic_simulations
 ```
 This will run all the integration tests in `tests/deterministic_simulations` with MATLAB and Octave. Again, it is possible to do this only with MATLAB:
-```
+```sh
 make m/deterministic_simulations
 ```
 or with Octave:
-```
+```sh
 make o/deterministic_simulations
 ```
 Finally if you want to run a single integration test, e.g. `deterministic_simulations/lbj/rbc.mod` with MATLAB:
-```
+```sh
 make deterministic_simulations/lbj/rbc.m.trs
 ```
 or with Octave:
-```
+```sh
 make deterministic_simulations/lbj/rbc.o.trs
 ```
 The result of the test (`PASSED` or `FAILED`) will be printed in the terminal, the produced log can be displayed with:
-```
+```sh
 make deterministic_simulations/lbj/rbc.m.drs
 ```
 or
-```
+```sh
 make deterministic_simulations/lbj/rbc.o.drs
 ```
 Note that only tests will be executed where the `m.trs/o.trs` does not yet exist. You can run
-```
+```sh
 make clean
 ```
 in the `tests` folder to delete files that were created by the run of the testsuite. You can also manually delete the desired `m.trs/o.trs` file(s).
@@ -239,11 +222,120 @@ All the prerequisites are packaged:
 - `latexmk`
 - `libjs-mathjax`
 - `doxygen`
+- `x13as`
 
 You can install them all at once with:
+```sh
+apt install build-essential gfortran liboctave-dev libboost-graph-dev libgsl-dev libmatio-dev libslicot-dev libslicot-pic libsuitesparse-dev flex bison autoconf automake texlive texlive-publishers texlive-latex-extra texlive-fonts-extra texlive-latex-recommended texlive-science texlive-plain-generic lmodern python3-sphinx latexmk libjs-mathjax doxygen x13as
 ```
-apt install build-essential gfortran liboctave-dev libboost-graph-dev libgsl-dev libmatio-dev libslicot-dev libslicot-pic libsuitesparse-dev flex bison autoconf automake texlive texlive-publishers texlive-latex-extra texlive-fonts-extra texlive-latex-recommended texlive-science texlive-plain-generic lmodern python3-sphinx latexmk libjs-mathjax doxygen
+If you use MATLAB, we strongly advise to also `apt install matlab-support` and confirm to rename the GCC libraries shipped with MATLAB to avoid possible conflicts with GCC libraries shipped by your distribution.
+
+Tested on
+- Debian 10
+- Ubuntu 20.04
+- Ubuntu 20.10
+
+## Fedora, CentOS or RHEL
+
+Almost all prerequisites are packaged:
+
+- `gcc`, `gcc-c++`, `make`
+- `gcc-gfortran`
+- `lapack` and `lapack-devel`
+- `openblas` and `openblas-devel`
+- `boost-devel`
+- `gsl-devel`
+- `matio-devel`
+- `suitesparse-devel`
+- `flex`
+- `bison`
+- `autoconf`
+- `automake`
+- `redhat-rpm-config`
+-  `octave`, `octave-devel`, `octave-statistics`, `octave-io`, `octave-optim`, `octave-control`
+- `texlive-scheme-minimal`, `texlive-collection-publishers`, `texlive-collection-latexextra`, `texlive-collection-fontsextra`, `texlive-collection-latexrecommended`, `texlive-collection-science`, `texlive-collection-plaingeneric`, `texlive-lm`
+- `python3-sphinx`
+- `latexmk`
+- `mathjax`
+- `doxygen`
+
+You can install them all at once with:
+```sh
+# Minimal packages (use --disable-doc and --disable-octave flags)
+dnf install -y gcc gcc-c++ make gcc-gfortran lapack lapack-devel openblas openblas-devel boost-devel gsl-devel matio-devel suitesparse-devel flex bison autoconf automake redhat-rpm-config
+# Octave packages (use --disable-doc flag)
+dnf install octave octave-devel octave-statistics octave-io octave-optim octave-control
+# Documentation packages
+dnf install texlive-scheme-minimal texlive-collection-publishers texlive-collection-latexextra texlive-collection-fontsextra texlive-collection-latexrecommended texlive-collection-science texlive-collection-plaingeneric texlive-lm python3-sphinx latexmk mathjax doxygen
+```
+In Fedora these are available from the default repositories; whereas for CentOS and RHEL you need to enable the [Extra Packages for Enterprise Linux (EPEL)](https://fedoraproject.org/wiki/EPEL) repository and either the PowerTools repository for CentOS or the CodeReady Linux Builder repository for RHEL:
+```sh
+yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm
+# CentOS 8
+dnf config-manager --set-enabled PowerTools
+# RHEL 8
+ARCH=$( /bin/arch )
+subscription-manager repos --enable "codeready-builder-for-rhel-8-${ARCH}-rpms"
+```
+The documentation packages have slightly different names in CentOS and RHEL, you can also choose to pass the `--disable-doc` flag to your configure script to skip these dependencies.
+
+`Slicot` and `x13as` need to be compiled from source:
+
+```sh
+# compile slicot from source and put it into /home/$USER/dynare/slicot/lib/
+mkdir -p /home/$USER/dynare/slicot
+cd /home/$USER/dynare/slicot
+wget https://deb.debian.org/debian/pool/main/s/slicot/slicot_5.0+20101122.orig.tar.gz
+tar xf slicot_5.0+20101122.orig.tar.gz
+cd slicot-5.0+20101122
+make FORTRAN=gfortran OPTS="-O2 -fPIC -fdefault-integer-8" LOADER=gfortran lib
+mkdir -p /home/$USER/dynare/slicot/lib
+cp slicot.a /home/$USER/dynare/slicot/lib/libslicot64_pic.a #for matlab
+cp slicot.a /home/$USER/dynare/slicot/lib/libslicot_pic.a #for octave
+
+# compile x13as from source and put it into /usr/bin/
+mkdir -p /home/$USER/dynare/x13as
+cd /home/$USER/dynare/x13as
+wget https://www.census.gov/ts/x13as/unix/x13assrc_V1.1_B39.tar.gz
+tar xf x13assrc_V1.1_B39.tar.gz
+sed -i "s|-static| |" makefile.gf # this removes '-static' in the makefile.gf
+make -f makefile.gf FFLAGS="-O2 -std=legacy" PROGRAM=x13as
+sudo cp x13as /usr/bin/
+```
+
+If you use MATLAB, we strongly advise to also rename or exclude the GCC libraries shipped with MATLAB to avoid possible conflicts with GCC libraries shipped by Fedora, see e.g. [Matlab on Fedora 33](https://mutschler.eu/linux/install-guides/fedora-post-install/#matlab) or [MATLAB-ArchWiki](https://wiki.archlinux.org/index.php/MATLAB) for instructions.
+
+Keep in mind to use the `--with-slicot` option to the configure command, e.g.:
+```sh
+cd /home/$USER/dynare
+git clone --recurse-submodules https://git.dynare.org/dynare/dynare.git unstable
+cd unstable
+autoreconf -si
+./configure --with-slicot=/home/$USER/dynare/slicot --with-matlab=/usr/local/MATLAB/R2020b
+make -j$(($(nproc)+1)) #rule of thumb: one more than CPUs as shown by e.g. lscpu
+```
+
+If your distribution ships an older version of `bison`, compile it from source and append it *temporarily* to your path before calling the configure script:
+```sh
+bison --version # bison (GNU Bison) 3.0.4
+mkdir -p /home/$USER/dynare/bison
+cd /home/$USER/dynare/bison
+wget http://ftp.gnu.org/gnu/bison/bison-3.6.4.tar.gz #change the version number accordingly
+tar xf bison-3.6.4.tar.gz
+cd bison-3.6.4
+./configure --prefix=/home/$USER/dynare/bison
+make
+make install
+export PATH=/home/$USER/dynare/bison/bin:$PATH
+bison --version # bison (GNU Bison) 3.6.4
 ```
+Now configure dynare as above.
+
+Tested on
+- CentOS 8
+- Fedora Workstation 32
+- Fedora Workstation 33
+- Red Hat Enterprise Linux 8
 
 ## Windows
 
@@ -251,18 +343,18 @@ apt install build-essential gfortran liboctave-dev libboost-graph-dev libgsl-dev
   have a 32-bit Windows, in which case see below)
 - Run a MSYS MinGW 64-bit shell
 - Update the system:
-```
+```sh
 pacman -Syu
 ```
   You may be asked to close the window at the end of the
   first upgrade batch, in which case you should rerun the upgrade in a new
   window to complete the upgrade.
 - Install all needed dependencies:
-```
+```sh
 pacman -S git autoconf automake-wrapper bison flex make tar texinfo mingw-w64-x86_64-gcc mingw-w64-x86_64-gcc-fortran mingw-w64-x86_64-boost mingw-w64-x86_64-gsl mingw-w64-x86_64-matio mingw-w64-x86_64-openblas
 ```
 - Compile and install SLICOT, needed for the `kalman_steady_state` MEX file
-```
+```sh
 wget https://deb.debian.org/debian/pool/main/s/slicot/slicot_5.0+20101122.orig.tar.gz
 tar xf slicot_5.0+20101122.orig.tar.gz
 cd slicot-5.0+20101122
@@ -272,13 +364,13 @@ cp slicot.a /usr/local/lib/libslicot64_pic.a
 cd ..
 ```
 - Prepare the Dynare sources, either by unpacking the source tarball, or with:
-```
+```sh
 git clone --recurse-submodules https://git.dynare.org/Dynare/dynare.git
 cd dynare
 autoreconf -si
 ```
 - Configure Dynare from the source directory:
-```
+```sh
 ./configure --with-slicot=/usr/local --with-matlab=<…> --disable-octave --disable-doc
 ```
 where the path of MATLAB is specified. Note that you should use
@@ -288,11 +380,11 @@ does not have short filenames (8dot3), then you can run `mkdir -p
 /usr/local/MATLAB && mount c:/Program\ Files/MATLAB /usr/local/MATLAB`, and
 then pass `/usr/local/MATLAB/…` as MATLAB path to the configure script.
 - Compile:
-```
+```sh
 make
 ```
 - Run the testsuite:
-```
+```sh
 make -C tests check-matlab
 ```
 
@@ -309,43 +401,53 @@ currently not supported.
 
 ## macOS
 
-To simply use a snapshot of Dynare, you have two choices. On MATLAB, you can
-use the [snapshot build](https://www.dynare.org/snapshot/macos/) provided by
-Dynare. On Octave, you can simply install [Homebrew](https://brew.sh/) and run
-```brew install dynare --HEAD``` (See the Install Dynare (unstable) section of
-[this webpage](https://archives.dynare.org/DynareWiki/InstallOnMacOSX) for more
-details).
-
-If you do not wish to use the snapshots provided by Dynare or Homebrew, follow
-the directions below to build Dynare on your local machine.
-
 Preparatory work:
 
-- Install the Xcode Command Line Tools:
-    - Open Terminal.app and type `xcode-select --install`
+- Install the Xcode Command Line Tools. Open Terminal.app and type:
+```sh
+xcode-select --install
+```
 - Install [Homebrew](https://brew.sh/) by following the instructions on their website
-
-The following commands will install the programs that Dynare needs to
-compile. They should be entered at the command prompt in Terminal.app.
-
-- `brew install automake bison flex boost fftw gcc gsl hdf5 libmatio metis veclibfort`
-- **(Optional)** To compile Dynare mex files for use on Octave:
-    - `brew install octave`
-- **(Optional)** To compile Dynare documentation
-     - Install the latest version of [MacTeX](http://www.tug.org/mactex/), deselecting the option to install Ghostscript
-     - `brew install doxygen latex2html`
+- Install [MacTeX](http://www.tug.org/mactex/index.html). Alternatively, if you
+  don’t want to install MacTeX, you should pass the `--disable-doc` flag to the
+  `configure` command below.
+- Install required Homebrew packages. Open Terminal.app and type:
+```sh
+brew install automake bison flex boost gcc gsl libmatio veclibfort octave sphinx-doc wget
+brew link --force sphinx-doc
+```
+- Compile and install SLICOT, needed for the `kalman_steady_state` MEX file.
+Still from Terminal.app:
+```sh
+wget https://deb.debian.org/debian/pool/main/s/slicot/slicot_5.0+20101122.orig.tar.gz
+tar xf slicot_5.0+20101122.orig.tar.gz
+cd slicot-5.0+20101122
+make -j$(nproc) FORTRAN=gfortran OPTS="-O2" LOADER=gfortran lib
+cp slicot.a /usr/local/lib/libslicot_pic.a
+make clean
+make -j$(nproc) FORTRAN=gfortran OPTS="-O2 -fdefault-integer-8" LOADER=gfortran lib
+cp slicot.a /usr/local/lib/libslicot64_pic.a
+cd ..
+```
 
 The following commands will download the Dynare source code and compile
 it. They should be entered at the command prompt in Terminal.app from the
 folder where you want Dynare installed.
 
-- `git clone --recurse-submodules https://git.dynare.org/Dynare/dynare.git`
-- `cd dynare`
-- `PATH="/usr/local/opt/bison/bin:/usr/local/opt/flex/bin:$PATH"`
-- `autoreconf -si`
-- `CC=gcc-9 CXX=g++-9 ./configure --disable-octave --with-matlab=/Applications/MATLAB_R2019a.app --with-matio=/usr/local --with-gsl=/usr/local --with-slicot=/usr/local`, adjusting the MATLAB path to accord with your local installation. If you don't have MATLAB, simply remove `--with-matlab=/Applications/MATLAB_R2019a.app` from the above command
-- `make -j`
-- **(Optional)** To then build mex files for Octave, run
-     - `cd mex/build/octave`
-     - `CC=gcc-9 CXX=g++-9 ./configure --with-matio=/usr/local --with-gsl=/usr/local --with-slicot=/usr/local LDFLAGS=-L/usr/local/lib`
-     - `make -j`
+- Prepare the Dynare sources:
+```sh
+git clone --recurse-submodules https://git.dynare.org/Dynare/dynare.git`
+cd dynare
+autoreconf -si
+```
+- Configure Dynare from the source directory:
+```sh
+./configure --with-matlab=<…> CC=gcc-10 CXX=g++-10 CPPFLAGS=-I/usr/local/include LDFLAGS=-L/usr/local/lib LEX=/usr/local/opt/flex/bin/flex YACC=/usr/local/opt/bison/bin/bison
+```
+where the path to MATLAB is specified, typically of the form
+`/Applications/MATLAB_R2020b.app`. If you don’t have MATLAB, simply replace
+`--with-matlab=<…>` in the above command by `--disable-matlab`.
+- Compile:
+```sh
+make -j$(nproc)
+```
diff --git a/doc/manual/source/bibliography.rst b/doc/manual/source/bibliography.rst
index a8442cbca60a93bdf191fb3a18fc756775c804d4..d2552a8c0fdf80f6b35feddde489764fd20e3069 100644
--- a/doc/manual/source/bibliography.rst
+++ b/doc/manual/source/bibliography.rst
@@ -71,4 +71,5 @@ Bibliography
 * Smets, Frank and Rafael Wouters (2003): “An Estimated Dynamic Stochastic General Equilibrium Model of the Euro Area,” *Journal of the European Economic Association*, 1(5), 1123–1175.
 * Stock, James H. and Mark W. Watson (1999). “Forecasting Inflation,”, *Journal of Monetary Economics*, 44(2), 293–335.
 * Uhlig, Harald (2001): “A Toolkit for Analysing Nonlinear Dynamic Stochastic Models Easily,” in *Computational Methods for the Study of Dynamic Economies*, Eds. Ramon Marimon and Andrew Scott, Oxford University Press, 30–61.
+* U.S. Census Bureau (2017): “X-13 ARIMA-SEATSReference Manual”.
 * Villemot, Sébastien (2011): “Solving rational expectations models at first order: what Dynare does,” *Dynare Working Papers*, 2, CEPREMAP.
diff --git a/doc/manual/source/examples.rst b/doc/manual/source/examples.rst
index 457086877c601a477cfbb872fea5ea811b191616..471dd42097835a404c3532a2c4976c9434cf17d0 100644
--- a/doc/manual/source/examples.rst
+++ b/doc/manual/source/examples.rst
@@ -61,4 +61,10 @@ description, please refer to the comments inside the files themselves.
 
     File demonstrating how to conduct optimal policy experiments in a 
     simple New Keynesian model either under commitment (Ramsey) or using
-    optimal simple rules (OSR)
\ No newline at end of file
+    optimal simple rules (OSR)
+
+``Ramsey_steady_file.mod``
+
+    File demonstrating how to conduct optimal policy experiments in a 
+    simple New Keynesian model under commitment (Ramsey) with a user-defined
+    conditional steady state file
\ No newline at end of file
diff --git a/doc/manual/source/index.rst b/doc/manual/source/index.rst
index 8c01b1220238c3f098e6e5bdfac2559c2d3d9408..5e0abf5ce2b32be1978f986f182cf4bd6b79a0ce 100644
--- a/doc/manual/source/index.rst
+++ b/doc/manual/source/index.rst
@@ -3,12 +3,11 @@ The Dynare Reference Manual, version |version|
 
 Currently the development team of Dynare is composed of:
 
-* Stéphane Adjemian (Université du Maine, Gains)
+* Stéphane Adjemian (Le Mans Université, Gains)
 * Houtan Bastani
 * Michel Juillard (Banque de France)
-* Sumudu Kankanamge (Toulouse School of Economics)
-* Frédéric Karamé (Université du Maine, Gains and CEPREMAP)
-* Dóra Kocsis (CEPREMAP)
+* Sumudu Kankanamge (Toulouse School of Economics and CEPREMAP)
+* Frédéric Karamé (Le Mans Université, Gains and CEPREMAP)
 * Junior Maih (Norges Bank)
 * Ferhat Mihoubi (Université Paris-Est Créteil, Érudite and CEPREMAP)
 * Willi Mutschler (University of Münster)
@@ -22,10 +21,11 @@ The following people used to be members of the team:
 * Alejandro Buesa
 * Fabrice Collard
 * Assia Ezzeroug
+* Dóra Kocsis
 * Stéphane Lhuissier
 * George Perendia
 
-Copyright © 1996-2020, Dynare Team.
+Copyright © 1996-2021, Dynare Team.
 
 Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 
diff --git a/doc/manual/source/introduction.rst b/doc/manual/source/introduction.rst
index 9628823564da540a52fa8769dccc96a82e93e0a9..c17a929d86ac4319f3821aa1eff9a88bfec24a1b 100644
--- a/doc/manual/source/introduction.rst
+++ b/doc/manual/source/introduction.rst
@@ -95,8 +95,8 @@ You should cite Dynare if you use it in your research. The
 recommended way todo this is to cite the present manual, as:
 
     Stéphane Adjemian, Houtan Bastani, Michel Juillard, Frédéric
-    Karamé, Junior Maih, Ferhat Mihoubi, George Perendia, Johannes Pfeifer, Marco
-    Ratto and Sébastien Villemot (2011), “Dynare: Reference Manual,
+    Karamé, Junior Maih, Ferhat Mihoubi, Willi Mutschler, George Perendia, Johannes Pfeifer, 
+    Marco Ratto and Sébastien Villemot (2011), “Dynare: Reference Manual,
     Version 4,” *Dynare Working Papers*, 1, CEPREMAP
 
 For convenience, you can copy and paste the following into your BibTeX file:
@@ -106,8 +106,8 @@ For convenience, you can copy and paste the following into your BibTeX file:
         @TechReport{Adjemianetal2011,
           author      = {Adjemian, St\'ephane and Bastani, Houtan and
                          Juillard, Michel and Karam\'e, Fr\'ederic and
-                         Maih, Junior and Mihoubi, Ferhat and
-                         Perendia, George and Pfeifer, Johannes and
+                         Maih, Junior and Mihoubi, Ferhat and Mutschler, Willi
+                         and Perendia, George and Pfeifer, Johannes and
                          Ratto, Marco and Villemot, S\'ebastien},
           title       = {Dynare: Reference Manual Version 4},
           year        = {2011},
diff --git a/doc/manual/source/running-dynare.rst b/doc/manual/source/running-dynare.rst
index 772696994125ba3b2ed11015b1729e585253e70f..0406ff663c71541f660115ce12fa59c5e1051a60 100644
--- a/doc/manual/source/running-dynare.rst
+++ b/doc/manual/source/running-dynare.rst
@@ -534,7 +534,10 @@ by the ``dynare`` command.
     ``M_``,``oo_``, and ``options_`` structures are saved in a file
     called ``FILENAME_results.mat``. If they exist, ``estim_params_``,
     ``bayestopt_``, ``dataset_``, ``oo_recursive_`` and
-    ``estimation_info`` are saved in the same file.
+    ``estimation_info`` are saved in the same file. Note that Matlab 
+    by default only allows ``.mat``-files up to 2GB. You can lift this 
+    restriction by enabling the ``save -v7.3``-option in 
+    ``Preferences -> General -> MAT-Files``.
 
     .. matvar:: M_
 
diff --git a/doc/manual/source/the-model-file.rst b/doc/manual/source/the-model-file.rst
index 74c956d02f31ed3e4bb7395e3f340e46651e039c..bd15b5a403a16dcab0e74c129b1866abc7181490 100644
--- a/doc/manual/source/the-model-file.rst
+++ b/doc/manual/source/the-model-file.rst
@@ -1137,9 +1137,8 @@ equations using the ``write_latex_static_model`` command.
         * Endogenous variables with leads or lags greater or equal
           than two will have been removed, replaced by new auxiliary
           variables and equations,
-        * For a stochastic model, exogenous variables with leads or
-          lags will also have been replaced by new auxiliary variables
-          and equations.
+        * Exogenous variables with leads or lags will also have been replaced
+          by new auxiliary variables and equations.
 
     For the required LaTeX packages, see
     :comm:`write_latex_original_model`.
@@ -1221,9 +1220,8 @@ auxiliary endogenous variables—along with corresponding auxiliary
 equations—which will appear in the final output.
 
 The main transformation concerns leads and lags. Dynare will perform a
-transformation of the model so that there is only one lead and one lag
-on endogenous variables and, in the case of a stochastic model, no
-leads/lags on exogenous variables.
+transformation of the model so that there is only one lead and one lag on
+endogenous variables and no leads/lags on exogenous variables.
 
 This transformation is achieved by the creation of auxiliary variables
 and corresponding equations. For example, if ``x(+2)`` exists in the
@@ -3842,7 +3840,7 @@ Computing the stochastic solution
        :mvar:`oo_.conditional_variance_decomposition_ME`).  The
        variance decomposition is only conducted, if theoretical
        moments are requested, *i.e.* using the ``periods=0``-option.
-       Only available at ``order<3``. In case of ``order=2``,
+       Only available at ``order<3`` and without ``pruning''. In case of ``order=2``,
        Dynare provides a second-order accurate
        approximation to the true second moments based on the linear
        terms of the second-order solution (see *Kim, Kim,
@@ -3859,7 +3857,11 @@ Computing the stochastic solution
        algorithm of *Kim, Kim, Schaumburg and Sims (2008)*, while at
        third order its generalization by *Andreasen,
        Fernández-Villaverde and Rubio-Ramírez (2018)* is used.
-       Not available above third order.
+       Not available above third order. When specified, theoretical moments
+       are based on the pruned state space, i.e. the computation of second moments 
+       uses all terms as in *Andreasen, Fernández-Villaverde and Rubio-Ramírez (2018), page 10* 
+       as opposed to simply providing a second-order accurate result based on the 
+       linear solution as in *Kim, Kim, Schaumburg and Sims (2008)*.
 
     .. option:: partial_information
 
@@ -4261,7 +4263,9 @@ which is described below.
        the endogenous variables are generated by assuming that the
        agents believe that there will no more shocks after period
        :math:`t+S`. This is an experimental feature and can be quite
-       slow. Default: ``0``.
+       slow. A non-zero value is not compatible with either the
+       ``bytecode`` or the ``block`` option of the ``model`` block.
+       Default: ``0``.
 
     .. option:: hybrid
 
@@ -5114,9 +5118,9 @@ block decomposition of the model (see :opt:`block`).
 
     .. option:: mh_replic = INTEGER
 
-       Number of replications for Metropolis-Hastings algorithm. For
-       the time being, ``mh_replic`` should be larger
-       than 1200. Default: ``20000``.
+       Number of replications for each chain of the Metropolis-Hastings algorithm. 
+       The number of draws should be sufficient to achieve convergence of the MCMC and 
+       to meaningfully compute posterior objects. Default: ``20000``.
 
     .. option:: sub_draws = INTEGER
 
@@ -5357,6 +5361,14 @@ block decomposition of the model (see :opt:`block`).
                 (available under MATLAB if the Global Optimization
                 Toolbox is installed; not available under Octave).
 
+           ``13``
+
+                Uses the ``lsqnonlin`` non-linear least squares optimization
+                routine (available under MATLAB if the Optimization Toolbox is
+                installed; available under Octave if the `optim
+                <https://octave.sourceforge.io/optim/>`__ package from
+                Octave-Forge is installed). ``101``
+
            ``101``
 
                 Uses the SolveOpt algorithm for local nonlinear
@@ -8950,11 +8962,6 @@ Optimal policy under commitment (Ramsey)
     optimal policy for the first time and committing not to
     re-optimize in the future.
 
-    Because it entails computing at least a second order approximation, the
-    computation of the planner objective value is skipped with a message when
-    the model is too large (more than 180 state variables, including lagged
-    Lagrange multipliers).
-
 .. command:: ramsey_policy [VARIABLE_NAME...];
              ramsey_policy (OPTIONS...) [VARIABLE_NAME...];
 
@@ -9039,8 +9046,9 @@ Optimal policy under discretion
     under discretion. The algorithm implemented is essentially an LQ
     solver, and is described by *Dennis (2007)*.
 
-    You should ensure that your model is linear and your objective is
-    quadratic. Also, you should set the ``linear`` option of the
+    You must ensure that your objective is quadratic. Regarding the model, it must 
+    either be linear or solved at first order with an analytical steady state provided. 
+    In the first case, you should set the ``linear`` option of the
     ``model`` block.
 
     It is possible to use the :comm:`estimation` command after the
@@ -9842,6 +9850,12 @@ Performing identification analysis
         Tolerance level for selecting non-zero singular values.
         Default: ``1.e-3``.
 
+    .. option:: schur_vec_tol = DOUBLE
+
+        Tolerance level used to find nonstationary variables in Schur decomposition 
+        of the transition matrix.
+        Default: ``1.e-11``.
+
 *Identification Strength Options*
 
     .. option:: no_identification_strength
@@ -12212,7 +12226,7 @@ Misc commands
     and ``morefloats``.
 
 
-.. _Dynare wiki: https://archives.dynare.org/DynareWiki/EquationsTags
+.. _Dynare wiki: https://archives.dynare.org/DynareWiki/
 .. _io: https://octave.sourceforge.io/io/
 .. _AIM website: https://www.federalreserve.gov/econres/ama-index.htm
 
diff --git a/doc/manual/source/time-series.rst b/doc/manual/source/time-series.rst
index f7dd8d484cf447168649418e3367cd8001c9fb94..2f6a786308cac91e91215189fbb82e664e2ebc72 100644
--- a/doc/manual/source/time-series.rst
+++ b/doc/manual/source/time-series.rst
@@ -10,10 +10,12 @@ Time Series
 
 Dynare provides a MATLAB/Octave class for handling time series data,
 which is based on a class for handling dates. Dynare also provides a
-new type for dates, so that the basic user does not have to worry
-about class and methods for dates. Below, you will first find the
-class and methods used for creating and dealing with dates and then
-the class used for using time series.
+new type for dates, so that the user does not have to worry about
+class and methods for dates. Below, you will first find the class and
+methods used for creating and dealing with dates and then the class
+used for using time series. Dynare also provides an interface to the
+X-13 ARIMA-SEATS seasonal adjustment program produced, distributed, and
+maintained by the US Census Bureau.
 
 
 Dates
@@ -85,44 +87,42 @@ below. Basic operations can be performed on dates:
     Tests if two ``dates`` objects are equal. ``+1950Q1==1950Q2``
     returns ``true``, ``1950Q1==1950Q2`` returns ``false``. If the compared
     objects have both ``n>1`` elements, the ``eq`` operator returns a
-    column vector, ``n`` by ``1``, of zeros and ones.
+    column vector, ``n`` by ``1``, of logicals.
 
 **ne operator (not equal, ~=)**
 
     Tests if two ``dates`` objects are not equal. ``+1950Q1~=``
     returns ``false`` while ``1950Q1~=1950Q2`` returns ``true``. If the
     compared objects both have ``n>1`` elements, the ``ne`` operator
-    returns an ``n`` by ``1`` column vector of zeros and ones.
+    returns an ``n`` by ``1`` column vector of logicals.
 
 **lt operator (less than, <)**
 
     Tests if a ``dates`` object preceeds another ``dates`` object. For
     instance, ``1950Q1<1950Q3`` returns ``true``. If the compared objects
     have both ``n>1`` elements, the ``lt`` operator returns a column
-    vector, ``n`` by ``1``, of zeros and ones.
+    vector, ``n`` by ``1``, of logicals.
 
 **gt operator (greater than, >)**
 
     Tests if a ``dates`` object follows another ``dates`` object. For
     instance, ``1950Q1>1950Q3`` returns ``false``. If the compared objects
     have both ``n>1`` elements, the ``gt`` operator returns a column
-    vector, ``n`` by ``1``, of zeros and ones.
+    vector, ``n`` by ``1``, of logicals.
 
 **le operator (less or equal, <=)**
 
     Tests if a ``dates`` object preceeds another ``dates`` object or
     is equal to this object. For instance, ``1950Q1<=1950Q3`` returns
     ``true``. If the compared objects have both ``n>1`` elements, the
-    ``le`` operator returns a column vector, ``n`` by ``1``, of zeros
-    and ones.
+    ``le`` operator returns a column vector, ``n`` by ``1``, of logicals.
 
 **ge operator (greater or equal, >=)**
 
     Tests if a ``dates`` object follows another ``dates`` object or is
     equal to this object. For instance, ``1950Q1>=1950Q3`` returns
     ``false``. If the compared objects have both ``n>1`` elements, the
-    ``ge`` operator returns a column vector, ``n`` by ``1``, of zeros
-    and ones.
+    ``ge`` operator returns a column vector, ``n`` by ``1``, of logicals.
 
 One can select an element, or some elements, in a ``dates`` object as
 he would extract some elements from a vector in MATLAB/Octave. Let ``a
@@ -164,13 +164,15 @@ The dates class
 
 .. class:: dates
 
-    :arg int freq: equal to 1, 4, or 12 (resp. for annual,
-                   quarterly, or monthly dates).
-    :arg int ndat: the number of declared dates in the object.
-    :arg int time: a ``ndat*2`` array, the years are stored in the
-                   first column, the subperiods (1 for annual dates,
-                   1-4 for quarterly dates, and 1-12 for monthly
-                   dates) are stored in the second column.
+    :arg freq: equal to 1, 4, 12 or 365 (resp. for annual, quarterly,
+               monthly, or daily dates).
+    :arg time: a ``n*2`` array of integers. If `freq` is equal to 1,
+               4, or 12, the years are stored in the first column, the
+               subperiods (1 for annual dates, 1-4 for quarterly
+               dates, and 1-12 for monthly dates) are stored in the
+               second column. If `freq` is equal to 365, the first
+               column stores the number of days since the first day of
+               year 0, the second column is not used.
 
     Each member is private, one can display the content of a member
     but cannot change its value directly. Note that it is not possible
@@ -185,14 +187,14 @@ The dates class
         |br| Returns an empty ``dates`` object with a given frequency
         (if the constructor is called with one input
         argument). ``FREQ`` is a character equal to ’Y’ or ’A’ for
-        annual dates, ’Q’ for quarterly dates, or ’M’ for monthly
-        dates. Note that ``FREQ`` is not case sensitive, so that, for
-        instance, ’q’ is also allowed for quarterly dates. The
-        frequency can also be set with an integer scalar equal to 1
-        (annual), 4 (quarterly), or 12 (monthly). The instantiation of
-        empty objects can be used to rename the ``dates`` class. For
-        instance, if one only works with quarterly dates, object
-        ``qq`` can be created as::
+        annual dates, ’Q’ for quarterly dates, ’M’ for monthly dates,
+        or ’D’ for daily dates. Note that ``FREQ`` is not case
+        sensitive, so that, for instance, ’q’ is also allowed for
+        quarterly dates. The frequency can also be set with an integer
+        scalar equal to 1 (annual), 4 (quarterly), 12
+        (monthly), or 365 (daily). The instantiation of empty objects can be used to
+        rename the ``dates`` class. For instance, if one only works
+        with quarterly dates, object ``qq`` can be created as::
 
             qq = dates('Q')
 
@@ -201,7 +203,14 @@ The dates class
             d0 = qq(2009,2);
 
         which is much simpler if ``dates`` objects have to be defined
-        programmatically.
+        programmatically. For daily dates, we would instantiate an
+        empty daily dates object as::
+
+            dd = dates('D')
+
+        and a ``dates`` object holding the date ``2020-12-31``::
+
+            d1 = dd(2020,12,31);
 
 
     .. construct:: dates(STRING)
@@ -211,11 +220,11 @@ The dates class
         given by the string ``STRING``. This string has to be
         interpretable as a date (only strings of the following forms
         are admitted: ``'1990Y'``, ``'1990A'``, ``'1990Q1'``,
-        ``'1990M2'``), the routine ``isdate`` can be used to test if a
-        string is interpretable as a date. If more than one argument
-        is provided, they should all be dates represented as strings,
-        the resulting ``dates`` object contains as many elements as
-        arguments to the constructor.
+        ``'1990M2'``, or ``'2020-12-31'``), the routine ``isdate`` can
+        be used to test if a string is interpretable as a date. If
+        more than one argument is provided, they should all be dates
+        represented as strings, the resulting ``dates`` object
+        contains as many elements as arguments to the constructor.
 
 
     .. construct:: dates(DATES)
@@ -229,15 +238,16 @@ The dates class
         constructor.
 
 
-    .. construct:: dates (FREQ, YEAR, SUBPERIOD)
+    .. construct:: dates (FREQ, YEAR, SUBPERIOD[, S])
 
-        |br| where ``FREQ`` is a single character (’Y’, ’A’, ’Q’, ’M’)
-        or integer (1, 4, or 12) specifying the frequency, ``YEAR``
-        and ``SUBPERIOD`` are ``n*1`` vectors of integers. Returns a
-        ``dates`` object with ``n`` elements. If ``FREQ`` is equal to
-        ``'Y'``, ``'A'`` or ``1``, the third argument is not needed
-        (because ``SUBPERIOD`` is necessarily a vector of ones in this
-        case).
+        |br| where ``FREQ`` is a single character (’Y’, ’A’, ’Q’, ’M’,
+        ’D’) or integer (1, 4, 12, or 365) specifying the frequency,
+        ``YEAR`` and ``SUBPERIOD`` and ``S`` are ``n*1`` vectors of
+        integers. Returns a ``dates`` object with ``n`` elements. The
+        last argument, ``S``, is only to be used for daily
+        frequency. If ``FREQ`` is equal to ``'Y'``, ``'A'`` or ``1``,
+        the third argument is not needed (because ``SUBPERIOD`` is
+        necessarily a vector of ones in this case).
 
 
     *Example*
@@ -248,6 +258,7 @@ The dates class
             do2 = dates('1950Q2','1950Q3');
             do3 = dates(do1,do2);
             do4 = dates('Q',1950, 1);
+            do5 = dates('D',1973, 1, 25);
 
 
     A list of the available methods, by alphabetical order, is given
@@ -338,11 +349,11 @@ The dates class
                 '1950Q1'
 
 
-   .. datesmethod:: C = colon (A, B)
+    .. datesmethod:: C = colon (A, B)
                      C = colon (A, i, B)
 
-        |br| Overloads the MATLAB/Octave colon (``:``) operator. A and B
-        are ``dates`` objects. The optional increment ``i`` is a
+        |br| Overloads the MATLAB/Octave colon (``:``) operator. A and
+        B are ``dates`` objects. The optional increment ``i`` is a
         scalar integer (default value is ``i=1``). This method returns
         a ``dates`` object and can be used to create ranges of dates.
 
@@ -366,12 +377,12 @@ The dates class
         |br| Returns a copy of a ``dates`` object.
 
 
-     .. datesmethod:: disp (A)
+    .. datesmethod:: disp (A)
 
         |br| Overloads the MATLAB/Octave disp function for ``dates`` object.
 
 
-     .. datesmethod:: display (A)
+    .. datesmethod:: display (A)
 
         |br| Overloads the MATLAB/Octave display function for ``dates`` object.
 
@@ -555,7 +566,7 @@ The dates class
 
                   1
 
-     .. datesmethod:: C = isequal (A, B)
+    .. datesmethod:: C = isequal (A, B)
 
         |br| Overloads the MATLAB/Octave ``isequal`` function.
 
@@ -616,7 +627,7 @@ The dates class
                    203
 
 
-        .. datesmethod:: C = lt (A, B)
+    .. datesmethod:: C = lt (A, B)
 
         |br| Overloads the MATLAB/Octave ``lt`` (less than,
         ``<``) operator. ``dates`` objects ``A`` and ``B`` must have
@@ -861,7 +872,7 @@ The dates class
 
                 >> A = dates('1950Q1');
                 >> A = A:A+1;
-                >> strings(A)
+                >> A.strings()
 
                   ans =
 
@@ -873,7 +884,8 @@ The dates class
     .. datesmethod:: B = subperiod (A)
 
         |br| Returns the subperiod of a date (an integer scalar
-        between 1 and ``A.freq``).
+        between 1 and ``A.freq``). This method is not implemented for
+        daily dates.
 
         *Example*
 
@@ -987,16 +999,14 @@ The dseries class
     data. As any MATLAB/Octave statements, this class can be used in a
     Dynare’s mod file. A ``dseries`` object has six members:
 
-    :arg name: A ``nobs*1`` cell of strings or a ``nobs*p`` character
-               array, the names of the variables.
-    :arg tex: A ``nobs*1`` cell of strings or a ``nobs*p`` character
-              array, the tex names of the variables.
+    :arg name: A ``vobs*1`` cell of strings or a ``vobs*p`` character array, the names of the variables.
+    :arg tex: A ``vobs*1`` cell of strings or a ``vobs*p`` character array, the tex names of the variables.
     :arg dates dates: An object with ``nobs`` elements, the dates of the sample.
     :arg double data: A ``nobs`` by ``vobs`` array, the data.
     :arg ops: The history of operations on the variables.
     :arg tags: The user-defined tags on the variables.
 
-    ``data``, ``name``, ``tex`` are private members. The following
+    ``data``, ``name``, ``tex``, and ``ops`` are private members. The following
     constructors are available:
 
     .. construct:: dseries ()
@@ -1021,8 +1031,6 @@ The dseries class
             INIT__ = '1994Q3';
             NAMES__ = {'azert';'yuiop'};
             TEX__ = {'azert';'yuiop'};
-            TAGS__ = struct()
-            DATA__ = {}
 
             azert = randn(100,1);
             yuiop = randn(100,1);
@@ -1367,7 +1375,7 @@ The dseries class
                5Y | 0.66997
 
 
-   .. dseriesmethod:: B = cumprod (A[, d[, v]])
+    .. dseriesmethod:: B = cumprod (A[, d[, v]])
                       cumprod_ (A[, d[, v]])
 
         |br| Overloads the MATLAB/Octave ``cumprod`` function for
@@ -1510,6 +1518,12 @@ The dseries class
         detrended with a different polynomial.
 
 
+    .. dseriesmethod:: B = dgrowth (A)
+                       dgrowth_ (A)
+
+        |br| Computes daily growth rates.
+
+
     .. dseriesmethod:: B = diff (A)
                        diff_ (A)
 
@@ -1659,6 +1673,13 @@ The dseries class
        |br| Returns the first period where all the variables in ``dseries`` object ``A`` are observed (non NaN).
 
 
+    .. dseriesmethod:: B = flip (A)
+                       flip_ (A)
+
+       |br| Flips the rows in the data member (without changing the
+       periods order).
+
+
     .. dseriesmethod:: f = frequency (B)
 
         |br| Returns the frequency of the variables in ``dseries`` object ``B``.
@@ -2028,8 +2049,10 @@ The dseries class
 
     .. dseriesmethod:: B = mdiff (A)
                        mdiff_ (A)
+                       B = mgrowth (A)
+                       mgrowth_ (A)
 
-       |br| Computes monthly growth rates of variables in
+       |br| Computes monthly differences or growth rates of variables in
        ``dseries`` object ``A``.
 
 
@@ -2299,6 +2322,16 @@ The dseries class
         otherwise (default) the arithmetic mean is reported.
 
 
+    .. dseriesmethod:: B = nanstd (A[, geometric])
+
+        |br| Overloads the MATLAB/Octave ``nanstd`` function for
+        ``dseries`` objects. Returns the standard deviation of each
+        variable in ``dseries`` object ``A`` ignoring the NaN
+        values. If the second argument is ``true`` the geometric std
+        is computed, default value of the second argument is
+        ``false``.
+
+
     .. dseriesmethod:: C = ne (A, B)
 
         |br| Overloads the MATLAB/Octave ``ne`` (not equal, ``~=``)
@@ -2478,6 +2511,39 @@ The dseries class
                 3Y | 1          | 1
 
 
+    .. dseriesmethod:: A = projection (A, info, periods)
+
+        |br| Projects variables in dseries object ``A``. ``info`` is
+        is a :math:`n \times 3` cell array. Each row provides
+        informations necessary to project a variable. The first column
+        contains the name of variable (row char array). the second
+        column contains the name of the method used to project the
+        associated variable (row char array), possible values are
+        ``'Trend'``, ``'Constant'``, and ``'AR'``. Last column
+        provides quantitative information about the projection. If the
+        second column value is ``'Trend'``, the third column value is
+        the growth factor of the (exponential) trend. If the second
+        column value is ``'Constant'``, the third column value is the
+        level of the variable. If the second column value is ``'AR'``,
+        the third column value is the autoregressive parameter. The
+        variables can be projected with an AR(p) model, if the third
+        column contains a 1×p vector of doubles. The stationarity of
+        the AR(p) model is not tested. The case of the constant
+        projection, using the last value of the variable, is covered
+        with 'Trend' and a growth factor equal to 1, or 'AR' with an
+        autoregressive parameter equal to one (random walk).  This
+        projection routine only deals with exponential trends.
+
+        *Example*
+
+            ::
+
+                >> data = ones(10,4);
+                >> ts = dseries(data, '1990Q1', {'A1', 'A2', 'A3', 'A4'});
+                >> info = {'A1', 'Trend', 1.2; 'A2', 'Constant', 0.0; 'A3', 'AR', .5; 'A4', 'AR', [.4, -.2]};
+                >> ts.projection(info, 10);
+
+
     .. dseriesmethod:: B = qdiff (A)
                        B = qgrowth (A)
                        qdiff_ (A)
@@ -2592,6 +2658,44 @@ The dseries class
                 2Y | 1          | 1     | 1
 
 
+    .. dseriesmethod:: A = resetops (A, ops)
+
+        |br| Redefine ``ops`` member.
+
+
+    .. dseriesmethod:: A = resetags (A, ops)
+
+        |br| Redefine ``tags`` member.
+
+
+    .. dseriesmethod:: B = round (A[, n])
+                       round_ (A[, n])
+
+        |br| Rounds to the nearest decimal or integer. ``n`` is the
+        precision parameter (number of decimals), default value is 0
+        meaning that that by default the method rounds to the nearest
+        integer.
+
+        *Example*
+
+            ::
+
+                >> ts = dseries(pi)
+
+                ts is a dseries object:
+
+                   | Variable_1
+                1Y | 3.1416
+
+                >> ts.round_();
+                >> ts
+
+                ts is a dseries object:
+
+                   | Variable_1
+                1Y | 3
+
+
     .. dseriesmethod:: save (A, basename[, format])
 
         |br| Overloads the MATLAB/Octave ``save`` function and saves
@@ -2697,6 +2801,28 @@ The dseries class
         (default value of the second argument is ``false``).
 
 
+    .. dseriesmethod:: B = subsample (A, d1, d2)
+
+        |br| Returns a subsample, for periods between ``dates`` ``d1``
+        and ``d2``. The same can be achieved by indexing a
+        ``dseries`` object with a ``dates`` object, but the
+        ``subsample`` method is easier to use programmatically.
+
+        *Example*
+
+            ::
+
+                >> o = dseries(transpose(1:5));
+                >> o.subsample(dates('2y'),dates('4y'))
+
+                ans is a dseries object:
+
+                   | Variable_1
+                2Y | 2
+                3Y | 3
+                4Y | 4
+
+
     .. dseriesmethod:: A = tag (A, a[, b, c])
 
         |br| Add a tag to a variable in ``dseries`` object ``A``.
@@ -2795,9 +2921,224 @@ The dseries class
                     2
 
 
-.. dseriesmethod:: B = ydiff (A)
-                   B = ygrowth (A)
-                   ydiff_ (A)
-                   ygrowth_ (A)
+    .. dseriesmethod:: B = ydiff (A)
+                       B = ygrowth (A)
+                       ydiff_ (A)
+                       ygrowth_ (A)
 
         |br| Computes yearly differences or growth rates.
+
+
+.. _x13-members:
+
+X-13 ARIMA-SEATS interface
+==========================
+
+.. class:: x13
+
+    |br| The x13 class provides a method for each X-13 command as
+    documented in the X-13 ARIMA-SEATS reference manual (`x11`,
+    `automdl`, `estimate`, ...), options can then be passed by
+    key/value pairs. The ``x13`` class has 22 members:
+
+    :arg y: ``dseries`` object with a single variable.
+    :arg x: ``dseries`` object with an arbitrary number of variables (to be used in the REGRESSION block).
+    :arg arima: structure containing the options of the ARIMA model command.
+    :arg automdl: structure containing the options of the ARIMA model selection command.
+    :arg regression: structure containing the options of the Regression command.
+    :arg estimate: structure containing the options of the estimation command.
+    :arg transform: structure containing the options of the transform command.
+    :arg outlier: structure containing the options of the outlier command.
+    :arg forecast: structure containing the options of the forecast command.
+    :arg check: structure containing the options of the check command.
+    :arg x11: structure containing the options of the X11 command.
+    :arg force: structure containing the options of the force command.
+    :arg history: structure containing the options of the history command.
+    :arg metadata: structure containing the options of the metadata command.
+    :arg identify: structure containing the options of the identify command.
+    :arg pickmdl: structure containing the options of the pickmdl command.
+    :arg seats: structure containing the options of the seats command.
+    :arg slidingspans: structure containing the options of the slidingspans command.
+    :arg spectrum: structure containing the options of the spectrum command.
+    :arg x11regression: structure containing the options of the x11Regression command.
+    :arg results: structure containing the results returned by x13.
+    :arg commands: cell array containing the list of commands.
+
+    All these members are private. The following constructors are available:
+
+    .. construct:: x13 (y)
+
+        |br| Instantiates an ``x13`` object with `dseries` object
+        ``y``. The ``dseries`` object passed as an argument must
+        contain only one variable, the one we need to pass to X-13.
+
+
+    .. construct:: x13 (y, x)
+
+        |br| Instantiates an ``x13`` object with `dseries` objects
+        ``y`` and ``x``. The first ``dseries`` object passed as an
+        argument must contain only one variable, the second
+        ``dseries`` object contains the exogenous variables used by
+        some of the X-13 commands. Both objects must be defined on the
+        same time span.
+
+
+    The Following methods allow to set sequence of X-13 commands, write an `.spc` file and run the X-13 binary:
+
+
+    .. x13method:: A = arima (A, key, value[, key, value[, [...]]])
+
+        Interface to the ``arima`` command, see the X-13 ARIMA-SEATS
+        reference manual. All the options must be passed by key/value
+        pairs.
+
+
+    .. x13method:: A = automdl (A, key, value[, key, value[, [...]]])
+
+        Interface to the ``automdl`` command, see the X-13 ARIMA-SEATS
+        reference manual. All the options must be passed by key/value
+        pairs.
+
+
+    .. x13method:: A = regression (A, key, value[, key, value[, [...]]])
+
+        Interface to the ``regression`` command, see the X-13
+        ARIMA-SEATS reference manual. All the options must be passed
+        by key/value pairs.
+
+
+    .. x13method:: A = estimate (A, key, value[, key, value[, [...]]])
+
+        Interface to the ``estimate`` command, see the X-13
+        ARIMA-SEATS reference manual. All the options must be passed
+        by key/value pairs.
+
+
+    .. x13method:: A = transform (A, key, value[, key, value[, [...]]])
+
+        Interface to the ``transform`` command, see the X-13
+        ARIMA-SEATS reference manual. All the options must be passed
+        by key/value pairs.
+
+
+    .. x13method:: A = outlier (A, key, value[, key, value[, [...]]])
+
+        Interface to the ``outlier`` command, see the X-13 ARIMA-SEATS
+        reference manual. All the options must be passed by key/value
+        pairs.
+
+
+    .. x13method:: A = forecast (A, key, value[, key, value[, [...]]])
+
+        Interface to the ``forecast`` command, see the X-13
+        ARIMA-SEATS reference manual. All the options must be passed
+        by key/value pairs.
+
+
+    .. x13method:: A = check (A, key, value[, key, value[, [...]]])
+
+        Interface to the ``check`` command, see the X-13 ARIMA-SEATS
+        reference manual. All the options must be passed by key/value
+        pairs.
+
+
+    .. x13method:: A = x11 (A, key, value[, key, value[, [...]]])
+
+        Interface to the ``x11`` command, see the X-13 ARIMA-SEATS
+        reference manual. All the options must be passed by key/value
+        pairs.
+
+
+    .. x13method:: A = force (A, key, value[, key, value[, [...]]])
+
+        Interface to the ``force`` command, see the X-13 ARIMA-SEATS
+        reference manual. All the options must be passed by key/value
+        pairs.
+
+
+    .. x13method:: A = history (A, key, value[, key, value[, [...]]])
+
+        Interface to the ``history`` command, see the X-13 ARIMA-SEATS
+        reference manual. All the options must be passed by key/value
+        pairs.
+
+
+    .. x13method:: A = metadata (A, key, value[, key, value[, [...]]])
+
+        Interface to the ``metadata`` command, see the X-13
+        ARIMA-SEATS reference manual. All the options must be passed
+        by key/value pairs.
+
+
+    .. x13method:: A = identify (A, key, value[, key, value[, [...]]])
+
+        Interface to the ``identify`` command, see the X-13
+        ARIMA-SEATS reference manual. All the options must be passed
+        by key/value pairs.
+
+
+    .. x13method:: A = pickmdl (A, key, value[, key, value[, [...]]])
+
+        Interface to the ``pickmdl`` command, see the X-13 ARIMA-SEATS
+        reference manual. All the options must be passed by key/value
+        pairs.
+
+
+    .. x13method:: A = seats (A, key, value[, key, value[, [...]]])
+
+        Interface to the ``seats`` command, see the X-13 ARIMA-SEATS
+        reference manual. All the options must be passed by key/value
+        pairs.
+
+
+    .. x13method:: A = slidingspans (A, key, value[, key, value[, [...]]])
+
+        Interface to the ``slidingspans`` command, see the X-13
+        ARIMA-SEATS reference manual. All the options must be passed
+        by key/value pairs.
+
+
+    .. x13method:: A = spectrum (A, key, value[, key, value[, [...]]])
+
+        Interface to the ``spectrum`` command, see the X-13
+        ARIMA-SEATS reference manual. All the options must be passed
+        by key/value pairs.
+
+
+    .. x13method:: A = x11regression (A, key, value[, key, value[, [...]]])
+
+        Interface to the ``x11regression`` command, see the X-13
+        ARIMA-SEATS reference manual. All the options must be passed
+        by key/value pairs.
+
+
+    .. x13method:: print (A[, basefilename])
+
+        Prints an ``.spc`` file with all the X-13 commands. The
+        optional second argument is a row char array specifying the
+        name (without extension) of the file.
+
+
+    .. x13method:: run (A)
+
+        Calls the X-13 binary and run the previously defined
+        commands. All the results are stored in the structure
+        ``A.results``. When it makes sense these results are saved in
+        ``dseries`` objects (*e.g.* for forecasts or filtered variables).
+
+
+    *Example*
+
+            ::
+
+                >> ts = dseries(rand(100,1),'1999M1');
+                >> o = x13(ts);
+
+                >> o.x11('save','(d11)');
+                >> o.automdl('savelog','amd','mixed','no');
+                >> o.outlier('types','all','save','(fts)');
+                >> o.check('maxlag',24,'save','(acf pcf)');
+                >> o.estimate('save','(mdl est)');
+                >> o.forecast('maxlead',18,'probability',0.95,'save','(fct fvr)');
+
+                >> o.run();
diff --git a/doc/manual/utils/dynare_dom.py b/doc/manual/utils/dynare_dom.py
index 765625b825f1f90187d252e4f59971a6bd32808d..d286601e18c79120992f7d7d4dc410ce7f3836ec 100644
--- a/doc/manual/utils/dynare_dom.py
+++ b/doc/manual/utils/dynare_dom.py
@@ -121,6 +121,8 @@ class DynObject(ObjectDescription):
             return _('%s (dates method)') % name
         elif self.objtype == 'dseriesmethod':
             return _('%s (dseries method)') % name
+        elif self.objtype == 'x13method':
+            return _('%s (x13 method)') % name
         elif self.objtype == 'reportingmethod':
             return _('%s (reporting method)') % name
         elif self.objtype == 'matcomm':
@@ -176,6 +178,10 @@ class DseriesMethod(DynCallable):
     display_prefix = 'Method: '
     allow_nesting = True
 
+class X13Method(DynCallable):
+    display_prefix = 'Method: '
+    allow_nesting = True
+
 class ReportingMethod(DynCallable):
     display_prefix = 'Method: '
     allow_nesting = True
@@ -294,7 +300,8 @@ class DynareDomain(Domain):
     'function':          ObjType(_('function'),         'func'),
     'datesmethod':       ObjType(_('method'),           'datmeth'),
     'dseriesmethod':     ObjType(_('method'),           'dsermeth'),
-    'reportingmethod':   ObjType(_('method'),       'repmeth'),
+    'x13method':         ObjType(_('method'),           'x13meth'),
+    'reportingmethod':   ObjType(_('method'),           'repmeth'),
     'matcomm':           ObjType(_('matlab command'),   'mcomm'),
     'command':           ObjType(_('command'),          'comm'),
     'class':             ObjType(_('class'),            'class'),
@@ -312,6 +319,7 @@ class DynareDomain(Domain):
     'function':          DynFunction,
     'datesmethod':       DatesMethod,
     'dseriesmethod':     DseriesMethod,
+    'x13method':         X13Method,
     'reportingmethod':   ReportingMethod,
     'matcomm':           MatComm,
     'command':           DynComm,
@@ -330,6 +338,7 @@ class DynareDomain(Domain):
     'func':     DynareXRefRole(),
     'datmeth':  DynareXRefRole(),
     'dsermeth': DynareXRefRole(),
+    'x13meth':  DynareXRefRole(),
     'repmeth':  DynareXRefRole(),
     'mcomm':    DynareXRefRole(),
     'comm':     DynareXRefRole(),
diff --git a/doc/parallel/parallel.tex b/doc/parallel/parallel.tex
index 55bbd28e054e6847d6ee9e9642cbaf0080fc01fe..a13dd2f59a2369bcd93f48bdb99369cbcc682e2d 100644
--- a/doc/parallel/parallel.tex
+++ b/doc/parallel/parallel.tex
@@ -248,7 +248,7 @@ The configuration file is designed as follows:
 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[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";
diff --git a/dynare++/kord/journal.cc b/dynare++/kord/journal.cc
index b8eaabd473f5c3ad975b7af55391553e0996e029..3ddfcef1ce66ce520b7e92753d8a843043b1f5ea 100644
--- a/dynare++/kord/journal.cc
+++ b/dynare++/kord/journal.cc
@@ -1,6 +1,6 @@
 /*
  * Copyright © 2004-2011 Ondra Kamenik
- * Copyright © 2019 Dynare Team
+ * Copyright © 2019-2020 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -203,8 +203,8 @@ Journal::printHeader()
   *this << "Dynare++ v. " << VERSION << '\n'
         << '\n'
         << u8"Copyright © 2004-2011 Ondra Kamenik\n"
-        << u8"Copyright © 2019 Dynare Team\n"
-        << "Dynare++ comes with ABSOLUTELY NO WARRANTY and is distributed under the GNU GPL,"
+        << u8"Copyright © 2019-2020 Dynare Team\n"
+        << "Dynare++ comes with ABSOLUTELY NO WARRANTY and is distributed under the GNU GPL,\n"
         << "version 3 or later (see https://www.gnu.org/licenses/gpl.html)\n"
         << "\n\n"
         << "System info: ";
@@ -219,7 +219,15 @@ Journal::printHeader()
   *this << ", processors online: " << std::thread::hardware_concurrency()
         << "\n\nStart time: ";
   std::time_t t = std::time(nullptr);
-  *this << std::put_time(std::localtime(&t), "%c %Z")
+  // NB: in the date/time string, we avoid using locale-specific strings (#1751)
+  *this << std::put_time(std::localtime(&t),
+#ifndef _WIN32
+                         "%F %T %z"
+#else
+                         // Specifiers introduced in C++11 don’t work under Windows…
+                         "%Y-%m-%d %H:%M:%S"
+#endif
+                         )
         << "\n\n"
         << u8"  ┌────╼ elapsed time (seconds)                     \n"
         << u8"  │       ┌────╼ record unique identifier           \n"
diff --git a/dynare++/kord/journal.hh b/dynare++/kord/journal.hh
index 63b77a9b931fcbb94424c42b88e1c02cfc6853c3..58ce81772e627be1ea6377832fba466a68ca2b10 100644
--- a/dynare++/kord/journal.hh
+++ b/dynare++/kord/journal.hh
@@ -1,6 +1,6 @@
 /*
  * Copyright © 2004 Ondra Kamenik
- * Copyright © 2019 Dynare Team
+ * Copyright © 2019-2020 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -57,14 +57,18 @@ struct SystemResources
 
 class Journal : public std::ofstream
 {
-  int ord;
-  int depth;
+  int ord{0};
+  int depth{0};
 public:
   explicit Journal(const std::string &fname)
-    : std::ofstream(fname), ord(0), depth(0)
+    : std::ofstream(fname)
   {
     printHeader();
   }
+  /* Constructor that does not initialize the std::ofstream. To be used when an
+     on-disk journal is not wanted. */
+  Journal() = default;
+  Journal &operator=(Journal &&) = default;
   ~Journal() override
   {
     flush();
diff --git a/dynare++/src/main.cc b/dynare++/src/main.cc
index 6d53d0331ecde9280e98807cfa2f8f8693967b52..f29e06ebf8ea6fc3fadcc34d3962e4726334a4ac 100644
--- a/dynare++/src/main.cc
+++ b/dynare++/src/main.cc
@@ -1,6 +1,6 @@
 /*
  * Copyright © 2004-2011 Ondra Kamenik
- * Copyright © 2019 Dynare Team
+ * Copyright © 2019-2020 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -47,7 +47,7 @@ main(int argc, char **argv)
       std::cout << "Dynare++ v. " << VERSION << '\n'
                 << '\n'
                 << u8"Copyright © 2004-2011 Ondra Kamenik\n"
-                << u8"Copyright © 2019 Dynare Team\n"
+                << u8"Copyright © 2019-2020 Dynare Team\n"
                 << "Dynare++ comes with ABSOLUTELY NO WARRANTY and is distributed under the GNU GPL,\n"
                 << "version 3 or later (see https://www.gnu.org/licenses/gpl.html)\n";
       return EXIT_SUCCESS;
diff --git a/examples/Ramsey_steady_file.mod b/examples/Ramsey_steady_file.mod
new file mode 100644
index 0000000000000000000000000000000000000000..1d8db31a84c172ed9b0449a16b4028cd330e6192
--- /dev/null
+++ b/examples/Ramsey_steady_file.mod
@@ -0,0 +1,119 @@
+/*
+ * This file replicates the model studied in:
+ * Lawrence J. Christiano, Roberto Motto and Massimo Rostagno (2007):
+ * "Notes on Ramsey-Optimal Monetary Policy", Section 2
+ * The paper is available at http://faculty.wcas.northwestern.edu/~lchrist/d16/d1606/ramsey.pdf
+ * 
+ * Notes:
+ * - This mod-files allows to simulate a simple New Keynesian Model with Rotemberg price 
+ *      adjustment costs under fully optimal monetary under commitment (Ramsey)
+ *
+ *  - This files shows how to use a userd-defined conditional steady state file in the Ramsey case. It takes
+ *      the value of the defined instrument R as given and then computes the rest of the steady 
+ *      state, including the steady state inflation rate, based on this value. The initial value 
+ *      of the instrument for steady state search must then be defined in an initval-block.
+ *
+ * This implementation was written by Johannes Pfeifer.
+ *
+ * If you spot mistakes, email me at jpfeifer@gmx.de
+ *
+ * Please note that the following copyright notice only applies to this Dynare 
+ * implementation of the model.
+ */
+
+/*
+ * Copyright (C) 2019 Dynare Team
+ *
+ * This 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.
+ *
+ * It 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.
+ *
+ * For a copy of the GNU General Public License,
+ * see <http://www.gnu.org/licenses/>.
+ */
+
+
+var C       $C$                 (long_name='Consumption')
+    pi      $\pi$               (long_name='Gross inflation')
+    h       $h$                 (long_name='hours worked')
+    Z       $Z$                 (long_name='TFP')
+    R       $R$                 (long_name='Net nominal interest rate')
+    log_C   ${\ln C}$           (long_name='Log Consumption')
+    log_h   ${\ln h}$           (long_name='Log hours worked')
+    pi_ann  ${\pi^{ann}}$       (long_name='Annualized net inflation')
+    R_ann   ${R^{ann}}$         (long_name='Annualized net nominal interest rate')
+    r_real  ${r^{ann,real}}$    (long_name='Annualized net real interest rate')
+    y_nat   ${y^{nat}}$         (long_name='Natural (flex price) output')
+    y_gap   ${r^{gap}}$         (long_name='Output gap')
+;
+
+varexo epsilon ${\varepsilon}$     (long_name='TFP shock')
+    ;
+
+parameters beta     ${\beta}$       (long_name='discount factor')
+        theta       ${\theta}$      (long_name='substitution elasticity')
+        tau         ${\tau}$        (long_name='labor subsidy')
+        chi         ${\chi}$        (long_name='labor disutility')
+        phi         ${\phi}$        (long_name='price adjustment costs')
+        rho         ${\rho}$        (long_name='TFP autocorrelation')
+        ;
+
+beta=0.99;
+theta=5;
+phi=100;
+rho=0.9;
+tau=0;
+chi=1;
+        
+model;
+    [name='Euler equation']
+    1/(1+R)=beta*C/(C(+1)*pi(+1));
+    [name='Firm FOC']
+    (tau-1/(theta-1))*(1-theta)+theta*(chi*h*C/(exp(Z))-1)=phi*(pi-1)*pi-beta*phi*(pi(+1)-1)*pi(+1);
+    [name='Resource constraint']
+    C*(1+phi/2*(pi-1)^2)=exp(Z)*h;
+    [name='TFP process']
+    Z=rho*Z(-1)+epsilon;
+    [name='Definition log consumption']
+    log_C=log(C);
+    [name='Definition log hours worked']
+    log_h=log(h);
+    [name='Definition annualized inflation rate']
+    pi_ann=4*log(pi);
+    [name='Definition annualized nominal interest rate']
+    R_ann=4*R;
+    [name='Definition annualized real interest rate']
+    r_real=4*log((1+R)/pi(+1));
+    [name='Definition natural output']
+    y_nat=exp(Z)*sqrt((theta-1)/theta*(1+tau)/chi);
+    [name='output gap']
+    y_gap=log_C-log(y_nat);
+end;
+
+initval;
+    R=1/beta-1;
+end;
+
+shocks;
+    var epsilon = 0.01^2;
+end;
+
+//use Ramsey optimal policy
+
+//define planner objective, which corresponds to utility function of agents
+planner_objective log(C)-chi/2*h^2;
+
+//set up Ramsey optimal policy problem with interest rate R as the instrument,...
+// defining the discount factor in the planner objective to be the one of private agents        
+ramsey_model(instruments=(R),planner_discount=beta,planner_discount_latex_name=$\beta$); 
+
+//conduct stochastic simulations of the Ramsey problem
+stoch_simul(order=1,irf=20,periods=500) pi_ann log_h R_ann log_C Z r_real;
+evaluate_planner_objective;
+
diff --git a/examples/Ramsey_steady_file_steadystate.m b/examples/Ramsey_steady_file_steadystate.m
new file mode 100644
index 0000000000000000000000000000000000000000..c5b48448797ba5dec71e80fb6dbc0921239683e7
--- /dev/null
+++ b/examples/Ramsey_steady_file_steadystate.m
@@ -0,0 +1,79 @@
+function [ys,params,check] = Ramsey_steady_file_steadystate(ys,exo,M_,options_)
+% function [ys,params,check] = Ramsey_steady_file_steadystate(ys,exo,M_,options_)
+% computes the steady state for the Ramsey_steady_file.mod, conditional on
+% the instrument value provided
+%
+% Inputs: 
+%   - ys        [vector] vector of initial values for the steady state of
+%                   the endogenous variables
+%   - exo       [vector] vector of values for the exogenous variables
+%   - M_        [structure] Dynare model structure
+%   - options   [structure] Dynare options structure
+%
+% Output: 
+%   - ys        [vector] vector of steady state values for the the endogenous variables
+%   - params    [vector] vector of parameter values
+%   - check     [scalar] set to 0 if steady state computation worked and to
+%                    1 of not (allows to impose restrictions on parameters)
+
+% Copyright (C) 2020 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 <http://www.gnu.org/licenses/>.
+
+% read out parameters to access them with their name
+beta=NaN; %make parameter known to Matlab function, prevents crashes due to Matlab function with same name;
+          %will be overwritten next
+          
+NumberOfParameters = M_.param_nbr;
+for ii = 1:NumberOfParameters
+  paramname = M_.param_names{ii};
+  eval([ paramname ' = M_.params(' int2str(ii) ');']);
+end
+
+% read in instrument values
+for ii = 1:size(options_.instruments,1)
+  eval([options_.instruments{ii} ' = ys(strmatch(options_.instruments{ii},M_.endo_names,''exact'')) ;']);
+end
+% initialize indicator
+check = 0;
+
+
+%% Enter model equations here
+
+    Z=0;
+    pi=(R+1)*beta;
+    C=sqrt((1+1/theta*((1-beta)*(pi-1)*pi-(tau-1/(theta-1))*(1-theta)))/(chi*(1+phi/2*(pi-1)^2)));
+    h=C*(1+phi/2*(pi-1)^2);
+    log_C=log(C);
+    log_h=log(h);
+    pi_ann=4*log(pi);
+    R_ann=4*R;
+    r_real=4*log((1+R)/pi);
+    y_nat=sqrt((theta-1)/theta*(1+tau)/chi);
+    y_gap=log_C-log(y_nat);
+
+%% end own model equations
+
+params=NaN(NumberOfParameters,1);
+for iter = 1:length(M_.params) %update parameters set in the file
+  eval([ 'params(' num2str(iter) ') = ' M_.param_names{iter} ';' ])
+end
+
+NumberOfEndogenousVariables = M_.orig_endo_nbr; %auxiliary variables are set automatically
+for ii = 1:NumberOfEndogenousVariables
+  varname = M_.endo_names{ii};
+  eval(['ys(' int2str(ii) ') = ' varname ';']);
+end
diff --git a/license.txt b/license.txt
index 18e5e35bb9553a4a336c594d0915c2f89ed8594f..9a514fc233323d426801edeec494a557b3335754 100644
--- a/license.txt
+++ b/license.txt
@@ -1,11 +1,10 @@
 Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
 Upstream-Name: Dynare
-Upstream-Contact: Dynare Team, whose members in 2020 are:
+Upstream-Contact: Dynare Team, whose members in 2021 are:
                   - Stéphane Adjemian <stephane.adjemian@univ-lemans.fr>
                   - Houtan Bastani <houtan@dynare.org>
                   - Michel Juillard <michel.juillard@mjui.fr>
                   - Frédéric Karamé <frederic.karame@univ-lemans.fr>
-                  - Dóra Kocsis <dora@dynare.org>
                   - Junior Maih <junior.maih@gmail.com>
                   - Ferhat Mihoubi <fmihoubi@univ-evry.fr>
                   - Willi Mutschler <willi@mutschler.eu>
@@ -17,12 +16,13 @@ Upstream-Contact: Dynare Team, whose members in 2020 are:
                   - Alejandro Buesa
                   - Fabrice Collard
                   - Assia Ezzeroug
+                  - Dóra Kocsis
                   - Stéphane Lhuissier
                   - George Perendia
 Source: https://www.dynare.org
 
 Files: *
-Copyright: 1996-2020 Dynare Team
+Copyright: 1996-2021 Dynare Team
 License: GPL-3+
 
 Files: matlab/AIM/SP*
diff --git a/m4/ax_mexopts.m4 b/m4/ax_mexopts.m4
index 60fda3441a371de8fb6094a18942d905bb846858..6f46ced2fd813612648cfc8cb4bdfe303e45dec9 100644
--- a/m4/ax_mexopts.m4
+++ b/m4/ax_mexopts.m4
@@ -64,7 +64,7 @@ case ${MATLAB_ARCH} in
     OPENMP_LDFLAGS="-Wl,-Bstatic,--whole-archive -lgomp -Wl,-Bdynamic,--no-whole-archive"
     ax_mexopts_ok="yes"
     ;;
-  maci | maci64)
+  maci64)
     MACOSX_DEPLOYMENT_TARGET='10.9'
     MATLAB_DEFS="$MATLAB_DEFS -DNDEBUG"
     MATLAB_CFLAGS="-fno-common -arch x86_64 -mmacosx-version-min=$MACOSX_DEPLOYMENT_TARGET -fexceptions"
@@ -72,7 +72,10 @@ case ${MATLAB_ARCH} in
     MATLAB_FCFLAGS="-g -O2 -fexceptions -fbackslash -arch x86_64"
     MATLAB_LDFLAGS_NOMAP="-Wl,-twolevel_namespace -undefined error -arch x86_64 -mmacosx-version-min=$MACOSX_DEPLOYMENT_TARGET -bundle"
     MATLAB_LDFLAGS="$MATLAB_LDFLAGS_NOMAP -Wl,-exported_symbols_list,\$(abs_top_srcdir)/mexFunction-MacOSX.map"
-    MATLAB_LIBS="-L$MATLAB/bin/maci64 -lmx -lmex -lmat -lmwlapack -lmwblas"
+    # This -L flag is put here, hence later on the linker command line, so as
+    # to avoid linking against the HDF5 shipped by MATLAB (which would
+    # otherwise override the HDF5 from Homebrew)
+    MATLAB_LIBS="-L$MATLAB/bin/maci64 -lmx -lmex -lmat -lmwlapack -lmwblas -lstdc++"
     ax_mexopts_ok="yes"
     ;;
   *)
diff --git a/m4/ax_slicot.m4 b/m4/ax_slicot.m4
index 921bc09454b7e06bf1989c00449326a3540eeda3..37bfaa843f4afec2e09901d582d198738551ad01 100644
--- a/m4/ax_slicot.m4
+++ b/m4/ax_slicot.m4
@@ -43,7 +43,7 @@ AC_DEFUN([AX_SLICOT],
   AC_FC_FUNC(sb02od)
 
   if test "$1" = matlab; then
-    LDFLAGS="$MATLAB_LDFLAGS_NOMAP $LDFLAGS_SLICOT"
+    LDFLAGS="$LDFLAGS $MATLAB_LDFLAGS_NOMAP $LDFLAGS_SLICOT"
 
     case ${MATLAB_ARCH} in
        glnxa64 | win64 | maci64)
diff --git a/macOS/build.sh b/macOS/build.sh
index 503d696c46ba03946525127a9e05d2d2d1013c7d..1b01dba55eadc8609e7767f4640d2a339623f789 100755
--- a/macOS/build.sh
+++ b/macOS/build.sh
@@ -1,6 +1,6 @@
 #!/usr/bin/env bash
 
-# Copyright © 2019-2020 Dynare Team
+# Copyright © 2019-2021 Dynare Team
 #
 # This file is part of Dynare.
 #
@@ -64,11 +64,15 @@ fi
 ##
 cd "$ROOTDIR"
 [[ -f configure ]] || autoreconf -si
-CC=$CC CXX=$CXX ./configure \
+./configure \
   PACKAGE_VERSION="$VERSION" \
   PACKAGE_STRING="dynare $VERSION" \
-  CXXFLAGS=-I/usr/local/include \
+  CC=$CC \
+  CXX=$CXX \
+  CPPFLAGS=-I/usr/local/include \
   LDFLAGS=-static-libgcc \
+  LEX=/usr/local/opt/flex/bin/flex \
+  YACC=/usr/local/opt/bison/bin/bison \
   --with-gsl="$LIB64"/gsl \
   --with-matio="$LIB64"/matio \
   --with-slicot="$LIB64"/Slicot/with-underscore \
@@ -88,6 +92,7 @@ make -j"$NTHREADS"
 NAME=dynare-"$VERSION"
 PKGFILES="$ROOTDIR"/macOS/pkg/"$NAME"
 mkdir -p \
+      "$PKGFILES"/preprocessor \
       "$PKGFILES"/mex/matlab/maci64-8.3-9.3 \
       "$PKGFILES"/mex/matlab/maci64-9.4-9.9 \
       "$PKGFILES"/mex/octave \
@@ -107,6 +112,12 @@ cp -p  "$ROOTDIR"/license.txt                                        "$PKGFILES"
 cp -pr "$ROOTDIR"/matlab                                             "$PKGFILES"
 cp -pr "$ROOTDIR"/examples                                           "$PKGFILES"
 
+cp -p  "$ROOTDIR"/preprocessor/src/dynare-preprocessor               "$PKGFILES"/preprocessor
+
+# Recreate backward-compatibility symlink
+rm -f "$ROOTDIR"/matlab/preprocessor64/dynare_m
+ln -sf ../../preprocessor/dynare-preprocessor                        "$PKGFILES"/matlab/preprocessor64/dynare_m
+
 cp -L  "$ROOTDIR"/mex/matlab/*                                       "$PKGFILES"/mex/matlab/maci64-8.3-9.3
 
 cp -p  "$ROOTDIR"/scripts/dynare.el                                  "$PKGFILES"/scripts
@@ -136,10 +147,12 @@ cp -p  "$ROOTDIR"/macOS/deps/lib64/x13as/x13as                       "$PKGFILES"
 ##
 cd "$ROOTDIR"/mex/build/matlab
 make clean
-CC=$CC CXX=$CXX ./configure \
+./configure \
   PACKAGE_VERSION="$VERSION" \
   PACKAGE_STRING="dynare $VERSION" \
-  CXXFLAGS=-I/usr/local/include \
+  CC=$CC \
+  CXX=$CXX \
+  CPPFLAGS=-I/usr/local/include \
   LDFLAGS=-static-libgcc \
   --with-gsl="$LIB64"/gsl \
   --with-matio="$LIB64"/matio \
@@ -156,10 +169,12 @@ cd "$ROOTDIR"/mex/build/octave
 OCTAVE_VERSION=$(grep OCTAVE_VERSION "$ROOTDIR"/macOS/deps/versions.mk | cut -d'=' -f2 | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
 OCTAVE_USR_DIR="/Applications/Octave-$OCTAVE_VERSION.app/Contents/Resources/usr"
 OCTAVE_BIN_DIR="$OCTAVE_USR_DIR/Cellar/octave-octave-app@$OCTAVE_VERSION/$OCTAVE_VERSION/bin"
-PATH="$OCTAVE_BIN_DIR:$PATH" CC=$CC CXX=$CXX ./configure \
+PATH="$OCTAVE_BIN_DIR:$PATH" ./configure \
   PACKAGE_VERSION="$VERSION" \
   PACKAGE_STRING="dynare $VERSION" \
-  CXXFLAGS=-I/usr/local/include \
+  CC=$CC \
+  CXX=$CXX \
+  CPPFLAGS=-I/usr/local/include \
   LDFLAGS="-static-libgcc -L$OCTAVE_USR_DIR/lib " \
   --with-gsl="$LIB64"/gsl \
   --with-matio="$LIB64"/matio \
diff --git a/matlab/UnivariateSpectralDensity.m b/matlab/UnivariateSpectralDensity.m
index 1c04d622d7a30611d42eabd08517f09bda504c50..d0f48f7d4f958383c37eee62196b0d2cf1b7d696 100644
--- a/matlab/UnivariateSpectralDensity.m
+++ b/matlab/UnivariateSpectralDensity.m
@@ -98,7 +98,7 @@ end
 [vx, u] =  lyapunov_symm(A,B*M_.Sigma_e*B',options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold,[],options_.debug);
 iky = iv(ivar);
 if ~isempty(u)
-    iky = iky(find(any(abs(ghx(iky,:)*u) < options_.Schur_vec_tol,2)));
+    iky = iky(find(any(abs(ghx(iky,:)*u) < options_.schur_vec_tol,2)));
     ivar = oo_.dr.order_var(iky);
 end
 
@@ -151,11 +151,11 @@ else
 end
 
 if ~options_.nograph
-    if ~exist(M_.fname, 'dir')
-        mkdir('.',M_.fname);
+    if ~exist(M_.dname, 'dir')
+        mkdir('.',M_.dname);
     end
-    if ~exist([M_.fname '/graphs'],'dir')
-        mkdir(M_.fname,'graphs');
+    if ~exist([M_.dname '/graphs'],'dir')
+        mkdir(M_.dname,'graphs');
     end
 
     for i= 1:nvar
@@ -165,6 +165,6 @@ if ~options_.nograph
         ylabel('f(\omega)')
         box on
         axis tight
-        dyn_saveas(hh,[M_.fname ,filesep,'graphs', filesep, 'SpectralDensity_' M_.endo_names{ivar(i)}],options_.nodisplay,options_.graph_format)
+        dyn_saveas(hh,[M_.dname ,filesep,'graphs', filesep, 'SpectralDensity_' M_.endo_names{ivar(i)}],options_.nodisplay,options_.graph_format)
     end
 end
diff --git a/matlab/accessors/get_posterior_covariance.m b/matlab/accessors/get_posterior_covariance.m
new file mode 100644
index 0000000000000000000000000000000000000000..d83c0fd964d945dd7ed1345a1ff2d068fefe8db9
--- /dev/null
+++ b/matlab/accessors/get_posterior_covariance.m
@@ -0,0 +1,74 @@
+function r = get_posterior_covariance(endo1, endo2)
+
+% Copyright (C) 2020 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 <http://www.gnu.org/licenses/>.
+
+global M_ options_
+
+id1 = find(strcmp(endo1, M_.endo_names));
+if nargin < 2
+    id2 = id1;
+else
+    id2 = find(strcmp(endo2, M_.endo_names));
+end
+
+ivar = get_variables_list(options_,M_);
+
+if ~ismember(id1, ivar)
+    error('Posterior moments have not been computed for %s', endo1)
+end
+if ~ismember(id2, ivar)
+    error('Posterior moments have not been computed for %s', endo2)
+end
+
+r = struct('draw', [], 'moment', []);
+
+
+% Fetch parameter draws
+
+NumberDrawsFiles = length(dir([M_.dname '/metropolis/' M_.fname '_posterior_draws*' ]));
+if NumberDrawsFiles == 0
+    error('Can''t find posterior draws file(s)')
+end
+
+idx = 1;
+for file = 1:NumberDrawsFiles
+    load([M_.dname '/metropolis/' M_.fname '_posterior_draws' int2str(file) ],'pdraws');
+    for i = 1:size(pdraws, 1)
+        r(idx).draw = pdraws{i, 1};
+        idx = idx+1;
+    end
+end
+
+
+% Fetch moments
+
+symidx = symmetric_matrix_index(find(ivar==id1), find(ivar==id2), length(ivar));
+
+NumberMomentsFiles = length(dir([M_.dname '/metropolis/' M_.fname '_Posterior2ndOrderMoments*']));
+if NumberMomentsFiles == 0
+    error('Can''t find posterior 2nd order moments file(s)')
+end
+
+idx = 1;
+for file = 1:NumberMomentsFiles
+    load([M_.dname '/metropolis/' M_.fname '_Posterior2ndOrderMoments' int2str(file) ],'Covariance_matrix');
+    for i = 1:size(Covariance_matrix, 1)
+        r(idx).moment = Covariance_matrix(i, symidx);
+        idx = idx+1;
+    end
+end
diff --git a/matlab/accessors/get_posterior_irf.m b/matlab/accessors/get_posterior_irf.m
new file mode 100644
index 0000000000000000000000000000000000000000..4835db71870c149d20483c01a401f0d0c21510b8
--- /dev/null
+++ b/matlab/accessors/get_posterior_irf.m
@@ -0,0 +1,74 @@
+function r = get_posterior_irf(endo, exo)
+
+% Copyright (C) 2020 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 <http://www.gnu.org/licenses/>.
+
+global M_ options_
+
+endo_id = find(strcmp(endo, M_.endo_names));
+exo_id = find(strcmp(exo, M_.exo_names));
+if isempty(exo_id)
+    error('Unknown exogenous: %s', exo)
+end
+
+ivar = get_variables_list(options_,M_);
+
+if ~ismember(endo_id, ivar)
+    error('Posterior IRFs have not been computed for %s', endo)
+end
+
+r = struct('draw', [], 'irf', []);
+
+
+% Fetch parameter draws
+
+NumberDrawsFiles = length(dir([M_.dname '/metropolis/' M_.fname '_param_irf*' ]));
+if NumberDrawsFiles == 0
+    error('Can''t find posterior draws file(s)')
+end
+
+idx = 1;
+for file = 1:NumberDrawsFiles
+    load([M_.dname '/metropolis/' M_.fname '_param_irf' int2str(file) ],'stock');
+    for i = 1:size(stock, 1)
+        r(idx).draw = stock(i, :);
+        idx = idx+1;
+    end
+end
+
+
+% Fetch IRFs
+
+% We use the raw files, i.e. those that are *not* the output of
+% ReshapeMatFiles.m. Their filename contains 'irf_dsge' in *lowercase*.
+filesUpperAndLower = dir([M_.dname '/metropolis/' M_.fname '_irf_dsge*']);
+filesLower = cellfun(@any, regexp({filesUpperAndLower.name}, [M_.fname '_irf_dsge\d\.mat']));
+NumberIRFsFiles = sum(filesLower);
+if NumberIRFsFiles == 0
+    error('Can''t find posterior IRFs file(s)')
+end
+
+endo_id_varlist = find(ivar == endo_id);
+
+idx = 1;
+for file = 1:NumberIRFsFiles
+    load([M_.dname '/metropolis/' M_.fname '_irf_dsge' int2str(file) ],'stock_irf_dsge');
+    for i = 1:size(stock_irf_dsge, 4)
+        r(idx).irf = stock_irf_dsge(:, endo_id_varlist, exo_id, i);
+        idx = idx+1;
+    end
+end
diff --git a/matlab/accessors/get_posterior_timeseries.m b/matlab/accessors/get_posterior_timeseries.m
new file mode 100644
index 0000000000000000000000000000000000000000..a15ada45f65cc2d40404b6db851287d65ecfe4cc
--- /dev/null
+++ b/matlab/accessors/get_posterior_timeseries.m
@@ -0,0 +1,110 @@
+function r = get_posterior_timeseries(type, endo)
+% Returns the posterior distribution of either
+% smoothed/updated/filtered/forecast timeseries for a given endogenous variable.
+% "type" must be either 'smoothed', 'updated', 'filtered' or 'forecast'.
+%
+% For filtered variables, returns a matrix with step-ahead in lines and periods
+%  in columns.
+% For forecasts, returns the "point" forecast (i.e. with uncertainty about both
+%  parameters and shocks).
+
+% Copyright (C) 2020 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 <http://www.gnu.org/licenses/>.
+
+global M_
+
+endo_id = find(strcmp(endo, M_.endo_names));
+
+if isempty(endo_id)
+    error('Unknown endogenous variable %s', endo)
+end
+
+r = struct('draw', [], type, []);
+
+
+% Fetch parameter draws
+
+DrawsFiles = dir([M_.dname '/metropolis/' M_.fname '_param*' ]);
+NumberDrawsFiles = 0;
+for i=1:length(DrawsFiles)
+    % We need to filter out the _param_irf* files
+    if ~isempty(regexp(DrawsFiles(i).name, '.*_param[0-9]+\.mat'))
+        NumberDrawsFiles = NumberDrawsFiles + 1;
+    end
+end
+if NumberDrawsFiles == 0
+    error('Can''t find posterior draws file(s)')
+end
+
+idx = 1;
+for file = 1:NumberDrawsFiles
+    load([M_.dname '/metropolis/' M_.fname '_param' int2str(file) ],'stock');
+    for i = 1:size(stock, 1)
+        r(idx).draw = stock(i, :);
+        idx = idx+1;
+    end
+end
+
+
+% Fetch timeseries
+
+switch type
+    case 'smoothed'
+        basename = 'smooth';
+    case 'updated'
+        basename = 'update';
+    case 'filtered'
+        basename = 'filter_step_ahead';
+    case 'forecast'
+        basename = 'forc_point';
+    otherwise
+        error('Unknown type requested. Should be one of: smoothed, updated, filtered, forecast')
+end
+
+
+if strcmp(type, 'smoothed')
+    SmoothedFiles = dir([M_.dname '/metropolis/' M_.fname '_smooth*']);
+    NumberTimeseriesFiles = 0;
+    for i=1:length(SmoothedFiles)
+        %% We need to filter out the _smoothed_{constant,trend}* files
+        if ~isempty(regexp(SmoothedFiles(i).name, '.*_smooth[0-9]+\.mat'))
+            NumberTimeseriesFiles = NumberTimeseriesFiles + 1;
+        end
+    end
+else
+    NumberTimeseriesFiles = length(dir([M_.dname '/metropolis/' M_.fname '_' ...
+                                          basename '*']));
+end
+if NumberTimeseriesFiles == 0
+    error('Can''t find file(s) with posterior timeseries of requested type')
+end
+
+idx = 1;
+for file = 1:NumberTimeseriesFiles
+    load([M_.dname '/metropolis/' M_.fname '_' basename int2str(file) ],'stock');
+    if strcmp(type, 'filtered')
+        for i = 1:size(stock, 4)
+            r(idx).(type) = reshape(stock(:, endo_id, :, i), size(stock,1), size(stock,3));
+            idx = idx+1;
+        end
+    else
+        for i = 1:size(stock, 3)
+            r(idx).(type) = stock(endo_id, :, i)';
+            idx = idx+1;
+        end
+    end
+end
diff --git a/matlab/bvar_forecast.m b/matlab/bvar_forecast.m
index 55fdf9ce9503b5985ab0438af82d6edebd0882b0..2fe5601cbf0b3c826f760af12ba43aadf02e333b 100644
--- a/matlab/bvar_forecast.m
+++ b/matlab/bvar_forecast.m
@@ -114,7 +114,7 @@ sims_with_shocks_sort = sort(sims_with_shocks, 3);
 sims_with_shocks_down_conf = sims_with_shocks_sort(:, :, sort_idx(1));
 sims_with_shocks_up_conf = sims_with_shocks_sort(:, :, sort_idx(2));
 
-OutputDirectoryName = CheckPath('graphs',M_.fname);
+OutputDirectoryName = CheckPath('graphs',M_.dname);
 
 dyn_graph=dynare_graph_init(sprintf('BVAR forecasts (nlags = %d)', nlags), ny, {'b-' 'g-' 'g-' 'r-' 'r-'});
 
@@ -153,10 +153,10 @@ end
 
 % Store results
 
-DirectoryName = [ M_.fname '/bvar_forecast' ];
+DirectoryName = [ M_.dname '/bvar_forecast' ];
 if ~isdir(DirectoryName)
-    if ~isdir(M_.fname)
-        mkdir(M_.fname);
+    if ~isdir(M_.dname)
+        mkdir(M_.dname);
     end
     mkdir(DirectoryName);
 end
diff --git a/matlab/bvar_irf.m b/matlab/bvar_irf.m
index 5f017aa7d40be6a4c7d487799d7f6cbd8bb55b3e..2dbd908e4e951d771e14020bfed1ae7d8aa1d653 100644
--- a/matlab/bvar_irf.m
+++ b/matlab/bvar_irf.m
@@ -126,7 +126,7 @@ for shock=1:ny
 end
 
 % Save intermediate results
-DirectoryName = [ M_.fname '/bvar_irf' ];
+DirectoryName = [ M_.dname '/bvar_irf' ];
 if ~isdir(DirectoryName)
     mkdir('.',DirectoryName);
 end
diff --git a/matlab/check_posterior_sampler_options.m b/matlab/check_posterior_sampler_options.m
index 0cb50758672fae4ec22f02b9dd6a115727ba4cea..ceb6c6337cc4e19f9d67c7627a2dc3d401764594 100644
--- a/matlab/check_posterior_sampler_options.m
+++ b/matlab/check_posterior_sampler_options.m
@@ -378,11 +378,13 @@ end
 
 % here are all samplers requiring a proposal distribution
 if ~strcmp(posterior_sampler_options.posterior_sampling_method,'slice')
-    if ~options_.cova_compute && ~(options_.load_mh_file && posterior_sampler_options.use_mh_covariance_matrix)
+    if ~options_.cova_compute && ~(options_.load_mh_file && posterior_sampler_options.use_mh_covariance_matrix) 
+        if strcmp('hessian',options_.MCMC_jumping_covariance)
         skipline()
         disp('check_posterior_sampler_options:: I cannot start the MCMC because the Hessian of the posterior kernel at the mode was not computed')
         disp('check_posterior_sampler_options:: or there is no previous MCMC to load ')
         error('check_posterior_sampler_options:: MCMC cannot start')
+        end
     end
 end
 
diff --git a/matlab/compute_moments_varendo.m b/matlab/compute_moments_varendo.m
index d4a35758b6330b15936528e88785d2322887c9b4..0604bd978643587059cfa7c061f4812e320b1bab 100644
--- a/matlab/compute_moments_varendo.m
+++ b/matlab/compute_moments_varendo.m
@@ -151,7 +151,7 @@ if M_.exo_nbr > 1
     end
     skipline();
     if ~all(diag(M_.H)==0)
-        if isoctave
+        if isoctave && octave_ver_less_than('6')
             [observable_name_requested_vars, varlist_pos] = intersect_stable(var_list_, options_.varobs);
         else
             [observable_name_requested_vars, varlist_pos] = intersect(var_list_, options_.varobs, 'stable');
diff --git a/matlab/conditional_variance_decomposition.m b/matlab/conditional_variance_decomposition.m
index f249a7c7a9e17b7de25b061c2ae30bdbe3cbaa35..8a8b90834f99463802941430ee9b5495363a949d 100644
--- a/matlab/conditional_variance_decomposition.m
+++ b/matlab/conditional_variance_decomposition.m
@@ -89,7 +89,7 @@ end
 % Measurement error
 
 if ~all(diag(StateSpaceModel.measurement_error)==0)
-    if isoctave
+    if isoctave && octave_ver_less_than('6')
         [observable_pos,index_subset,index_observables]=intersect_stable(SubsetOfVariables,StateSpaceModel.observable_pos);
     else
         [observable_pos,index_subset,index_observables]=intersect(SubsetOfVariables,StateSpaceModel.observable_pos,'stable');
diff --git a/matlab/conditional_variance_decomposition_ME_mc_analysis.m b/matlab/conditional_variance_decomposition_ME_mc_analysis.m
index a0b5ffdd7a1df2e0fa2127091bd78466ffb90027..b9f187298d6d1911944861e7d770d8c6e9731e28 100644
--- a/matlab/conditional_variance_decomposition_ME_mc_analysis.m
+++ b/matlab/conditional_variance_decomposition_ME_mc_analysis.m
@@ -63,7 +63,7 @@ if isempty(exogenous_variable_index)
     end
 end
 
-if isoctave
+if isoctave && octave_ver_less_than('6')
     [observable_pos_requested_vars,index_subset,index_observables]=intersect_stable(var_list,options_.varobs);
 else
     [observable_pos_requested_vars,index_subset,index_observables]=intersect(var_list,options_.varobs,'stable');
diff --git a/matlab/default_option_values.m b/matlab/default_option_values.m
index f00b79b4e8247182f7de6e94ed2f3008d9ecdf3d..66ba29f1389967b5beeb925d481730059a450dec 100644
--- a/matlab/default_option_values.m
+++ b/matlab/default_option_values.m
@@ -46,7 +46,7 @@ options_.gstep(2) = 1.0;
 options_.scalv = 1;
 options_.debug = false;
 options_.initval_file = false;
-options_.Schur_vec_tol = 1e-11; % used to find nonstationary variables in Schur decomposition of the
+options_.schur_vec_tol = 1e-11; % used to find nonstationary variables in Schur decomposition of the
                                 % transition matrix
 options_.qz_criterium = [];
 options_.qz_zero_threshold = 1e-6;
diff --git a/matlab/discretionary_policy/discretionary_policy.m b/matlab/discretionary_policy/discretionary_policy.m
index b2c67403d6d2bbf87dd1f47c83b4ee540751680e..4c918263a13e67f2335d09497e28ee3f4035694d 100644
--- a/matlab/discretionary_policy/discretionary_policy.m
+++ b/matlab/discretionary_policy/discretionary_policy.m
@@ -36,15 +36,16 @@ options_.discretionary_policy = 1;
 options_.order = 1;
 [info, oo_, options_, M_] = stoch_simul(M_, options_, oo_, var_list);
 
+oo_.steady_state = oo_.dr.ys;
+
 if ~options_.noprint
-    disp_steady_state(M_,oo_)
+    disp_steady_state(M_,oo_,options_)
     for i=M_.orig_endo_nbr:M_.endo_nbr
         if strmatch('mult_', M_.endo_names{i})
             fprintf('%s \t\t %g\n', M_.endo_names{i}, oo_.dr.ys(i));
         end
     end
 end
-
 oo_.planner_objective_value = evaluate_planner_objective(M_,options_,oo_);
 
 options_.order = origorder;
diff --git a/matlab/discretionary_policy/discretionary_policy_1.m b/matlab/discretionary_policy/discretionary_policy_1.m
index 314f442725e9c216515afa6e546c911f9ff26e07..c9424b57d6a0370e08b4e0042138a9f81b867c3d 100644
--- a/matlab/discretionary_policy/discretionary_policy_1.m
+++ b/matlab/discretionary_policy/discretionary_policy_1.m
@@ -41,11 +41,13 @@ beta = get_optimal_policy_discount_factor(M_.params, M_.param_names);
 %call steady_state_file if present to update parameters
 if options_.steadystate_flag
     % explicit steady state file
-    [~,M_.params,info] = evaluate_steady_state_file(oo_.steady_state,[oo_.exo_steady_state; oo_.exo_det_steady_state],M_, ...
+    [ys,M_.params,info] = evaluate_steady_state_file(oo_.steady_state,[oo_.exo_steady_state; oo_.exo_det_steady_state],M_, ...
                                                     options_,false);
     if info(1)
         return;
     end
+else
+    ys=zeros(M_.endo_nbr,1);
 end
 [U,Uy,W] = feval([M_.fname,'.objective.static'],zeros(M_.endo_nbr,1),[], M_.params);
 if any(any(isnan(Uy)))
@@ -73,8 +75,10 @@ W=reshape(W,M_.endo_nbr,M_.endo_nbr);
 klen = M_.maximum_lag + M_.maximum_lead + 1;
 iyv=M_.lead_lag_incidence';
 % Find the jacobian
-z = repmat(zeros(M_.endo_nbr,1),1,klen);
-z = z(nonzeros(iyv)) ;
+z = repmat(ys,1,klen);
+iyr0 = find(iyv(:)) ;
+
+z = z(iyr0);
 it_ = M_.maximum_lag + 1 ;
 
 if M_.exo_nbr == 0
@@ -82,16 +86,16 @@ if M_.exo_nbr == 0
 end
 
 [junk,jacobia_] = feval([M_.fname '.dynamic'],z, [zeros(size(oo_.exo_simul)) ...
-                    oo_.exo_det_simul], M_.params, zeros(M_.endo_nbr,1), it_);
-if any(junk~=0)
-    info = 65; %the model must be written in deviation form and not have constant terms
-    return;
+                    oo_.exo_det_simul], M_.params, ys, it_);
+if max(abs(junk))>options_.solve_tolf
+     info = 65; %the model must be written in deviation form and not have constant terms or have a steady state provided
+     return;
 end
 
 Indices={'lag','contemp','lead'};
 iter=1;
 for j=1:numel(Indices)
-    A.(Indices{j})=zeros(M_.orig_eq_nbr,M_.endo_nbr);
+    A.(Indices{j})=zeros(M_.eq_nbr,M_.endo_nbr);
     if strcmp(Indices{j},'contemp')||(strcmp(Indices{j},'lag') && M_.maximum_lag)||(strcmp(Indices{j},'lead') && M_.maximum_lead)
         [~,row,col]=find(M_.lead_lag_incidence(iter,:));
         A.(Indices{j})(:,row)=jacobia_(:,col);
@@ -116,10 +120,12 @@ else
 end
 
 %write back solution to dr
-dr.ys =zeros(M_.endo_nbr,1);
+dr.ys =ys;
 dr=set_state_space(dr,M_,options_);
 T=H(dr.order_var,dr.order_var);
 dr.ghu=G(dr.order_var,:);
-Selection=M_.lead_lag_incidence(1,dr.order_var)>0;%select state variables
+if M_.maximum_endo_lag
+    Selection=M_.lead_lag_incidence(1,dr.order_var)>0;%select state variables
+end
 dr.ghx=T(:,Selection);
 oo_.dr = dr;
diff --git a/matlab/disp_dr.m b/matlab/disp_dr.m
index d11699222089f5c543c577f561588d87e9aceb30..13c42166bda78a8f9cb628f24da3ff5f1414f731 100644
--- a/matlab/disp_dr.m
+++ b/matlab/disp_dr.m
@@ -67,6 +67,9 @@ header_label_length=16; %default
 for ii=1:length(ivar)
     header_label_length = max(header_label_length,length(M_.endo_names{k1(ivar(ii))})+2);
 end
+if options_.loglinear
+    header_label_length=header_label_length+5;
+end
 header_label_format  = sprintf('%%%ds',header_label_length);
 value_format_float  = sprintf('%%%d.6f',header_label_length);
 value_format_zero  = sprintf('%%%dd',header_label_length);
@@ -83,8 +86,11 @@ else
     aux_var_additional_characters=0;
 end
 
-var_name_width = max([cellofchararraymaxlength(M_.endo_names(k1(ivar))), cellofchararraymaxlength(M_.exo_names)]);
-
+if options_.loglinear
+    var_name_width = max([cellofchararraymaxlength(M_.endo_names(k1(ivar)))+5, cellofchararraymaxlength(M_.exo_names)]);
+else
+    var_name_width = max([cellofchararraymaxlength(M_.endo_names(k1(ivar))), cellofchararraymaxlength(M_.exo_names)]);
+end
 %deal with covariances
 if order > 1
     var_name_width=max(2*(var_name_width+aux_var_additional_characters)+2,20); %account for covariances, separated by comma
@@ -99,7 +105,11 @@ disp('POLICY AND TRANSITION FUNCTIONS')
 % variable names
 str = char(32*ones(1,var_name_width));
 for i=1:nvar
-    str = [str sprintf(header_label_format, M_.endo_names{k1(ivar(i))})];
+    if options_.loglinear
+        str = [str sprintf(header_label_format, ['log(',M_.endo_names{k1(ivar(i))},')'])];
+    else
+        str = [str sprintf(header_label_format, M_.endo_names{k1(ivar(i))})];
+    end
 end
 disp(str);
 %
@@ -138,7 +148,11 @@ for k=1:nx
     else
         str1 = subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2);
     end
-    str = sprintf(label_format,str1);
+    if options_.loglinear
+        str = sprintf(label_format,['log(',str1,')']);
+    else
+        str = sprintf(label_format,str1);
+    end
     for i=1:nvar
         x = dr.ghx(ivar(i),k);
         [str,flag]=get_print_string(str,x,value_format_zero,value_format_float,flag,options_);
diff --git a/matlab/disp_moments.m b/matlab/disp_moments.m
index 3d0cb6aa15739da4eb0480361fda82822219f669..94a6709cab66d1d6ff590ec1e6aabb789970a115 100644
--- a/matlab/disp_moments.m
+++ b/matlab/disp_moments.m
@@ -50,7 +50,7 @@ y = y(ivar,options_.drop+1:end)';
 
 ME_present=0;
 if ~all(M_.H==0)
-    if isoctave
+    if isoctave && octave_ver_less_than('6')
         [observable_pos_requested_vars, index_subset, index_observables] = intersect_stable(ivar, options_.varobs_id);
     else
         [observable_pos_requested_vars, index_subset, index_observables] = intersect(ivar, options_.varobs_id, 'stable');
@@ -94,8 +94,8 @@ oo_.var(zero_variance_var_index,:)=0;
 oo_.var(:,zero_variance_var_index)=0;
 
 
-labels = M_.endo_names(ivar);
-labels_TeX = M_.endo_names_tex(ivar);
+labels=get_labels_transformed_vars(M_.endo_names,ivar,options_,false);
+labels_TeX=get_labels_transformed_vars(M_.endo_names_tex,ivar,options_,true);
 
 if ~options_.nomoments
     z = [ m' s' s2' oo_.skewness oo_.kurtosis ];
@@ -204,10 +204,11 @@ if ~options_.nodecomposition
             headers = vertcat(' ', headers);
             lh = cellofchararraymaxlength(M_.endo_names(ivar))+2;
             dyntable(options_, title, vertcat(headers, 'Tot. lin. contr.'), ...
-                     M_.endo_names(ivar), [oo_.variance_decomposition sum(oo_.variance_decomposition,2)], lh, 8, 2);
+                     labels, [oo_.variance_decomposition sum(oo_.variance_decomposition,2)], lh, 8, 2);
             if ME_present
                 headers_ME = vertcat(headers, 'ME');
-                dyntable(options_, [title,' WITH MEASUREMENT ERROR'], vertcat(headers_ME, 'Tot. lin. contr.'), M_.endo_names(ivar(index_subset)), ...
+                labels_obs=get_labels_transformed_vars(M_.endo_names,ivar(index_subset),options_,false);
+                dyntable(options_, [title,' WITH MEASUREMENT ERROR'], vertcat(headers_ME, 'Tot. lin. contr.'), labels_obs, ...
                          [oo_.variance_decomposition_ME sum(oo_.variance_decomposition_ME, 2)], lh, 8, 2);
             end
             if options_.TeX
@@ -219,9 +220,10 @@ if ~options_.nodecomposition
                                 labels_TeX, [oo_.variance_decomposition sum(oo_.variance_decomposition, 2)], lh, 8, 2);
                 if ME_present
                     headers_ME = vertcat(headers, 'ME');
+                    labels_obs_TeX=get_labels_transformed_vars(M_.endo_names_tex,ivar(index_subset),options_,true);
                     dyn_latex_table(M_, options_, [title, ' WITH MEASUREMENT ERROR'], 'sim_var_decomp_ME', ...
                                     vertcat(headers_ME, 'Tot. lin. contr.'), ...
-                                    labels_TeX(ivar(index_subset)), ...
+                                    labels_obs_TeX, ...
                                     [oo_.variance_decomposition_ME sum(oo_.variance_decomposition_ME, 2)], lh, 8, 2);
                 end
             end
@@ -256,3 +258,4 @@ else
 end
 
 end
+
diff --git a/matlab/disp_steady_state.m b/matlab/disp_steady_state.m
index 8c1bd549ba8d080068cd773f838b51970c5b950b..027f23ec723a23b9e53c7777ee5756c6f73f629b 100644
--- a/matlab/disp_steady_state.m
+++ b/matlab/disp_steady_state.m
@@ -1,10 +1,11 @@
-function disp_steady_state(M,oo)
-% function disp_steady_state(M,oo)
+function disp_steady_state(M,oo,options)
+% function disp_steady_state(M,oo,options)
 % computes and prints the steady state calculations
 %
 % INPUTS
 %   M      structure of parameters
 %   oo     structure of results
+%   options structure of options
 %
 % OUTPUTS
 %   none
@@ -12,7 +13,7 @@ function disp_steady_state(M,oo)
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2001-2018 Dynare Team
+% Copyright (C) 2001-2020 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -30,7 +31,11 @@ function disp_steady_state(M,oo)
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 skipline()
-disp('STEADY-STATE RESULTS:')
+if options.loglinear
+    disp('STEADY-STATE RESULTS FOR THE UNLOGGED VARIABLES:')
+else
+    disp('STEADY-STATE RESULTS:')
+end
 skipline()
 endo_names = char(M.endo_names);
 steady_state = oo.steady_state;
diff --git a/matlab/disp_th_moments.m b/matlab/disp_th_moments.m
index 5ea5040bd1a2410356fa9280a2ab622e85f3ab1b..3c8466c512a07dab7f304f91d79d7d3279aaa634 100644
--- a/matlab/disp_th_moments.m
+++ b/matlab/disp_th_moments.m
@@ -55,7 +55,7 @@ oo_.var = oo_.gamma_y{1};
 
 ME_present=0;
 if ~all(diag(M_.H)==0)
-    if isoctave
+    if isoctave && octave_ver_less_than('6')
         [observable_pos_requested_vars,index_subset,index_observables]=intersect_stable(ivar,options_.varobs_id);
     else
         [observable_pos_requested_vars,index_subset,index_observables]=intersect(ivar,options_.varobs_id,'stable');
@@ -82,11 +82,11 @@ if size(stationary_vars, 1) > 0
         end
         title = add_filter_subtitle(title, options_);
         headers = {'VARIABLE';'MEAN';'STD. DEV.';'VARIANCE'};
-        labels = M_.endo_names(ivar);
+        labels=get_labels_transformed_vars(M_.endo_names,ivar,options_,false);
         lh = cellofchararraymaxlength(labels)+2;
         dyntable(options_, title, headers, labels, z, lh, 11, 4);
         if options_.TeX
-            labels = M_.endo_names_tex(ivar);
+            labels=get_labels_transformed_vars(M_.endo_names_tex,ivar,options_,true);
             lh = cellofchararraymaxlength(labels)+2;
             dyn_latex_table(M_, options_, title, 'th_moments', headers, labels, z, lh, 11, 4);
         end
@@ -102,26 +102,29 @@ if size(stationary_vars, 1) > 0
             headers = M_.exo_names;
             headers(M_.exo_names_orig_ord) = headers;
             headers = vertcat(' ', headers);
-            lh = cellofchararraymaxlength(M_.endo_names(ivar(stationary_vars)))+2;
-            dyntable(options_, title, headers, M_.endo_names(ivar(stationary_vars)), 100*oo_.gamma_y{options_.ar+2}(stationary_vars,:), lh, 8, 2);
+            labels=get_labels_transformed_vars(M_.endo_names,ivar(stationary_vars),options_,false);
+            lh = cellofchararraymaxlength(labels)+2;
+            dyntable(options_, title, headers, labels, 100*oo_.gamma_y{options_.ar+2}(stationary_vars,:), lh, 8, 2);
             if ME_present
-                if isoctave
+                if isoctave && octave_ver_less_than('6')
                     [stationary_observables, pos_index_subset] = intersect_stable(index_subset, stationary_vars);
                 else
                     [stationary_observables, pos_index_subset] = intersect(index_subset, stationary_vars, 'stable');
                 end
                 headers_ME = vertcat(headers, 'ME');
-                dyntable(options_, [title,' WITH MEASUREMENT ERROR'], headers_ME, M_.endo_names(ivar(stationary_observables)), ...
+                labels=get_labels_transformed_vars(M_.endo_names,ivar(stationary_observables),options_,false);
+                dyntable(options_, [title,' WITH MEASUREMENT ERROR'], headers_ME, labels, ...
                          oo_.variance_decomposition_ME(pos_index_subset,:), lh, 8, 2);
             end
             if options_.TeX
                 headers = M_.exo_names_tex;
                 headers = vertcat(' ', headers);
-                labels = M_.endo_names_tex(ivar(stationary_vars));
+                labels=get_labels_transformed_vars(M_.endo_names_tex,ivar(stationary_vars),options_,true);
                 lh = cellofchararraymaxlength(labels)+2;
                 dyn_latex_table(M_, options_, title, 'th_var_decomp_uncond', headers, labels, 100*oo_.gamma_y{options_.ar+2}(stationary_vars,:), lh, 8, 2);
                 if ME_present
                     headers_ME = vertcat(headers, 'ME');
+                    labels=get_labels_transformed_vars(M_.endo_names_tex,ivar(stationary_observables),options_,true);
                     dyn_latex_table(M_, options_, [title,' WITH MEASUREMENT ERROR'], ...
                                     'th_var_decomp_uncond_ME', headers_ME, labels, oo_.variance_decomposition_ME(pos_index_subset,:), lh, 8, 2);
                 end
@@ -172,12 +175,12 @@ if ~options_.nocorr && size(stationary_vars, 1)>0
             title = 'MATRIX OF CORRELATIONS';
         end
         title = add_filter_subtitle(title, options_);
-        labels = M_.endo_names(ivar(i1));
+        labels=get_labels_transformed_vars(M_.endo_names,ivar(i1),options_,false);
         headers = vertcat('Variables', labels);
         lh = cellofchararraymaxlength(labels)+2;
         dyntable(options_, title, headers, labels, corr(i1,i1), lh, 8, 4);
         if options_.TeX
-            labels = M_.endo_names_tex(ivar(i1));
+            labels=get_labels_transformed_vars(M_.endo_names_tex,ivar(i1),options_,true);
             headers = vertcat('Variables', labels);
             lh = cellofchararraymaxlength(labels)+2;
             dyn_latex_table(M_, options_, title, 'th_corr_matrix', headers, labels, corr(i1,i1), lh, 8, 4);
@@ -199,15 +202,15 @@ if options_.ar > 0 && size(stationary_vars, 1) > 0
             title = 'COEFFICIENTS OF AUTOCORRELATION';
         end
         title = add_filter_subtitle(title, options_);
-        labels = M_.endo_names(ivar(i1));
+            labels=get_labels_transformed_vars(M_.endo_names,ivar(i1),options_,false);
         headers = vertcat('Order ', cellstr(int2str([1:options_.ar]')));
         lh = cellofchararraymaxlength(labels)+2;
         dyntable(options_, title, headers, labels, z, lh, 8, 4);
         if options_.TeX
-            labels = M_.endo_names_tex(ivar(i1));
+            labels=get_labels_transformed_vars(M_.endo_names_tex,ivar(i1),options_,true);
             headers = vertcat('Order ', cellstr(int2str([1:options_.ar]')));
             lh = cellofchararraymaxlength(labels)+2;
             dyn_latex_table(M_, options_, title, 'th_autocorr_matrix', headers, labels, z, lh, 8, 4);
         end
     end
-end
+end
\ No newline at end of file
diff --git a/matlab/disp_th_moments_order3.m b/matlab/disp_th_moments_pruned_state_space.m
similarity index 100%
rename from matlab/disp_th_moments_order3.m
rename to matlab/disp_th_moments_pruned_state_space.m
diff --git a/matlab/display_conditional_variance_decomposition.m b/matlab/display_conditional_variance_decomposition.m
index 300320109373e0b8de15abfe7c61ed82a358de65..211e31fdd49afe3d08dcb096a1befa2466a204fb 100644
--- a/matlab/display_conditional_variance_decomposition.m
+++ b/matlab/display_conditional_variance_decomposition.m
@@ -63,9 +63,12 @@ else
 end
 
 headers = vertcat(' ', headers);
-lh = cellofchararraymaxlength(M_.endo_names(SubsetOfVariables))+2;
+
+labels=get_labels_transformed_vars(M_.endo_names,SubsetOfVariables,options_,false);
+
+lh = cellofchararraymaxlength(labels)+2;
 if options_.TeX
-    labels_TeX = M_.endo_names_tex(SubsetOfVariables);
+    labels_TeX=get_labels_transformed_vars(M_.endo_names,SubsetOfVariables,options_,true);
     lh = cellofchararraymaxlength(labels_TeX)+2;
 end
 
@@ -76,7 +79,7 @@ for i=1:length(Steps)
     for j=1:shock_number
         vardec_i(:,j) = 100*conditional_decomposition_array(:,i,j);
     end
-    dyntable(options_, '', headers, M_.endo_names(SubsetOfVariables), vardec_i, lh, 8, 2);
+    dyntable(options_, '', headers, labels, vardec_i, lh, 8, 2);
     if options_.TeX
         dyn_latex_table(M_, options_, [title, '; Period ' int2str(Steps(i))], ['th_var_decomp_cond_h', int2str(Steps(i))], headers_TeX, labels_TeX, vardec_i, lh, 8, 2);
     end
diff --git a/matlab/dsge_likelihood.m b/matlab/dsge_likelihood.m
index 917ef8bfb37f07a64187d8078564b1da157d22f1..94c37513d25179aa712bfdb3771b9ee8e8fe8569 100644
--- a/matlab/dsge_likelihood.m
+++ b/matlab/dsge_likelihood.m
@@ -791,7 +791,7 @@ if DynareOptions.endogenous_prior==1
     if DynareOptions.lik_init==2 || DynareOptions.lik_init==3
         error('Endogenous prior not supported with non-stationary models')
     else
-        [lnpriormom]  = endogenous_prior(Y,Pstar,BayesInfo,H);
+        [lnpriormom]  = endogenous_prior(Y,DatasetInfo,Pstar,BayesInfo,H);
         fval    = (likelihood-lnprior-lnpriormom);
     end
 else
diff --git a/matlab/dsge_simulated_theoretical_conditional_variance_decomposition.m b/matlab/dsge_simulated_theoretical_conditional_variance_decomposition.m
index 22ced1fe5c37d79defee7d76cb1133054750030f..b923e3654cad742040388cf09a46c705bb7780ff 100644
--- a/matlab/dsge_simulated_theoretical_conditional_variance_decomposition.m
+++ b/matlab/dsge_simulated_theoretical_conditional_variance_decomposition.m
@@ -83,7 +83,7 @@ MaXNumberOfConditionalDecompLines = ceil(options_.MaxNumberOfBytes/NumberOfSaved
 
 ME_present=0;
 if ~all(diag(M_.H)==0)
-    if isoctave
+    if isoctave && octave_ver_less_than('6')
         [observable_pos_requested_vars,index_subset,index_observables]=intersect_stable(ivar,options_.varobs_id);
     else
         [observable_pos_requested_vars,index_subset,index_observables]=intersect(ivar,options_.varobs_id,'stable');
diff --git a/matlab/dsge_simulated_theoretical_variance_decomposition.m b/matlab/dsge_simulated_theoretical_variance_decomposition.m
index b93aa246ed7f5370f8dc7bec05aef5eb4be4a41a..714cfdb31beace49d9ac2a3acaf54ea58229b037 100644
--- a/matlab/dsge_simulated_theoretical_variance_decomposition.m
+++ b/matlab/dsge_simulated_theoretical_variance_decomposition.m
@@ -86,7 +86,7 @@ MaXNumberOfDecompLines = ceil(options_.MaxNumberOfBytes/NumberOfSavedElementsPer
 
 ME_present=0;
 if ~all(diag(M_.H)==0)
-    if isoctave
+    if isoctave && octave_ver_less_than('6')
         [observable_pos_requested_vars,index_subset,index_observables]=intersect_stable(ivar,options_.varobs_id);
     else
         [observable_pos_requested_vars,index_subset,index_observables]=intersect(ivar,options_.varobs_id,'stable');
diff --git a/matlab/dyn_second_order_solver.m b/matlab/dyn_second_order_solver.m
index bd5c37a9fa786dd19eac24ef12e396ff3563e658..3dab25c1a99bff37da6e23aaa2a71dc1dbd9379e 100644
--- a/matlab/dyn_second_order_solver.m
+++ b/matlab/dyn_second_order_solver.m
@@ -62,7 +62,7 @@ k1 = nonzeros(M.lead_lag_incidence(:,dr.order_var)');
 kk1 = [k1; length(k1)+(1:M.exo_nbr+M.exo_det_nbr)'];
 nk = size(kk1,1);
 kk2 = reshape(1:nk^2,nk,nk);
-ic = [ M.nstatic+(1:M.nspred) M.endo_nbr+(1:size(dr.ghx,2)-M.nspred) ]';
+ic = [ M.nstatic+(1:M.nspred) ]';
 
 klag  = M.lead_lag_incidence(1,dr.order_var); %columns are in DR order
 kcurr = M.lead_lag_incidence(2,dr.order_var); %columns are in DR order
diff --git a/matlab/dynare.m b/matlab/dynare.m
index f2460990155d604c713fe2590d0bbf688e8ec46e..4df698911f1d899664e4a4c016f39800faf39976 100644
--- a/matlab/dynare.m
+++ b/matlab/dynare.m
@@ -16,7 +16,7 @@ function dynare(fname, varargin)
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2001-2020 Dynare Team
+% Copyright (C) 2001-2021 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -184,16 +184,14 @@ nolog = ismember('nolog', varargin) || ismember('nolog', file_opts);
 onlymacro = ismember('onlymacro', varargin) || ismember('onlymacro', file_opts);
 onlyjson = ismember('onlyjson', varargin) || ismember('onlyjson', file_opts);
 
-if ispc
-    arch = getenv('PROCESSOR_ARCHITECTURE');
-else
-    [~, arch] = system('uname -m');
-end
-
-if isempty(strfind(arch, '64'))
-    arch_ext = '32';
-else
-    arch_ext = '64';
+% Start journal
+diary off
+if ~nolog
+    logfile = [ fname(1:end-4) '.log' ];
+    if exist(logfile, 'file')
+        delete(logfile)
+    end
+    diary(logfile)
 end
 
 if preprocessoroutput
@@ -206,7 +204,7 @@ if preprocessoroutput
     end
 end
 
-command = ['"' dynareroot 'preprocessor' arch_ext filesep 'dynare_m" ' fname] ;
+command = ['"' dynareroot '..' filesep 'preprocessor' filesep 'dynare-preprocessor" ' fname] ;
 command = [ command ' mexext=' mexext ' "matlabroot=' matlabroot '"'];
 % Properly quote arguments before passing them to the shell
 if ~isempty(varargin)
@@ -265,15 +263,8 @@ if exist(fname(1:end-4),'dir') && exist([fname(1:end-4) filesep 'hooks'],'dir')
     run([fname(1:end-4) filesep 'hooks/postprocessing'])
 end
 
-% Save preprocessor result in logfile (if `no_log' option not present)
-if ~nolog
-    logname = [fname(1:end-4) '.log'];
-    fid = fopen(logname, 'w');
-    fprintf(fid, '%s', result);
-    fclose(fid);
-end
-
 if status
+    diary off
     % Should not use "error(result)" since message will be truncated if too long
     error('Dynare: preprocessing failed')
 end
@@ -286,7 +277,14 @@ end
 % within the driver will clean the rest)
 clear(['+' fname '/driver'])
 
-evalin('base',[fname '.driver']) ;
+try
+    evalin('base',[fname '.driver']) ;
+catch ME
+    diary off
+    rethrow(ME)
+end
+
+diary off
 
 end
 
diff --git a/matlab/dynare_config.m b/matlab/dynare_config.m
index a513b0474bd1927b90b9fba36b8375151034d7fb..f54506f4fa41734cfce21cf7dac064297773b72a 100644
--- a/matlab/dynare_config.m
+++ b/matlab/dynare_config.m
@@ -90,8 +90,8 @@ if isoctave && octave_ver_less_than('5')
     p{end+1} = '/missing/ordeig';
 end
 
-%% intersect(…, 'stable') doesn't exist in Octave
-if isoctave
+%% intersect(…, 'stable') doesn't exist in Octave < 6
+if isoctave && octave_ver_less_than('6')
     p{end+1} = '/missing/intersect_stable';
 end
 
diff --git a/matlab/dynare_estimation.m b/matlab/dynare_estimation.m
index 812857d0037ca88af26a8ed1da1d5e07e8122f00..07f1300e16aebb28287eff6fd728720b9e8ae680 100644
--- a/matlab/dynare_estimation.m
+++ b/matlab/dynare_estimation.m
@@ -147,7 +147,7 @@ if nnobs > 1 && horizon > 0
     [~,nr,nc,~,~,nstar] = pltorg(nvar);
     m = 1;
     plot_index=0;
-    OutputDirectoryName = CheckPath('graphs',M_.fname);
+    OutputDirectoryName = CheckPath('graphs',M_.dname);
     for i = 1:length(var_list)
         if mod(i,nstar) == 1
             plot_index=plot_index+1;
@@ -208,7 +208,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_.fname,filesep,'graphs',filesep M_.fname '_RecursiveForecasts_' int2str(plot_index)],options_.nodisplay,options_.graph_format);
+            dyn_saveas(hfig,[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 ca97cd30f569daec4b0c021a452904f265f7dad0..7d49dcff901932d8d14f80a070e0caf2749cad15 100644
--- a/matlab/dynare_estimation_1.m
+++ b/matlab/dynare_estimation_1.m
@@ -557,11 +557,11 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
 
     if ~options_.nograph
         [nbplt,nr,nc,lr,lc,nstar] = pltorg(M_.exo_nbr);
-        if ~exist([M_.fname '/graphs'],'dir')
-            mkdir(M_.fname,'graphs');
+        if ~exist([M_.dname '/graphs'],'dir')
+            mkdir(M_.dname,'graphs');
         end
         if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
-            fidTeX = fopen([M_.fname, '/graphs/' M_.fname '_SmoothedShocks.tex'],'w');
+            fidTeX = fopen([M_.dname, '/graphs/' M_.fname '_SmoothedShocks.tex'],'w');
             fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation_1.m (Dynare).\n');
             fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
             fprintf(fidTeX,' \n');
@@ -599,11 +599,11 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
                     title(name,'Interpreter','none')
                 end
             end
-            dyn_saveas(fh,[M_.fname, '/graphs/' M_.fname '_SmoothedShocks' int2str(plt)],options_.nodisplay,options_.graph_format);
+            dyn_saveas(fh,[M_.dname, '/graphs/' M_.fname '_SmoothedShocks' int2str(plt)],options_.nodisplay,options_.graph_format);
             if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                 fprintf(fidTeX,'\\begin{figure}[H]\n');
                 fprintf(fidTeX,'\\centering \n');
-                fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_SmoothedShocks%s}\n',options_.figures.textwidth*min(i/nc,1),[M_.fname, '/graphs/' M_.fname],int2str(plt));
+                fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_SmoothedShocks%s}\n',options_.figures.textwidth*min(i/nc,1),[M_.dname, '/graphs/' M_.fname],int2str(plt));
                 fprintf(fidTeX,'\\caption{Smoothed shocks.}');
                 fprintf(fidTeX,'\\label{Fig:SmoothedShocks:%s}\n',int2str(plt));
                 fprintf(fidTeX,'\\end{figure}\n');
@@ -628,7 +628,7 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
         if ~options_.nograph
             [nbplt,nr,nc,lr,lc,nstar] = pltorg(number_of_plots_to_draw);
             if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
-                fidTeX = fopen([M_.fname, '/graphs/' M_.fname '_SmoothedObservationErrors.tex'],'w');
+                fidTeX = fopen([M_.dname, '/graphs/' M_.fname '_SmoothedObservationErrors.tex'],'w');
                 fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation_1.m (Dynare).\n');
                 fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
                 fprintf(fidTeX,' \n');
@@ -665,11 +665,11 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
                         title(name,'Interpreter','none')
                     end
                 end
-                dyn_saveas(fh,[M_.fname, '/graphs/' M_.fname '_SmoothedObservationErrors' int2str(plt)],options_.nodisplay,options_.graph_format);
+                dyn_saveas(fh,[M_.dname, '/graphs/' M_.fname '_SmoothedObservationErrors' int2str(plt)],options_.nodisplay,options_.graph_format);
                 if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                     fprintf(fidTeX,'\\begin{figure}[H]\n');
                     fprintf(fidTeX,'\\centering \n');
-                    fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_SmoothedObservationErrors%s}\n',options_.figures.textwidth*min(i/nc,1),[M_.fname, '/graphs/' M_.fname],int2str(plt));
+                    fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_SmoothedObservationErrors%s}\n',options_.figures.textwidth*min(i/nc,1),[M_.dname, '/graphs/' M_.fname],int2str(plt));
                     fprintf(fidTeX,'\\caption{Smoothed observation errors.}');
                     fprintf(fidTeX,'\\label{Fig:SmoothedObservationErrors:%s}\n',int2str(plt));
                     fprintf(fidTeX,'\\end{figure}\n');
@@ -689,7 +689,7 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
     if ~options_.nograph
         [nbplt,nr,nc,lr,lc,nstar] = pltorg(n_varobs);
         if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
-            fidTeX = fopen([M_.fname, '/graphs/' M_.fname '_HistoricalAndSmoothedVariables.tex'],'w');
+            fidTeX = fopen([M_.dname, '/graphs/' M_.fname '_HistoricalAndSmoothedVariables.tex'],'w');
             fprintf(fidTeX,'%% TeX eps-loader file generated by dynare_estimation_1.m (Dynare).\n');
             fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
             fprintf(fidTeX,' \n');
@@ -727,11 +727,11 @@ if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.psha
                     title(name,'Interpreter','none')
                 end
             end
-            dyn_saveas(fh,[M_.fname, '/graphs/' M_.fname '_HistoricalAndSmoothedVariables' int2str(plt)],options_.nodisplay,options_.graph_format);
+            dyn_saveas(fh,[M_.dname, '/graphs/' M_.fname '_HistoricalAndSmoothedVariables' int2str(plt)],options_.nodisplay,options_.graph_format);
             if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
                 fprintf(fidTeX,'\\begin{figure}[H]\n');
                 fprintf(fidTeX,'\\centering \n');
-                fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_HistoricalAndSmoothedVariables%s}\n',options_.figures.textwidth*min(i/nc,1),[M_.fname, '/graphs/' M_.fname],int2str(plt));
+                fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_HistoricalAndSmoothedVariables%s}\n',options_.figures.textwidth*min(i/nc,1),[M_.dname, '/graphs/' M_.fname],int2str(plt));
                 fprintf(fidTeX,'\\caption{Historical and smoothed variables.}');
                 fprintf(fidTeX,'\\label{Fig:HistoricalAndSmoothedVariables:%s}\n',int2str(plt));
                 fprintf(fidTeX,'\\end{figure}\n');
diff --git a/matlab/dynare_estimation_init.m b/matlab/dynare_estimation_init.m
index 27cc95b34de93c8f74799e04293dc5938a429e2b..13e9bbf2e9089c4221965cc3e4bdd0c160a6df22 100644
--- a/matlab/dynare_estimation_init.m
+++ b/matlab/dynare_estimation_init.m
@@ -555,6 +555,18 @@ end
 %set options for old interface from the ones for new interface
 if ~isempty(dataset_)
     options_.nobs = dataset_.nobs;
+    if options_.endogenous_prior 
+        if dataset_info.missing.no_more_missing_observations<dataset_.nobs-10
+            fprintf('\ndynare_estimation_init: There are missing observations in the data.\n')
+            fprintf('dynare_estimation_init: I am computing the moments for the endogenous prior only\n')
+            fprintf('dynare_estimation_init: on the observations after the last missing one, i.e. %u.\n',dataset_info.missing.no_more_missing_observations)
+        else
+            fprintf('\ndynare_estimation_init: There are too many missing observations in the data.\n')        
+            fprintf('dynare_estimation_init: The endogenous_prior-option needs a consistent sample of \n')
+            fprintf('dynare_estimation_init: at least 10 full observations at the end.\n')
+            error('The endogenous_prior-option does not support your missing data.')
+        end
+    end
 end
 
 % setting steadystate_check_flag option
diff --git a/matlab/dynare_identification.m b/matlab/dynare_identification.m
index 063f4e451c91fc7dd117707f8f41695aafe4d792..c843f1b808195687c569b8b2502fcbc83ff8b92b 100644
--- a/matlab/dynare_identification.m
+++ b/matlab/dynare_identification.m
@@ -139,6 +139,8 @@ options_ident = set_default_option(options_ident,'tol_deriv',1.e-8);
     % tolerance level for selecting columns of non-zero derivatives
 options_ident = set_default_option(options_ident,'tol_sv',1.e-3);
     % tolerance level for selecting non-zero singular values in identification_checks.m
+options_ident = set_default_option(options_ident,'schur_vec_tol',1e-11);
+    % tolerance level used to find nonstationary variables in Schur decomposition of the transition matrix.
 
 %check whether to compute identification strength based on information matrix
 if ~isfield(options_ident,'no_identification_strength')
@@ -289,7 +291,7 @@ if options_ident.order == 3
 end
 options_.ar = options_ident.ar;
 options_.prior_mc = options_ident.prior_mc;
-options_.Schur_vec_tol = 1.e-8;
+options_.schur_vec_tol = options_ident.schur_vec_tol;
 options_.nomoments = 0;
 options_.analytic_derivation=options_ident.analytic_derivation;
     % 1: analytic derivation of gradient and hessian of likelihood in dsge_likelihood.m, only works for stationary models, i.e. kalman_algo<3
diff --git a/matlab/endogenous_prior.m b/matlab/endogenous_prior.m
index 26ea7ce5f5b9028f0ab68f28a0ca546e67f84278..5a192ad190eee360da4ed61061b6d50af8f5ffb9 100644
--- a/matlab/endogenous_prior.m
+++ b/matlab/endogenous_prior.m
@@ -1,8 +1,9 @@
-function [lnpriormom] = endogenous_prior(data,Pstar,BayesInfo,H)
+function [lnpriormom] = endogenous_prior(data,dataset_info, Pstar,BayesInfo,H)
 % Computes the endogenous log prior addition to the initial prior
 %
 % INPUTS
 %    data           [double]     n*T vector of data observations
+%    dataset_info   [structure]  various information about the dataset
 %    Pstar          [double]     k*k matrix of
 %    BayesInfo      [structure]
 %
@@ -11,7 +12,7 @@ function [lnpriormom] = endogenous_prior(data,Pstar,BayesInfo,H)
 
 % Code to implement notes on endogenous priors by Lawrence Christiano,
 % specified in the appendix of:
-% ’Introducing Financial Frictions and Unemployment into a Small Open Economy Model’
+% Introducing Financial Frictions and Unemployment into a Small Open Economy Model
 % by Lawrence J. Christiano, Mathias Trabandt and Karl Walentin (2011), Journal of Economic Dynamics and Control
 % this is the 'mother' of the priors on the model parameters.
 % the priors include a metric across some choosen moments of the (supposedly
@@ -41,7 +42,8 @@ function [lnpriormom] = endogenous_prior(data,Pstar,BayesInfo,H)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-Y=data';
+Y=data(:,dataset_info.missing.no_more_missing_observations:end)';
+
 [Tsamp,n]=size(Y);    % sample length and number of matched moments (here set equal to nr of observables)
 
 hmat=zeros(n,Tsamp);
@@ -85,4 +87,4 @@ Z=II(mf,:);
 Ftheta=diag(Z*Pstar(:,mf)+H);
 % below commented out line is for Del Negro Schorfheide style priors:
 %     lnpriormom=-.5*n*TT*log(2*pi)-.5*TT*log(det(sigma))-.5*TT*trace(inv(sigma)*(gamyy-2*phi'*gamxy+phi'*gamxx*phi));
-lnpriormom=.5*n*log(Tsamp/(2*pi))-.5*log(det(Shat))-.5*Tsamp*(Fhat-Ftheta)'/Shat*(Fhat-Ftheta);
+lnpriormom=.5*n*log(Tsamp/(2*pi))-.5*log(det(Shat))-.5*Tsamp*(Fhat-Ftheta)'/Shat*(Fhat-Ftheta);
\ No newline at end of file
diff --git a/matlab/ep/ep_notes.org b/matlab/ep/ep_notes.org
index 7585a4918adf616ceb72458640c7bf8ac0179a1f..9c043fded7f5bb3358617cc33602bbc7bf98e962 100644
--- a/matlab/ep/ep_notes.org
+++ b/matlab/ep/ep_notes.org
@@ -37,7 +37,6 @@ ep:
                                 ortpol: 'hermite'
                                 nodes: 5
                                 pruned: [1x1 struct]
-   use_bytecode: 0
    verbosity: 0
 initial_period: NaN
 lmmcp:
@@ -59,7 +58,6 @@ ut: (unscented free parameter)
 pfm.stochastic_order = DynareOptions.ep.stochastic.order;
 pfm.periods = DynareOptions.ep.periods;
 pfm.verbose = DynareOptions.ep.verbosity;
-pfm.use_bytecode = DynareOptions.ep.use_bytecode ;
 
 
 * in extended_path_core, one passes options.ep and individual options
diff --git a/matlab/ep/euler_equation_error.m b/matlab/ep/euler_equation_error.m
index f2b9a896ea1ab6a198a8b66e03baf930349a20fe..d6efe622ac660b0caaf374bf0fb38664229c60da 100644
--- a/matlab/ep/euler_equation_error.m
+++ b/matlab/ep/euler_equation_error.m
@@ -1,6 +1,6 @@
 function e = euler_equation_error(y0,x,innovations,M,options,oo,pfm,nodes,weights)
 
-% Copyright (C) 2016-2017 Dynare Team
+% Copyright (C) 2016-2020 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -23,7 +23,7 @@ ep = options.ep;
                                                   M.endo_nbr, M.exo_nbr, ...
                                                   innovations.positive_var_indx, ...
                                                   x, ep.init, y0, oo.steady_state, ...
-                                                  0, ep.use_bytecode, ...
+                                                  0, ...
                                                   ep.stochastic.order, M, ...
                                                   pfm, ep.stochastic.algo, ...
                                                   ep.solve_algo, ...
@@ -39,7 +39,7 @@ for i=1:length(nodes)
     [y2, info_convergence, endogenousvariablespaths] = ...
         extended_path_core(ep.periods, M.endo_nbr, M.exo_nbr, ...
                            innovations.positive_var_indx, x2, ep.init, ...
-                           y1, oo.steady_state, 0, ep.use_bytecode, ...
+                           y1, oo.steady_state, 0, ...
                            ep.stochastic.order, M, pfm, ep.stochastic.algo, ...
                            ep.solve_algo, ep.stack_solve_algo, options.lmmcp, ...
                            options, oo, []);
@@ -47,4 +47,4 @@ for i=1:length(nodes)
     z = [y0(i_pred); y1; y2(i_fwrd)];
     res(:,i) = dynamic_model(z,x,M.params,oo.steady_state,2);
 end
-e = res*weights;
\ No newline at end of file
+e = res*weights;
diff --git a/matlab/ep/extended_path.m b/matlab/ep/extended_path.m
index c7bfdb23e3f73e8dd6245733ce194102620a3186..82e55ccbae56a868fd57567b3bd180ce594a2c36 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 (C) 2009-2018 Dynare Team
+% Copyright (C) 2009-2020 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -70,7 +70,7 @@ while (t <= samplesize)
     [endogenous_variables_paths(:,t), info_convergence, endogenousvariablespaths] = extended_path_core(ep.periods, DynareModel.endo_nbr, DynareModel.exo_nbr, innovations.positive_var_indx, ...
                                                       spfm_exo_simul, ep.init, endogenous_variables_paths(:,t-1), ...
                                                       DynareResults.steady_state, ...
-                                                      verbosity, ep.use_bytecode, ep.stochastic.order, ...
+                                                      verbosity, ep.stochastic.order, ...
                                                       DynareModel, pfm, ep.stochastic.algo, ep.solve_algo, ep.stack_solve_algo, ...
                                                       DynareOptions.lmmcp, ...
                                                       DynareOptions, ...
@@ -105,4 +105,4 @@ assignin('base', 'Simulated_time_series', ts);
 
 if ~nargout || nargout<2
     assignin('base', 'oo_', DynareResults);
-end
\ No newline at end of file
+end
diff --git a/matlab/ep/extended_path_core.m b/matlab/ep/extended_path_core.m
index 99575734277ed5f0c45421fa7b92f001c0c1e1f5..2fee70d824829cc54f069a5b59cbb685ecba4a35 100644
--- a/matlab/ep/extended_path_core.m
+++ b/matlab/ep/extended_path_core.m
@@ -1,7 +1,7 @@
 function [y, info_convergence, endogenousvariablespaths] = extended_path_core(periods,endo_nbr,exo_nbr,positive_var_indx, ...
                                                   exo_simul,init,initial_conditions,...
                                                   steady_state, ...
-                                                  debug,bytecode_flag,order,M,pfm,algo,solve_algo,stack_solve_algo,...
+                                                  debug,order,M,pfm,algo,solve_algo,stack_solve_algo,...
                                                   olmmcp,options,oo,initialguess)
 
 % Copyright (C) 2016-2020 Dynare Team
@@ -40,46 +40,38 @@ if debug
     save ep_test_1.mat endo_simul exo_simul
 end
 
-if bytecode_flag && ~ep.stochastic.order
-    try
-        tmp = bytecode('dynamic', endo_simul, exo_simul, M.params, endo_simul, periods);
-        flag = false;
-    catch ME
-        disp(ME.message);
-        flag = true;
-    end
-else
-    flag = true;
+if options.bytecode && order > 0
+    error('Option order > 0 of extended_path command is not compatible with bytecode option.')
+end
+if options.block && order > 0
+    error('Option order > 0 of extended_path command is not compatible with block option.')
 end
 
-if flag
-    if order == 0
-        options.periods = periods;
-        options.block = pfm.block;
-        oo.endo_simul = endo_simul;
-        oo.exo_simul = exo_simul;
-        oo.steady_state = steady_state;
-        options.bytecode = bytecode_flag;
-        options.lmmcp = olmmcp;
-        options.solve_algo = solve_algo;
-        options.stack_solve_algo = stack_solve_algo;
-        tmp = perfect_foresight_solver_core(M, options, oo);
-        if ~tmp.deterministic_simulation.status
-            info_convergence = false;
-        else
-            info_convergence = true;
-        end
+if order == 0
+    options.periods = periods;
+    options.block = pfm.block;
+    oo.endo_simul = endo_simul;
+    oo.exo_simul = exo_simul;
+    oo.steady_state = steady_state;
+    options.lmmcp = olmmcp;
+    options.solve_algo = solve_algo;
+    options.stack_solve_algo = stack_solve_algo;
+    tmp = perfect_foresight_solver_core(M, options, oo);
+    if ~tmp.deterministic_simulation.status
+        info_convergence = false;
     else
-        switch(algo)
-          case 0
+        info_convergence = true;
+    end
+else
+    switch(algo)
+        case 0
             [flag, tmp.endo_simul] = ...
-                solve_stochastic_perfect_foresight_model(endo_simul, exo_simul, pfm, ep.stochastic.quadrature.nodes, ep.stochastic.order);
-          case 1
+            solve_stochastic_perfect_foresight_model(endo_simul, exo_simul, pfm, ep.stochastic.quadrature.nodes, ep.stochastic.order);
+        case 1
             [flag, tmp.endo_simul] = ...
-                solve_stochastic_perfect_foresight_model_1(endo_simul, exo_simul, options, pfm, ep.stochastic.order);
-        end
-        info_convergence = ~flag;
+            solve_stochastic_perfect_foresight_model_1(endo_simul, exo_simul, options, pfm, ep.stochastic.order);
     end
+    info_convergence = ~flag;
 end
 
 if ~info_convergence && ~options.no_homotopy
diff --git a/matlab/ep/extended_path_initialization.m b/matlab/ep/extended_path_initialization.m
index 33d76339152049ece7675b5ceca8da13ed460a01..302112bb5af141a383a96cbf5a7c68134ff8c697 100644
--- a/matlab/ep/extended_path_initialization.m
+++ b/matlab/ep/extended_path_initialization.m
@@ -35,9 +35,6 @@ function [initial_conditions, innovations, pfm, ep, verbosity, DynareOptions, Dy
 
 ep  = DynareOptions.ep;
 
-% Set bytecode flag (see #1717)
-ep.use_bytecode = DynareOptions.bytecode;
-
 % Set verbosity levels.
 DynareOptions.verbosity = ep.verbosity;
 verbosity = ep.verbosity+ep.debug;
diff --git a/matlab/ep/extended_path_mc.m b/matlab/ep/extended_path_mc.m
index f31ae2dc9647b4570cd8851dd8695d0ad7ed1ffc..901235d7e4d08cc67e8c681596c9bbb21a4dfaf9 100644
--- a/matlab/ep/extended_path_mc.m
+++ b/matlab/ep/extended_path_mc.m
@@ -19,7 +19,7 @@ function Simulations = extended_path_mc(initialconditions, samplesize, replic, e
 %
 % SPECIAL REQUIREMENTS
 
-% Copyright (C) 2016-2017 Dynare Team
+% Copyright (C) 2016-2020 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -83,7 +83,7 @@ if ep.parallel
             [endogenous_variables_paths(:,t), info_convergence] = extended_path_core(ep.periods, DynareModel.endo_nbr, DynareModel.exo_nbr, innovations_.positive_var_indx, ...
                                                               spfm_exo_simul, ep.init, endogenous_variables_paths(:,t-1), ...
                                                               DynareResults_.steady_state, ...
-                                                              ep.verbosity, ep.use_bytecode, ep.stochastic.order, ...
+                                                              ep.verbosity, ep.stochastic.order, ...
                                                               DynareModel, pfm,ep.stochastic.algo, ep.solve_algo, ep.stack_solve_algo, ...
                                                               DynareOptions.lmmcp, DynareOptions, DynareResults_);
             if ~info_convergence
@@ -112,7 +112,7 @@ else
             [endogenous_variables_paths(:,t), info_convergence] = extended_path_core(ep.periods, DynareModel.endo_nbr, DynareModel.exo_nbr, innovations.positive_var_indx, ...
                                                               spfm_exo_simul, ep.init, endogenous_variables_paths(:,t-1), ...
                                                               DynareResults.steady_state, ...
-                                                              ep.verbosity, ep.use_bytecode, ep.stochastic.order, ...
+                                                              ep.verbosity, ep.stochastic.order, ...
                                                               DynareModel, pfm,ep.stochastic.algo, ep.solve_algo, ep.stack_solve_algo, ...
                                                               DynareOptions.lmmcp, DynareOptions, DynareResults);
             if ~info_convergence
diff --git a/matlab/ep/setup_stochastic_perfect_foresight_model_solver.m b/matlab/ep/setup_stochastic_perfect_foresight_model_solver.m
index 55e4d8a822d7c10769a5f668e2b974a6008a2203..3e68407d3864e393eb9b261b88f4c9a053052e46 100644
--- a/matlab/ep/setup_stochastic_perfect_foresight_model_solver.m
+++ b/matlab/ep/setup_stochastic_perfect_foresight_model_solver.m
@@ -1,6 +1,6 @@
 function pfm = setup_stochastic_perfect_foresight_model_solver(DynareModel,DynareOptions,DynareOutput)
 
-% Copyright (C) 2013-2017 Dynare Team
+% Copyright (C) 2013-2020 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -66,8 +66,9 @@ else
 end
 pfm.i_cols_j = 1:pfm.nd;
 pfm.i_upd = pfm.ny+(1:pfm.periods*pfm.ny);
-pfm.dynamic_model = str2func([DynareModel.fname,'.dynamic']);
+if ~DynareOptions.bytecode
+    pfm.dynamic_model = str2func([DynareModel.fname,'.dynamic']);
+end
 pfm.verbose = DynareOptions.ep.verbosity;
 pfm.maxit_ = DynareOptions.simul.maxit;
 pfm.tolerance = DynareOptions.dynatol.f;
-pfm.use_bytecode = DynareOptions.ep.use_bytecode ;
diff --git a/matlab/evaluate_planner_objective.m b/matlab/evaluate_planner_objective.m
index 63ec0ab6a7c380c7a0829a54fd03e8d755e00353..a6df353260b7916ce77032f1a111f906a366be39 100644
--- a/matlab/evaluate_planner_objective.m
+++ b/matlab/evaluate_planner_objective.m
@@ -37,11 +37,6 @@ dr = oo.dr;
 exo_nbr = M.exo_nbr;
 nstatic = M.nstatic;
 nspred = M.nspred;
-if nspred > 180
-    fprintf('\nevaluate_planner_objective: model too large, can''t evaluate planner objective\n')
-    planner_objective_value = NaN;
-    return
-end
 beta = get_optimal_policy_discount_factor(M.params, M.param_names);
 
 Gy = dr.ghx(nstatic+(1:nspred),:);
@@ -64,7 +59,13 @@ Uyygygu = A_times_B_kronecker_C(Uyy,gy,gu);
 Wbar =U/(1-beta); %steady state welfare
 Wy = Uy*gy/(eye(nspred)-beta*Gy);
 Wu = Uy*gu+beta*Wy*Gu;
-Wyy = Uyygygy/(eye(nspred*nspred)-beta*kron(Gy,Gy));
+% Wyy = Uyygygy/(eye(nspred*nspred)-beta*kron(Gy,Gy)); %solve Wyy=Uyy*kron(gy,gy)+beta*Wyy*kron(Gy,Gy)
+if isempty(options.qz_criterium)
+    options.qz_criterium = 1+1e-6;
+end
+%solve Lyapunuv equation Wyy=gy'*Uyy*gy+beta*Gy'Wyy*Gy
+Wyy = reshape(lyapunov_symm(sqrt(beta)*Gy',reshape(Uyygygy,nspred,nspred),options.lyapunov_fixed_point_tol,options.qz_criterium,options.lyapunov_complex_threshold, 3, options.debug),1,nspred*nspred);
+
 Wyygugu = A_times_B_kronecker_C(Wyy,Gu,Gu);
 Wyygygu = A_times_B_kronecker_C(Wyy,Gy,Gu);
 Wuu = Uyygugu+beta*Wyygugu;
diff --git a/matlab/evaluate_steady_state.m b/matlab/evaluate_steady_state.m
index 8fc5826c875e95af34205bb8fe0ccc96436a0a1e..10e5a839de770d079335457c28a401ebd80b834a 100644
--- a/matlab/evaluate_steady_state.m
+++ b/matlab/evaluate_steady_state.m
@@ -309,12 +309,22 @@ if M.static_and_dynamic_models_differ
     if options.bytecode
         [r, ~]= bytecode('dynamic','evaluate', z, zx, params, ys, 1);
     elseif options.block
-        [r, oo.dr] = feval([M.fname '.dynamic'], z', zx, params, ys, M.maximum_lag+1, oo.dr);
+        T=NaN(M.block_structure.dyn_tmp_nbr, 1);
+        for i = 1:length(M.block_structure.block)
+            [rr, yy, T, g] = feval([M.fname '.dynamic'], i, ...
+                                   dynvars_from_endo_simul(z, M.maximum_lag+1, M), ...
+                                   zx, params, ys, T, M.maximum_lag+1, false);
+            if M.block_structure.block(i).Simulation_Type == 1 || ... % evaluateForward
+               M.block_structure.block(i).Simulation_Type == 2        % evaluateBackward
+                vidx = M.block_structure.block(i).variable;
+                rr = yy(M.lead_lag_incidence(M.maximum_endo_lag+1, vidx)) - oo.steady_state(vidx);
+            end
+            idx = M.block_structure.block(i).equation;
+            r(idx) = rr;
+        end
     else
-        iyv = M.lead_lag_incidence';
-        iyr0 = find(iyv(:));
-        xys = z(iyr0);
-        r = feval([M.fname '.dynamic'], z(iyr0), zx, params, ys, M.maximum_lag + 1);
+        r = feval([M.fname '.dynamic'], dynvars_from_endo_simul(z, M.maximum_lag+1, M), ...
+                  zx, params, ys, M.maximum_lag + 1);
     end
     % Fail if residual greater than tolerance
     if max(abs(r)) > options.solve_tolf
diff --git a/matlab/get_error_message.m b/matlab/get_error_message.m
index c4ed1148a4de596af8963bb0c08530f91409a2d8..8ba23678e40bd4493dceef22e91327aabb4b7edc 100644
--- a/matlab/get_error_message.m
+++ b/matlab/get_error_message.m
@@ -122,7 +122,7 @@ switch info(1)
     case 64
         message = 'discretionary_policy: the derivatives of the objective function contain NaN.';
     case 65
-        message = 'discretionary_policy: the model must be written in deviation form and not have constant terms.';
+        message = 'discretionary_policy: the model must be written in deviation form and not have constant terms or an analytical steady state meeds to be provided.';
     case 66
         message = 'discretionary_policy: the objective function must have zero first order derivatives.';
     case 71
diff --git a/matlab/get_variance_of_endogenous_variables.m b/matlab/get_variance_of_endogenous_variables.m
index 965319b1bdadf8960309f849c305f3b883be58fc..02ea62d6b0eb5af938449b31e952c3ffdbed9b32 100644
--- a/matlab/get_variance_of_endogenous_variables.m
+++ b/matlab/get_variance_of_endogenous_variables.m
@@ -48,7 +48,7 @@ n = length(i_var);
 [vx,u] = lyapunov_symm(A,B*Sigma_e*B',options_.lyapunov_fixed_point_tol,options_.qz_criterium,options_.lyapunov_complex_threshold, [], options_.debug);
 
 if size(u,2) > 0
-    i_stat = find(any(abs(ghx*u) < options_.Schur_vec_tol,2)); %only set those variances of objective function for which variance is finite
+    i_stat = find(any(abs(ghx*u) < options_.schur_vec_tol,2)); %only set those variances of objective function for which variance is finite
     ghx = ghx(i_stat,:);
     ghu = ghu(i_stat,:);
 else
diff --git a/matlab/global_initialization.m b/matlab/global_initialization.m
index b3c4d268854d8d7d414a692e8f9788ff059f8496..02220f79479d25b02dbc665b2d4f9f3706cfc2eb 100644
--- a/matlab/global_initialization.m
+++ b/matlab/global_initialization.m
@@ -144,11 +144,6 @@ dyn_first_order_solver();
 % Set dynare random generator and seed.
 set_dynare_seed('default');
 
-
-% Create directories
-[~,~]=mkdir(M_.fname);
-[~,~]=mkdir([M_.fname filesep 'Output']);
-
 % Load user configuration file.
 if isfield(options_, 'global_init_file')
     if isfile(options_.global_init_file)
diff --git a/matlab/histvalf.m b/matlab/histvalf.m
index 07a6a25a7f5367cf86e80b7078fd32739f3841ac..a8f3092cde6efcea54703804399c1a9d84e67bb0 100644
--- a/matlab/histvalf.m
+++ b/matlab/histvalf.m
@@ -31,8 +31,6 @@ function [endo_histval, exo_histval, exo_det_histval] = histvalf(M, options)
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 series = histvalf_initvalf('HISTVAL', M, options);
-% capture the difference between stochastic and
-% perfect foresight setup
 k = M.orig_maximum_lag - M.maximum_lag + 1;
 endo_histval  = series{M.endo_names{:}}.data(k:end, :)';
 
diff --git a/matlab/identification_analysis.m b/matlab/identification_analysis.m
index 6262fb347a6bba5fd9d62242eb9b8d5ec92d76b1..ff773195cf7810d42f5618469f271a4b3b0f7140 100644
--- a/matlab/identification_analysis.m
+++ b/matlab/identification_analysis.m
@@ -147,18 +147,23 @@ if info(1) == 0 %no errors in solution
     if init
         %check stationarity
         if ~no_identification_moments
-            ind_dMOMENTS = (find(max(abs(dMOMENTS'),[],1) > tol_deriv)); %index for non-zero rows
-            if isempty(ind_dMOMENTS) && any(any(isnan(dMOMENTS)))
-                error('There are NaN in the dMOMENTS matrix. Please check whether your model has units roots and you forgot to set diffuse_filter=1.' )
-            end
             if any(any(isnan(MOMENTS)))
-                error('There are NaN''s in the theoretical moments: make sure that for non-stationary models stationary transformations of non-stationary observables are used for checking identification. [TIP: use first differences].')
+                if options_.diffuse_filter == 1 % use options_ as it inherits diffuse_filter from options_ident if set by user
+                    error('There are NaN''s in the theoretical moments. Make sure that for non-stationary models stationary transformations of non-stationary observables are used for checking identification. [TIP: use first differences].')
+                else
+                    error('There are NaN''s in the theoretical moments. Please check whether your model has units roots, and you forgot to set diffuse_filter=1.' )
+                end
             end
+            ind_dMOMENTS = (find(max(abs(dMOMENTS'),[],1) > tol_deriv)); %index for non-zero rows
+            if isempty(ind_dMOMENTS) && any(any(isnan(dMOMENTS)))                
+                error('There are NaN in the dMOMENTS matrix.' )
+            end
+            
         end
         if ~no_identification_spectrum
             ind_dSPECTRUM = (find(max(abs(dSPECTRUM'),[],1) > tol_deriv)); %index for non-zero rows
-            if isempty(ind_dSPECTRUM) && any(any(isnan(dSPECTRUM)))
-                warning_SPECTRUM = 'WARNING: There are NaN in the dSPECTRUM matrix. Please check whether your model has units roots and your forgot to set diffuse_filter=1.\n';
+            if any(any(isnan(dSPECTRUM)))
+                warning_SPECTRUM = 'WARNING: There are NaN in the dSPECTRUM matrix. Note that identification based on spectrum does not support non-stationary models (yet).\n';
                 warning_SPECTRUM = [warning_SPECTRUM '         Skip identification analysis based on spectrum.\n'];
                 fprintf(warning_SPECTRUM);
                 %reset options to neither display nor plot dSPECTRUM anymore
@@ -168,8 +173,8 @@ if info(1) == 0 %no errors in solution
         end
         if ~no_identification_minimal
             ind_dMINIMAL = (find(max(abs(dMINIMAL'),[],1) > tol_deriv)); %index for non-zero rows
-            if isempty(ind_dMINIMAL) && any(any(isnan(dMINIMAL)))
-                warning_MINIMAL = 'WARNING: There are NaN in the dMINIMAL matrix. Please check whether your model has units roots and you forgot to set diffuse_filter=1.\n';
+            if any(any(isnan(dMINIMAL)))
+                warning_MINIMAL = 'WARNING: There are NaN in the dMINIMAL matrix. Note that identification based on minimal system does not support non-stationary models (yet).\n';
                 warning_MINIMAL = [warning_MINIMAL '         Skip identification analysis based on minimal system.\n'];
                 fprintf(warning_MINIMAL);
                 %reset options to neither display nor plot dMINIMAL anymore
@@ -178,8 +183,8 @@ if info(1) == 0 %no errors in solution
             end
         end
         if no_identification_moments && no_identification_minimal && no_identification_spectrum
-            %display error if all three criteria fail
-            error('identification_analyis: Stationarity condition(s) failed and/or diffuse_filter option missing');
+            %display error if all three criteria fail            
+            error(sprintf('identification_analyis: Stationarity condition(s) failed and/or diffuse_filter option missing.\nMake sure that for non-stationary models stationary transformations of non-stationary observables are used for checking identification.\n[TIP: use first differences].'));
         end
 
         % Check order conditions
diff --git a/matlab/lmmcp/catstruct.m b/matlab/lmmcp/catstruct.m
index df4a9c05b500bbaac74a356d6aa3eebdd10ad050..a021b3ba3c592509f97d83ef224c553d0db75722 100644
--- a/matlab/lmmcp/catstruct.m
+++ b/matlab/lmmcp/catstruct.m
@@ -48,7 +48,7 @@ function A = catstruct(varargin)
 
 % Copyright (C) 2005 Jos van der Geest <jos@jasen.nl>
 % Copyright (C) 2013 Christophe Gouel
-% Copyright (C) 2016-2017 Dynare Team
+% Copyright (C) 2016-2020 Dynare Team
 %
 % Redistribution and use in source and binary forms, with or without
 % modification, are permitted provided that the following conditions are
@@ -150,7 +150,7 @@ else
     FN = squeeze(FN) ;
     VAL = squeeze(VAL) ;
     MatlabVersion = version;
-    if isoctave || str2double(MatlabVersion(end-5:end-2))<2013 % Equivalent to, but faster than if verLessThan('matlab','8.1')
+    if isoctave && octave_ver_less_than('6')
         [UFN,ind] = unique(FN) ;
     else
         [UFN,ind] = unique(FN,'legacy') ;
diff --git a/matlab/lmmcp/get_complementarity_conditions.m b/matlab/lmmcp/get_complementarity_conditions.m
index 6a1f2c1ed7862189f4d9fdf2bd841f99e463ed79..9cc6044eb402d035d4b3b3250dd183f6c38c8295 100644
--- a/matlab/lmmcp/get_complementarity_conditions.m
+++ b/matlab/lmmcp/get_complementarity_conditions.m
@@ -1,5 +1,5 @@
-function [lb,ub,eq_index] = get_complementarity_conditions(M,ramsey_policy)
-% [lb,ub,eq_index] = get_complementarity_conditions(M,ramsey_policy)
+function [lb,ub,eq_index] = get_complementarity_conditions(M_,ramsey_policy)
+% [lb,ub,eq_index] = get_complementarity_conditions(M_,ramsey_policy)
 % INPUTS
 %   - M                   [struct] contains a description of the model.
 %   - ramsey_policy       [boolean] indicator whether a Ramsey problem is considered
@@ -29,12 +29,12 @@ function [lb,ub,eq_index] = get_complementarity_conditions(M,ramsey_policy)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-ub = inf(M.endo_nbr,1);
+ub = inf(M_.endo_nbr,1);
 lb = -ub;
-eq_index = (1:M.endo_nbr)';
+eq_index = (1:M_.endo_nbr)';
 if ramsey_policy
-    if isfield(M,'ramsey_model_constraints')
-        rc = M.ramsey_model_constraints;
+    if isfield(M_,'ramsey_model_constraints')
+        rc = M_.ramsey_model_constraints;
         for i = 1:length(rc)
             switch rc{i}{2}
               case {'>','>='}
@@ -48,17 +48,17 @@ if ramsey_policy
     end
 end
 
-etags = M.equations_tags;
+etags = M_.equations_tags;
 for i=1:size(etags,1)
     if strcmp(etags{i,2},'mcp')
         eq_nbr = etags{i,1};
         if ramsey_policy
-            eq_nbr = eq_nbr + M.ramsey_eq_nbr;
+            eq_nbr = eq_nbr + M_.ramsey_eq_nbr;
         end
         str = etags{i,3};
         kop = strfind(etags{i,3},'<');
         if ~isempty(kop)
-            k = find(strcmp(strtrim(str(1:kop-1)), M.endo_names)); %get variable index with restriction
+            k = find(strcmp(strtrim(str(1:kop-1)), M_.endo_names)); %get variable index with restriction
             if isempty(k)
                 error(sprintf(['Complementarity condition %s: variable %s is ' ...
                                'not recognized'],etags{i,3},strtrim(str(1:kop-1))))
@@ -69,7 +69,7 @@ for i=1:size(etags,1)
         else
             kop = strfind(etags{i,3},'>');
             if ~isempty(kop)
-                k = find(strcmp(strtrim(str(1:kop-1)), M.endo_names)); %get variable index with restriction
+                k = find(strcmp(strtrim(str(1:kop-1)), M_.endo_names)); %get variable index with restriction
                 if isempty(k)
                     error(sprintf(['Complementarity condition %s: variable %s is ' ...
                                    'not recognized'],etags{i,3},strtrim(str(1:kop-1))))
diff --git a/matlab/method_of_moments/method_of_moments.m b/matlab/method_of_moments/method_of_moments.m
index 28ec839c943e553dca316fa54788c46ef9b77f00..9d6736116970e99fe1ccede3328ac0c27459f32b 100644
--- a/matlab/method_of_moments/method_of_moments.m
+++ b/matlab/method_of_moments/method_of_moments.m
@@ -49,8 +49,8 @@ function [oo_, options_mom_, M_] = method_of_moments(bayestopt_, options_, oo_,
 %  o get_all_parameters.m
 %  o get_matrix_entries_for_psd_check.m
 %  o makedataset.m
+%  o method_of_moments_check_plot.m
 %  o method_of_moments_data_moments.m
-%  o method_of_moments_mode_check.m
 %  o method_of_moments_objective_function.m
 %  o method_of_moments_optimal_weighting_matrix
 %  o method_of_moments_standard_errors
@@ -63,7 +63,7 @@ function [oo_, options_mom_, M_] = method_of_moments(bayestopt_, options_, oo_,
 %  o set_all_parameters.m
 %  o test_for_deep_parameters_calibration.m
 % =========================================================================
-% Copyright (C) 2020 Dynare Team
+% Copyright (C) 2020-2021 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -86,21 +86,13 @@ function [oo_, options_mom_, M_] = method_of_moments(bayestopt_, options_, oo_,
 % =========================================================================
 
 %% TO DO LIST
-% - [ ] why does lsqnonlin take less time in Andreasen toolbox?
-% - [ ] test user-specified weightning matrix
-% - [ ] which qz_criterium value?
-% - [ ] document that in method_of_moments_data_moments.m NaN are replaced by mean of moment
 % - [ ] add IRF matching
-% - [ ] test estimated_params_bounds block
-% - [ ] test what happens if all parameters will be estimated but some/all are not calibrated
-% - [ ] speed up lyapunov equation by using doubling with old initial values
-% - [ ] check smm at order > 3 without pruning
-% - [ ] provide option to use analytical derivatives to compute std errors (similar to what we already do in identification)
-% - [ ] add Bayesian GMM/SMM estimation
-% - [ ] useautocorr
-% - [ ] do we need dirname?
-% - [ ] decide on default weighting matrix scheme, I would propose 2 stage with Diagonal of optimal matrix
-% - [ ] check smm with product moments greater than 2
+% - [ ] speed up pruned_state_space_system (by using doubling with old initial values, hardcoding zeros, other "tricks" used in e.g. nlma)
+% - [ ] add option to use autocorrelations (we have useautocorr in identification toolbox already)
+% - [ ] SMM with extended path
+% - [ ] deal with measurement errors (once @wmutschl has implemented this in identification toolbox)
+% - [ ] improve check for duplicate moments by using the cellfun and unique functions
+% - [ ] dirname option to save output to different directory not yet implemented
 % -------------------------------------------------------------------------
 % Step 0: Check if required structures and options exist
 % -------------------------------------------------------------------------
@@ -125,7 +117,7 @@ else
     options_mom_.loglinear = false;
 end
 
-fprintf('\n==== Method of Moments (%s) Estimation ====\n\n',options_mom_.mom.mom_method)
+fprintf('\n==== Method of Moments Estimation (%s) ====\n\n',options_mom_.mom.mom_method)
 
 % -------------------------------------------------------------------------
 % Step 1a: Prepare options_mom_ structure
@@ -142,15 +134,15 @@ if strcmp(options_mom_.mom.mom_method,'GMM') || strcmp(options_mom_.mom.mom_meth
     options_mom_.mom = set_default_option(options_mom_.mom,'bartlett_kernel_lag',20);               % bandwith in optimal weighting matrix
     options_mom_.mom = set_default_option(options_mom_.mom,'penalized_estimator',false);            % include deviation from prior mean as additional moment restriction and use prior precision as weight
     options_mom_.mom = set_default_option(options_mom_.mom,'verbose',false);                        % display and store intermediate estimation results
-    options_mom_.mom = set_default_option(options_mom_.mom,'weighting_matrix',{'DIAGONAL'; 'DIAGONAL'});   % weighting matrix in moments distance objective function at each iteration of estimation; cell of strings with
+    options_mom_.mom = set_default_option(options_mom_.mom,'weighting_matrix',{'DIAGONAL'; 'DIAGONAL'});   % weighting matrix in moments distance objective function at each iteration of estimation;
                                                                                                            % possible values are 'OPTIMAL', 'IDENTITY_MATRIX' ,'DIAGONAL' or a filename. Size of cell determines stages in iterated estimation.
-    options_mom_.mom = set_default_option(options_mom_.mom,'weighting_matrix_scaling_factor',1);    % scaling of weighting matrix
+    options_mom_.mom = set_default_option(options_mom_.mom,'weighting_matrix_scaling_factor',1);    % scaling of weighting matrix in objective function
     options_mom_.mom = set_default_option(options_mom_.mom,'se_tolx',1e-5);                         % step size for numerical computation of standard errors
     options_mom_ = set_default_option(options_mom_,'order',1);                                      % order of Taylor approximation in perturbation
-    options_mom_ = set_default_option(options_mom_,'pruning',true);                                 % use pruned state space system at higher-order
+    options_mom_ = set_default_option(options_mom_,'pruning',false);                                % use pruned state space system at higher-order
     % Checks for perturbation order
     if options_mom_.order < 1
-        error('method_of_moments:: The order of the Taylor approximation cannot be 0!')
+        error('method_of_moments: The order of the Taylor approximation cannot be 0!')
     end
 end
 if strcmp(options_mom_.mom.mom_method,'SMM')
@@ -169,11 +161,16 @@ if strcmp(options_mom_.mom.mom_method,'GMM')
         fprintf('GMM at higher order only works with pruning, so we set pruning option to 1.\n');
         options_mom_.pruning = true;
     end
+    if options_mom_.order > 3
+        error('method_of_moments: perturbation orders higher than 3 are not implemented for GMM estimation, try using SMM.\n');
+    end
+    options_mom_.mom = set_default_option(options_mom_.mom,'analytic_standard_errors',false);       % compute standard errors numerically (0) or analytically (1). Analytical derivatives are only available for GMM.
 end
+options_mom_.mom.compute_derivs = false;% flag to compute derivs in objective function (needed for analytic standard errors with GMM)
 
     
 % General options that can be set by the user in the mod file, otherwise default values are provided
-options_mom_ = set_default_option(options_mom_,'dirname',M_.fname);    % directory in which to store estimation output
+options_mom_ = set_default_option(options_mom_,'dirname',M_.dname);    % specify directory in which to store estimation output [not yet working]
 options_mom_ = set_default_option(options_mom_,'graph_format','eps');  % specify the file format(s) for graphs saved to disk
 options_mom_ = set_default_option(options_mom_,'nodisplay',false);     % do not display the graphs, but still save them to disk
 options_mom_ = set_default_option(options_mom_,'nograph',false);       % do not create graphs (which implies that they are not saved to the disk nor displayed)
@@ -203,12 +200,12 @@ options_mom_ = set_default_option(options_mom_,'mode_compute',13);
 options_mom_ = set_default_option(options_mom_,'additional_optimizer_steps',[]); % vector of additional mode-finders run after mode_compute
 options_mom_ = set_default_option(options_mom_,'optim_opt',[]);                  % a list of NAME and VALUE pairs to set options for the optimization routines. Available options depend on mode_compute
 options_mom_ = set_default_option(options_mom_,'silent_optimizer',false);        % run minimization of moments distance silently without displaying results or saving files in between
-% Mode_check plot options that can be set by the user in the mod file, otherwise default values are provided
+% Check plot options that can be set by the user in the mod file, otherwise default values are provided
 options_mom_.mode_check.nolik = false;                                                          % we don't do likelihood (also this initializes mode_check substructure)
-options_mom_.mode_check = set_default_option(options_mom_.mode_check,'status',false);            % plot the target function for values around the computed mode for each estimated parameter in turn. This is helpful to diagnose problems with the optimizer.
-options_mom_.mode_check = set_default_option(options_mom_.mode_check,'neighbourhood_size',.5);  % width of the window around the mode to be displayed on the diagnostic plots. This width is expressed in percentage deviation. The Inf value is allowed, and will trigger a plot over the entire domain
-options_mom_.mode_check = set_default_option(options_mom_.mode_check,'symmetric_plots',true);   % ensure that the check plots are symmetric around the mode. A value of 0 allows to have asymmetric plots, which can be useful if the posterior mode is close to a domain boundary, or in conjunction with mode_check_neighbourhood_size = Inf when the domain is not the entire real line
-options_mom_.mode_check = set_default_option(options_mom_.mode_check,'number_of_points',20);    % number of points around the mode where the target function is evaluated (for each parameter)
+options_mom_.mode_check = set_default_option(options_mom_.mode_check,'status',false);           % plot the target function for values around the computed minimum for each estimated parameter in turn. This is helpful to diagnose problems with the optimizer.
+options_mom_.mode_check = set_default_option(options_mom_.mode_check,'neighbourhood_size',.5);  % width of the window around the computed minimum to be displayed on the diagnostic plots. This width is expressed in percentage deviation. The Inf value is allowed, and will trigger a plot over the entire domain
+options_mom_.mode_check = set_default_option(options_mom_.mode_check,'symmetric_plots',true);   % ensure that the check plots are symmetric around the minimum. A value of 0 allows to have asymmetric plots, which can be useful if the minimum is close to a domain boundary, or in conjunction with neighbourhood_size = Inf when the domain is not the entire real line
+options_mom_.mode_check = set_default_option(options_mom_.mode_check,'number_of_points',20);    % number of points around the minimum where the target function is evaluated (for each parameter)
 
 % Numerical algorithms options that can be set by the user in the mod file, otherwise default values are provided
 options_mom_ = set_default_option(options_mom_,'aim_solver',false);                     % use AIM algorithm to compute perturbation approximation instead of mjdgges
@@ -226,8 +223,11 @@ options_mom_ = set_default_option(options_mom_,'lyapunov_fixed_point_tol',1e-10)
 options_mom_ = set_default_option(options_mom_,'lyapunov_doubling_tol',1e-16);          % convergence criterion used in the doubling algorithm
 options_mom_ = set_default_option(options_mom_,'sylvester_fp',false);                   % determines whether to use fixed point algorihtm to solve Sylvester equation (gensylv_fp), faster for large scale models
 options_mom_ = set_default_option(options_mom_,'sylvester_fixed_point_tol',1e-12);      % convergence criterion used in the fixed point Sylvester solver
-options_mom_ = set_default_option(options_mom_,'qz_criterium',1-1e-6);                  % value used to split stable from unstable eigenvalues in reordering the Generalized Schur decomposition used for solving first order problems [IS THIS CORRET @wmutschl]
+options_mom_ = set_default_option(options_mom_,'qz_criterium',1-1e-6);                  % value used to split stable from unstable eigenvalues in reordering the Generalized Schur decomposition used for solving first order problems
+                                                                                        % if there are no unit roots one can use 1.0 (or slightly below) which we set as default; if they are possible, you may have have multiple unit roots and the accuracy decreases when computing the eigenvalues in lyapunov_symm
+                                                                                        % Note that unit roots are only possible at first-order, at higher order we set it to 1 in pruned_state_space_system and focus only on stationary observables.
 options_mom_ = set_default_option(options_mom_,'qz_zero_threshold',1e-6);               % value used to test if a generalized eigenvalue is 0/0 in the generalized Schur decomposition
+options_mom_ = set_default_option(options_mom_,'schur_vec_tol',1e-11);                  % tolerance level used to find nonstationary variables in Schur decomposition of the transition matrix.
 if options_mom_.order > 2
     fprintf('Dynare will use ''k_order_solver'' as the order>2\n');
     options_mom_.k_order_solver = true;
@@ -326,6 +326,7 @@ options_mom_.solveopt         = options_.solveopt;
 options_mom_.gradient_method  = options_.gradient_method;
 options_mom_.gradient_epsilon = options_.gradient_epsilon;
 options_mom_.analytic_derivation = 0;
+options_mom_.analytic_derivation_mode = 0; % needed by get_perturbation_params_derivs.m, ie use efficient sylvester equation method to compute analytical derivatives as in Ratto & Iskrev (2012)
 
 options_mom_.vector_output= false;           % specifies whether the objective function returns a vector
 
@@ -362,8 +363,6 @@ end
 % -------------------------------------------------------------------------
 % Step 2: Checks and transformations for matched moments structure (preliminary)
 % -------------------------------------------------------------------------
-% Note that we do not have a preprocessor interface yet for this, so this
-% will need much improvement later on. @wmutschl
 
 % Initialize indices
 options_mom_.mom.index.E_y       = false(options_mom_.obs_nbr,1);                      %unconditional first order product moments
@@ -423,8 +422,6 @@ for jm=1:size(M_.matched_moments,1)
     end
 end
 
-
-% @wmutschl: add check for duplicate moments by using the cellfun and unique functions
 %Remove duplicate elements
 UniqueMomIdx = [nonzeros(options_mom_.mom.index.E_y_pos); nonzeros(tril(options_mom_.mom.index.E_yy_pos)); nonzeros(options_mom_.mom.index.E_yyt_pos)];
 DuplicateMoms = setdiff(1:size(M_.matched_moments,1),UniqueMomIdx);
@@ -614,16 +611,14 @@ if ~isempty(dataset_)
     options_mom_.nobs = dataset_.nobs;
 end
 
-% provide info on missing observations
-if any(any(isnan(dataset_.data)))
-    fprintf('missing observations will be replaced by the sample mean of the corresponding moment')
-end
-
 % Check length of data for estimation of second moments
 if options_mom_.ar > options_mom_.nobs+1
     error('method_of_moments: Data set is too short to compute second moments');
 end
 
+% Provide info on data moments handling
+fprintf('Computing data moments. Note that NaN values in the moments (due to leads and lags or missing data) are replaced by the mean of the corresponding moment\n');
+
 % Get data moments for the method of moments
 [oo_.mom.data_moments, oo_.mom.m_data] = method_of_moments_data_moments(dataset_.data, oo_, M_.matched_moments, options_mom_);
 
@@ -632,9 +627,17 @@ if strcmp(options_mom_.mom.mom_method,'SMM')
     options_mom_.mom.long = round(options_mom_.mom.simulation_multiple*options_mom_.nobs);
     options_mom_.mom.variance_correction_factor = (1+1/options_mom_.mom.simulation_multiple);
     % draw shocks for SMM
-    smmstream = RandStream('mt19937ar','Seed',options_mom_.mom.seed);
-    temp_shocks = randn(smmstream,options_mom_.mom.long+options_mom_.mom.burnin,M_.exo_nbr);
-    temp_shocks_ME = randn(smmstream,options_mom_.mom.long,length(M_.H));
+    if ~isoctave
+        smmstream = RandStream('mt19937ar','Seed',options_mom_.mom.seed);
+        temp_shocks = randn(smmstream,options_mom_.mom.long+options_mom_.mom.burnin,M_.exo_nbr);
+        temp_shocks_ME = randn(smmstream,options_mom_.mom.long,length(M_.H));
+    else
+        [state_u,state_n] = get_dynare_random_generator_state; %get state for later resetting
+        set_dynare_random_generator_state(options_mom_.mom.seed,options_mom_.mom.seed);
+        temp_shocks = randn(options_mom_.mom.long+options_mom_.mom.burnin,M_.exo_nbr);
+        temp_shocks_ME = randn(options_mom_.mom.long,length(M_.H));  
+        set_dynare_random_generator_state(state_u,state_n); %reset state for later resetting
+    end
     if options_mom_.mom.bounded_shock_support == 1
         temp_shocks(temp_shocks>2) = 2;
         temp_shocks(temp_shocks<-2) = -2;
@@ -643,6 +646,9 @@ if strcmp(options_mom_.mom.mom_method,'SMM')
     end
     options_mom_.mom.shock_series = temp_shocks;
     options_mom_.mom.ME_shock_series = temp_shocks_ME;
+    if options_mom_.k_order_solver && ~options_mom_.pruning % dynare++ routines will be called in simult_.m, store some additional stuff
+        options_mom_.DynareRandomStreams.seed = options_mom_.mom.seed;
+    end
 end
 
 % -------------------------------------------------------------------------
@@ -680,6 +686,11 @@ if isfield(estim_params_,'param_vals') && ~isempty(estim_params_.param_vals)
         fprintf('This will override parameter values and may lead to wrong results.\n')
         fprintf('Check whether this is really intended.\n')
         warning('The steady state file internally changes the values of the estimated parameters.')
+        if strcmp(options_mom_.mom.mom_method,'GMM') && options_mom_.mom.analytic_standard_errors
+            fprintf('For analytical standard errors, the parameter-Jacobians of the dynamic model and of the steady-state will be computed numerically\n'),
+            fprintf('(re-set options_mom_.analytic_derivation_mode= -2)'),
+            options_mom_.analytic_derivation_mode= -2;
+        end
     end
 end
 
@@ -729,11 +740,6 @@ catch last_error% if check fails, provide info on using calibration if present
     rethrow(last_error);
 end
 
-if options_mom_.mode_compute == 0 %We only report value of moments distance at initial value of the parameters
-    fprintf('No minimization of moments distance due to ''mode_compute=0''\n')
-    return
-end
-
 % -------------------------------------------------------------------------
 % Step 7a: Method of moments estimation: print some info
 % -------------------------------------------------------------------------
@@ -751,34 +757,69 @@ end
 if options_mom_.mom.penalized_estimator
     fprintf('\n  - penalized estimation using deviation from prior mean and weighted with prior precision');
 end
-if     options_mom_.mode_compute ==   1; fprintf('\n  - optimizer (mode_compute=1): fmincon');
-elseif options_mom_.mode_compute ==   2; fprintf('\n  - optimizer (mode_compute=2): continuous simulated annealing');
-elseif options_mom_.mode_compute ==   3; fprintf('\n  - optimizer (mode_compute=3): fminunc');
-elseif options_mom_.mode_compute ==   4; fprintf('\n  - optimizer (mode_compute=4): csminwel');
-elseif options_mom_.mode_compute ==   5; fprintf('\n  - optimizer (mode_compute=5): newrat');
-elseif options_mom_.mode_compute ==   6; fprintf('\n  - optimizer (mode_compute=6): gmhmaxlik');
-elseif options_mom_.mode_compute ==   7; fprintf('\n  - optimizer (mode_compute=7): fminsearch');
-elseif options_mom_.mode_compute ==   8; fprintf('\n  - optimizer (mode_compute=8): Dynare Nelder-Mead simplex');
-elseif options_mom_.mode_compute ==   9; fprintf('\n  - optimizer (mode_compute=9): CMA-ES');
-elseif options_mom_.mode_compute ==  10; fprintf('\n  - optimizer (mode_compute=10): simpsa');
-elseif options_mom_.mode_compute ==  11; fprintf('\n  - optimizer (mode_compute=11): online_auxiliary_filter');
-elseif options_mom_.mode_compute ==  12; fprintf('\n  - optimizer (mode_compute=12): particleswarm');
-elseif options_mom_.mode_compute == 101; fprintf('\n  - optimizer (mode_compute=101): SolveOpt');
-elseif options_mom_.mode_compute == 102; fprintf('\n  - optimizer (mode_compute=102): simulannealbnd');
-elseif options_mom_.mode_compute ==  13; fprintf('\n  - optimizer (mode_compute=13): lsqnonlin');
-elseif ischar(minimizer_algorithm); fprintf(['\n  - user-defined optimizer: ' minimizer_algorithm]);
-else
-    error('method_of_moments: Unknown optimizer, please contact the developers ')
-end
-if options_mom_.silent_optimizer
-    fprintf(' (silent)');
+optimizer_vec=[options_mom_.mode_compute;num2cell(options_mom_.additional_optimizer_steps)]; % at each stage one can possibly use different optimizers sequentially
+for i = 1:length(optimizer_vec)
+    if i == 1
+        str = '- optimizer (mode_compute';
+    else
+        str = '            (additional_optimizer_steps';
+    end
+    switch optimizer_vec{i}
+        case 0
+            fprintf('\n  %s=0): no minimization',str);
+        case 1
+            fprintf('\n  %s=1): fmincon',str);
+        case 2
+            fprintf('\n  %s=2): continuous simulated annealing',str);
+        case 3
+            fprintf('\n  %s=3): fminunc',str);
+        case 4
+            fprintf('\n  %s=4): csminwel',str);
+        case 5
+            fprintf('\n  %s=5): newrat',str);
+        case 6
+            fprintf('\n  %s=6): gmhmaxlik',str);
+        case 7
+            fprintf('\n  %s=7): fminsearch',str);
+        case 8
+            fprintf('\n  %s=8): Dynare Nelder-Mead simplex',str);
+        case 9
+            fprintf('\n  %s=9): CMA-ES',str);
+        case 10
+            fprintf('\n  %s=10): simpsa',str);
+        case 11
+            fprintf('\n  %s=11): online_auxiliary_filter',str);
+        case 12
+            fprintf('\n  %s=12): particleswarm',str);
+        case 101
+            fprintf('\n  %s=101): SolveOpt',str);
+        case 102
+            fprintf('\n  %s=102): simulannealbnd',str);
+        case 13
+            fprintf('\n  %s=13): lsqnonlin',str);
+        otherwise
+            if ischar(optimizer_vec{i})
+                fprintf('\n  %s=%s): user-defined',str,optimizer_vec{i});
+            else
+                error('method_of_moments: Unknown optimizer, please contact the developers ')
+            end
+    end
+    if options_mom_.silent_optimizer
+        fprintf(' (silent)');
+    end
 end
 fprintf('\n  - perturbation order:        %d', options_mom_.order)
 if options_mom_.order > 1 && options_mom_.pruning
     fprintf(' (with pruning)')
 end
+if strcmp(options_mom_.mom.mom_method,'GMM') && options_mom_.mom.analytic_standard_errors
+    fprintf('\n  - standard errors:           analytic derivatives');
+else
+    fprintf('\n  - standard errors:           numerical derivatives');
+end
 fprintf('\n  - number of matched moments: %d', options_mom_.mom.mom_nbr);
-fprintf('\n  - number of parameters:      %d\n\n', length(xparam0));
+fprintf('\n  - number of parameters:      %d', length(xparam0));
+fprintf('\n\n');
 
 % -------------------------------------------------------------------------
 % Step 7b: Iterated method of moments estimation
@@ -787,8 +828,6 @@ if size(options_mom_.mom.weighting_matrix,1)>1 && ~(any(strcmpi('diagonal',optio
     fprintf('\nYou did not specify the use of an optimal or diagonal weighting matrix. There is no point in running an iterated method of moments.\n')
 end
 
-optimizer_vec=[options_mom_.mode_compute,options_mom_.additional_optimizer_steps]; % at each stage one can possibly use different optimizers sequentially
-
 for stage_iter=1:size(options_mom_.mom.weighting_matrix,1)
     fprintf('Estimation stage %u\n',stage_iter);
     Woptflag = false;
@@ -834,15 +873,20 @@ for stage_iter=1:size(options_mom_.mom.weighting_matrix,1)
     end
 
     for optim_iter= 1:length(optimizer_vec)
-        if optimizer_vec(optim_iter)==13
-            options_mom_.vector_output = true;
+        if optimizer_vec{optim_iter}==0
+            xparam1=xparam0; %no minimization, evaluate objective at current values
+            fval = feval(objective_function, xparam1, Bounds, oo_, estim_params_, M_, options_mom_);
         else
-            options_mom_.vector_output = false;
-        end
-        [xparam1, fval, exitflag] = dynare_minimize_objective(objective_function, xparam0, optimizer_vec(optim_iter), options_mom_, [Bounds.lb Bounds.ub], bayestopt_laplace.name, bayestopt_laplace, [],...
-                                                              Bounds, oo_, estim_params_, M_, options_mom_);
-        if options_mom_.vector_output
-            fval = fval'*fval;
+            if optimizer_vec{optim_iter}==13
+                options_mom_.vector_output = true;
+            else
+                options_mom_.vector_output = false;
+            end
+            [xparam1, fval, exitflag] = dynare_minimize_objective(objective_function, xparam0, optimizer_vec{optim_iter}, options_mom_, [Bounds.lb Bounds.ub], bayestopt_laplace.name, bayestopt_laplace, [],...
+                                                                  Bounds, oo_, estim_params_, M_, options_mom_);
+            if options_mom_.vector_output
+                fval = fval'*fval;
+            end
         end
         fprintf('\nStage %d Iteration %d: value of minimized moment distance objective function: %12.10f.\n',stage_iter,optim_iter,fval)
         if options_mom_.mom.verbose
@@ -853,8 +897,12 @@ for stage_iter=1:size(options_mom_.mom.weighting_matrix,1)
     options_mom_.vector_output = false;    
     % Update M_ and DynareResults (in particular to get oo_.mom.model_moments)    
     M_ = set_all_parameters(xparam1,estim_params_,M_);
+    if strcmp(options_mom_.mom.mom_method,'GMM') && options_mom_.mom.analytic_standard_errors
+        options_mom_.mom.compute_derivs = true; % for GMM we compute derivatives analytically in the objective function with this flag        
+    end
     [fval, ~, ~,~,~, oo_] = feval(objective_function, xparam1, Bounds, oo_, estim_params_, M_, options_mom_);
-    % Compute Standard errors
+    options_mom_.mom.compute_derivs = false; % reset to not compute derivatives in objective function during optimization
+    
     SE = method_of_moments_standard_errors(xparam1, objective_function, Bounds, oo_, estim_params_, M_, options_mom_, Woptflag);
     
     % Store results in output structure
@@ -901,7 +949,7 @@ if options_mom_.TeX
 end
 
 if options_mom_.mode_check.status
-    method_of_moments_mode_check(objective_function,xparam1,SE,options_mom_,M_,estim_params_,Bounds,bayestopt_laplace,...
+    method_of_moments_check_plot(objective_function,xparam1,SE,options_mom_,M_,estim_params_,Bounds,bayestopt_laplace,...
         Bounds, oo_, estim_params_, M_, options_mom_)
 end
 
diff --git a/matlab/method_of_moments/method_of_moments_mode_check.m b/matlab/method_of_moments/method_of_moments_check_plot.m
similarity index 86%
rename from matlab/method_of_moments/method_of_moments_mode_check.m
rename to matlab/method_of_moments/method_of_moments_check_plot.m
index 1df8af84f11105a0431bd222d5c70a0662539b4e..ceb1a15b75d988eb32c5835840afb9e7fa841cca 100644
--- a/matlab/method_of_moments/method_of_moments_mode_check.m
+++ b/matlab/method_of_moments/method_of_moments_check_plot.m
@@ -1,8 +1,8 @@
-function method_of_moments_mode_check(fun,xparam,SE_vec,options_,M_,estim_params_,Bounds,bayestopt_,varargin)
-% Checks the estimated ML mode or Posterior mode.
+function method_of_moments_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 (C) 2020 Dynare Team
+% Copyright (C) 2020-2021 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -28,7 +28,7 @@ fval = feval(fun,xparam,varargin{:});
 
 if ~isempty(SE_vec)
     skipline()
-    disp('MODE CHECK')
+    disp('LOCAL MINIMUM CHECK')
     skipline()
     fprintf('Fval obtained by the minimization routine: %f', fval);
     skipline()
@@ -39,12 +39,12 @@ end
 
 [nbplt,nr,nc,lr,lc,nstar] = pltorg(length(xparam));
 
-if ~exist([M_.fname filesep 'graphs'],'dir')
-    mkdir(M_.fname,'graphs');
+if ~exist([M_.dname filesep 'graphs'],'dir')
+    mkdir(M_.dname,'graphs');
 end
 if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
-    fidTeX = fopen([M_.fname, '/graphs/', M_.fname '_MoMCheckPlots.tex'],'w');
-    fprintf(fidTeX,'%% TeX eps-loader file generated by method_of_moments_mode_check.m (Dynare).\n');
+    fidTeX = fopen([M_.dname, '/graphs/', M_.fname '_MoMCheckPlots.tex'],'w');
+    fprintf(fidTeX,'%% TeX eps-loader file generated by method_of_moments_check_plot.m (Dynare).\n');
     fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
     fprintf(fidTeX,' \n');
 end
@@ -54,14 +54,14 @@ if isinf(ll)
     options_.mode_check.symmetric_plots = false;
 end
 
-mcheck = struct('cross',struct(),'emode',struct());
+mcheck = struct('cross',struct(),'emin',struct());
 
 for plt = 1:nbplt
     if TeX
         NAMES = [];
         TeXNAMES = [];
     end
-    hh = dyn_figure(options_.nodisplay,'Name','Mode check plots');
+    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;
@@ -119,7 +119,7 @@ for plt = 1:nbplt
             else
                 y(i,1) = NaN;
                 if options_.debug
-                    fprintf('mode_check:: could not solve model for parameter %s at value %4.3f, error code: %u\n',name,z(i),info(1))
+                    fprintf('method_of_moments_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
@@ -127,9 +127,9 @@ for plt = 1:nbplt
                 y(i,2)  = (y(i,1)+prior-dy);
             end
         end
-        mcheck.cross = setfield(mcheck.cross, name, [transpose(z), -y]);
-        mcheck.emode = setfield(mcheck.emode, name, xparam(kk));
-        fighandle=plot(z,-y);
+        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)
@@ -165,12 +165,12 @@ for plt = 1:nbplt
         text(0.25,0.5,'log-post')
         text(0.69,0.5,'log-lik kernel')
     end
-    dyn_saveas(hh,[M_.fname, '/graphs/', M_.fname '_MoMCheckPlots' int2str(plt) ],options_.nodisplay,options_.graph_format);
+    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]{%_MoMCheckPlots%s}\n',options_.figures.textwidth*min(k/nc,1),[M_.fname, '/graphs/',M_.fname],int2str(plt));
+        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');
@@ -181,5 +181,4 @@ if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
     fclose(fidTeX);
 end
 
-OutputDirectoryName = CheckPath('modecheck',M_.dname);
-save([OutputDirectoryName '/MoM_check_plot_data.mat'],'mcheck');
+save([M_.dname filesep 'graphs' filesep M_.fname '_MoMCheckPlots_data.mat'],'mcheck');
diff --git a/matlab/method_of_moments/method_of_moments_data_moments.m b/matlab/method_of_moments/method_of_moments_data_moments.m
index 38d205a272f7e6155e52b81e4c9aa3c7a067a24d..26bf7a4dcd9b63da55e189ca312b59903ad0aa53 100644
--- a/matlab/method_of_moments/method_of_moments_data_moments.m
+++ b/matlab/method_of_moments/method_of_moments_data_moments.m
@@ -16,7 +16,7 @@ function [dataMoments, m_data] = method_of_moments_data_moments(data, oo_, match
 %  o method_of_moments.m
 %  o method_of_moments_objective_function.m
 % =========================================================================
-% Copyright (C) 2020 Dynare Team
+% Copyright (C) 2020-2021 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -59,7 +59,11 @@ for jm = 1:options_mom_.mom.mom_nbr
         end
     end
     % We replace NaN (due to leads and lags and missing values) with the corresponding mean
-    dataMoments(jm,1) = mean(m_data_tmp,'omitnan');
+    if isoctave
+        dataMoments(jm,1) = nanmean(m_data_tmp);
+    else
+        dataMoments(jm,1) = mean(m_data_tmp,'omitnan');
+    end
     m_data_tmp(isnan(m_data_tmp)) = dataMoments(jm,1);
     m_data(:,jm) = m_data_tmp;
 end
diff --git a/matlab/method_of_moments/method_of_moments_objective_function.m b/matlab/method_of_moments/method_of_moments_objective_function.m
index 8a15ed749b2cf74bc2a351f23d0350f7182294ee..745f8570e13bda062f73fcb874abdd8c7bede040 100644
--- a/matlab/method_of_moments/method_of_moments_objective_function.m
+++ b/matlab/method_of_moments/method_of_moments_objective_function.m
@@ -31,7 +31,7 @@ function [fval, info, exit_flag, junk1, junk2, oo_, M_, options_mom_] = method_o
 %  o resol
 %  o set_all_parameters
 % =========================================================================
-% Copyright (C) 2020 Dynare Team
+% Copyright (C) 2020-2021 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -109,7 +109,32 @@ if strcmp(options_mom_.mom.mom_method,'GMM')
     %--------------------------------------------------------------------------
     % 3. Set up pruned state-space system and compute model moments
     %--------------------------------------------------------------------------
-    pruned_state_space = pruned_state_space_system(M_, options_mom_, dr, oo_.dr.obs_var, options_mom_.ar, 0, 0);
+    if options_mom_.mom.compute_derivs && options_mom_.mom.analytic_standard_errors        
+        indpmodel = []; %initialize index for model parameters
+        if ~isempty(estim_params_.param_vals)
+            indpmodel = estim_params_.param_vals(:,1); %values correspond to parameters declaration order, row number corresponds to order in estimated_params
+        end
+        indpstderr=[]; %initialize index for stderr parameters
+        if ~isempty(estim_params_.var_exo)
+            indpstderr = estim_params_.var_exo(:,1); %values correspond to varexo declaration order, row number corresponds to order in estimated_params
+        end
+        indpcorr=[]; %initialize matrix for corr paramters
+        if ~isempty(estim_params_.corrx)
+            indpcorr = estim_params_.corrx(:,1:2); %values correspond to varexo declaration order, row number corresponds to order in estimated_params
+        end
+        if estim_params_.nvn || estim_params_.ncn %nvn is number of stderr parameters and ncn is number of corr parameters of measurement innovations as declared in estimated_params
+            error('Analytic computation of standard errrors does not (yet) support measurement errors.\nInstead, define them explicitly as varexo and provide measurement equations in the model definition.\nAlternatively, use numerical standard errors.')
+        end
+        modparam_nbr = estim_params_.np;        % number of model parameters as declared in estimated_params
+        stderrparam_nbr = estim_params_.nvx;    % number of stderr parameters
+        corrparam_nbr = estim_params_.ncx;      % number of corr parameters
+        totparam_nbr = stderrparam_nbr+corrparam_nbr+modparam_nbr;
+        dr.derivs = get_perturbation_params_derivs(M_, options_mom_, estim_params_, oo_, indpmodel, indpstderr, indpcorr, 0); %analytic derivatives of perturbation matrices
+        oo_.mom.model_moments_params_derivs = NaN(options_mom_.mom.mom_nbr,totparam_nbr);
+        pruned_state_space = pruned_state_space_system(M_, options_mom_, dr, oo_.dr.obs_var, options_mom_.ar, 0, 1);
+    else
+        pruned_state_space = pruned_state_space_system(M_, options_mom_, dr, oo_.dr.obs_var, options_mom_.ar, 0, 0);
+    end
     
     oo_.mom.model_moments = NaN(options_mom_.mom.mom_nbr,1);
     offset = 0;
@@ -118,6 +143,9 @@ if strcmp(options_mom_.mom.mom_method,'GMM')
         E_y = pruned_state_space.E_y;
         E_y_nbr = nnz(options_mom_.mom.index.E_y);
         oo_.mom.model_moments(offset+1:E_y_nbr,1) = E_y(options_mom_.mom.index.E_y);
+        if options_mom_.mom.compute_derivs && options_mom_.mom.analytic_standard_errors
+            oo_.mom.model_moments_params_derivs(offset+1:E_y_nbr,:) = pruned_state_space.dE_y(options_mom_.mom.index.E_y,:);
+        end
         offset = offset + E_y_nbr;
     end
     % Second moments
@@ -125,22 +153,47 @@ if strcmp(options_mom_.mom.mom_method,'GMM')
     if isfield(options_mom_.mom.index,'E_yy') && nnz(options_mom_.mom.index.E_yy) > 0
         if options_mom_.prefilter
             E_yy = pruned_state_space.Var_y;
+            if options_mom_.mom.compute_derivs && options_mom_.mom.analytic_standard_errors
+                dE_yy = pruned_state_space.dVar_y;
+            end            
         else
             E_yy = pruned_state_space.Var_y + pruned_state_space.E_y*pruned_state_space.E_y';
+            if options_mom_.mom.compute_derivs && options_mom_.mom.analytic_standard_errors
+                dE_yy = pruned_state_space.dVar_y;
+                for jp=1:totparam_nbr
+                    dE_yy(:,:,jp) = dE_yy(:,:,jp) + pruned_state_space.dE_y(:,jp)*pruned_state_space.E_y' + pruned_state_space.E_y*pruned_state_space.dE_y(:,jp)';
+                end
+            end
         end
         E_yy_nbr = nnz(tril(options_mom_.mom.index.E_yy));
         oo_.mom.model_moments(offset+(1:E_yy_nbr),1) = E_yy(tril(options_mom_.mom.index.E_yy));
+        if options_mom_.mom.compute_derivs && options_mom_.mom.analytic_standard_errors
+            oo_.mom.model_moments_params_derivs(offset+(1:E_yy_nbr),:) = reshape(dE_yy(repmat(tril(options_mom_.mom.index.E_yy),[1 1 totparam_nbr])),E_yy_nbr,totparam_nbr);
+        end
         offset = offset + E_yy_nbr;
     end
     % Lead/lags covariance
     if isfield(options_mom_.mom.index,'E_yyt') && nnz(options_mom_.mom.index.E_yyt) > 0
         if options_mom_.prefilter
             E_yyt = pruned_state_space.Var_yi;
+            if options_mom_.mom.compute_derivs && options_mom_.mom.analytic_standard_errors
+                dE_yyt = pruned_state_space.dVar_yi;
+            end
         else
             E_yyt = pruned_state_space.Var_yi + repmat(pruned_state_space.E_y*pruned_state_space.E_y',[1 1 size(pruned_state_space.Var_yi,3)]);
+            if options_mom_.mom.compute_derivs && options_mom_.mom.analytic_standard_errors
+                dE_yyt = pruned_state_space.dVar_yi;
+                for jp=1:totparam_nbr
+                    dE_yyt(:,:,:,jp) = dE_yyt(:,:,:,jp) + repmat(pruned_state_space.dE_y(:,jp)*pruned_state_space.E_y',[1 1 size(pruned_state_space.Var_yi,3)])...
+                                                        + repmat(pruned_state_space.E_y*pruned_state_space.dE_y(:,jp)',[1 1 size(pruned_state_space.Var_yi,3)]);
+                end
+            end
         end
         E_yyt_nbr = nnz(options_mom_.mom.index.E_yyt);
         oo_.mom.model_moments(offset+(1:E_yyt_nbr),1) = E_yyt(options_mom_.mom.index.E_yyt);
+        if options_mom_.mom.compute_derivs && options_mom_.mom.analytic_standard_errors
+            oo_.mom.model_moments_params_derivs(offset+(1:E_yyt_nbr),:) = reshape(dE_yyt(repmat(options_mom_.mom.index.E_yyt,[1 1 1 totparam_nbr])),E_yyt_nbr,totparam_nbr);
+        end
     end
 
 elseif strcmp(options_mom_.mom.mom_method,'SMM')
@@ -179,7 +232,7 @@ elseif strcmp(options_mom_.mom.mom_method,'SMM')
         i_ME = setdiff([1:size(M_.H,1)],find(diag(M_.H) == 0)); % find ME with 0 variance
         chol_S = chol(M_.H(i_ME,i_ME)); %decompose rest
         shock_mat=zeros(size(options_mom_.mom.ME_shock_series)); %initialize
-        shock_mat(:,i_ME)=options_mom_.mom.ME_shock_series(:,i_exo_var)*chol_S;
+        shock_mat(:,i_ME)=options_mom_.mom.ME_shock_series(:,i_ME)*chol_S;
         y_sim = y_sim+shock_mat;
     end
 
diff --git a/matlab/method_of_moments/method_of_moments_optimal_weighting_matrix.m b/matlab/method_of_moments/method_of_moments_optimal_weighting_matrix.m
index 7dde93568d45b011e081e63b615c5ffbcb9749be..ad2db20f7c0bb32db11d699452b3288dbb77dabf 100644
--- a/matlab/method_of_moments/method_of_moments_optimal_weighting_matrix.m
+++ b/matlab/method_of_moments/method_of_moments_optimal_weighting_matrix.m
@@ -19,7 +19,7 @@ function W_opt = method_of_moments_optimal_weighting_matrix(m_data, moments, q_l
 % This function calls:
 %  o CorrMatrix (embedded)
 % =========================================================================
-% Copyright (C) 2020 Dynare Team
+% Copyright (C) 2020-2021 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/method_of_moments/method_of_moments_standard_errors.m b/matlab/method_of_moments/method_of_moments_standard_errors.m
index 888ccf01f59e9650a5a3472c146d7254eaf67e8b..459f583f7aade842d0804353471da31f594c14ea 100644
--- a/matlab/method_of_moments/method_of_moments_standard_errors.m
+++ b/matlab/method_of_moments/method_of_moments_standard_errors.m
@@ -29,7 +29,7 @@ function [SE_values, Asympt_Var] = method_of_moments_standard_errors(xparam, obj
 %  o SMM_objective_function.m
 %  o method_of_moments_optimal_weighting_matrix  
 % =========================================================================
-% Copyright (C) 2020 Dynare Team
+% Copyright (C) 2020-2021 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -57,30 +57,46 @@ dim_params   = size(xparam,1);
 D            = zeros(num_mom,dim_params);
 eps_value    = options_mom_.mom.se_tolx;
 
-for i=1:dim_params
-    %Positive step
-    xparam_eps_p      = xparam;
-    xparam_eps_p(i,1) = xparam_eps_p(i) + eps_value;
-    [~, info_p, ~, ~,~, oo__p] = feval(objective_function, xparam_eps_p, Bounds, oo_, estim_params_, M_, options_mom_);
-    
-    % Negative step
-    xparam_eps_m      = xparam;
-    xparam_eps_m(i,1) = xparam_eps_m(i) - eps_value;
-    [~, info_m,  ~, ~,~, oo__m] = feval(objective_function, xparam_eps_m, Bounds, oo_, estim_params_, M_, options_mom_);
-
-    % The Jacobian:
-    if nnz(info_p)==0 && nnz(info_m)==0
-        D(:,i) = (oo__p.mom.model_moments - oo__m.mom.model_moments)/(2*eps_value);
-    else
-        problpar = get_the_name(i,options_mom_.TeX, M_, estim_params_, options_mom_);
-        message_p = get_error_message(info_p, options_mom_);
-        message_m = get_error_message(info_m, options_mom_);        
-        
-        warning('method_of_moments:info','Cannot compute the Jacobian for parameter %s - no standard errors available\n %s %s\nCheck your bounds and/or priors, or use a different optimizer.\n',problpar, message_p, message_m)
+if strcmp(options_mom_.mom.mom_method,'GMM') && options_mom_.mom.analytic_standard_errors
+    fprintf('\nComputing standard errors using analytical derivatives of moments\n');
+    D = oo_.mom.model_moments_params_derivs; %already computed in objective function via get_perturbation_params.m
+    idx_nan = find(any(isnan(D)));
+    if any(idx_nan)
+        for i = idx_nan            
+             fprintf('No standard errors available for parameter %s\n',get_the_name(i,options_mom_.TeX, M_, estim_params_, options_mom_))
+        end        
+        warning('There are NaN in the analytical Jacobian of Moments. Check your bounds and/or priors, or use a different optimizer.')
         Asympt_Var = NaN(length(xparam),length(xparam));
         SE_values = NaN(length(xparam),1);
         return
     end
+else    
+    fprintf('\nComputing standard errors using numerical derivatives of moments\n');
+    for i=1:dim_params
+        %Positive step
+        xparam_eps_p      = xparam;
+        xparam_eps_p(i,1) = xparam_eps_p(i) + eps_value;
+        [~, info_p, ~, ~,~, oo__p] = feval(objective_function, xparam_eps_p, Bounds, oo_, estim_params_, M_, options_mom_);
+
+        % Negative step
+        xparam_eps_m      = xparam;
+        xparam_eps_m(i,1) = xparam_eps_m(i) - eps_value;
+        [~, info_m,  ~, ~,~, oo__m] = feval(objective_function, xparam_eps_m, Bounds, oo_, estim_params_, M_, options_mom_);
+
+        % The Jacobian:
+        if nnz(info_p)==0 && nnz(info_m)==0
+            D(:,i) = (oo__p.mom.model_moments - oo__m.mom.model_moments)/(2*eps_value);
+        else
+            problpar = get_the_name(i,options_mom_.TeX, M_, estim_params_, options_mom_);
+            message_p = get_error_message(info_p, options_mom_);
+            message_m = get_error_message(info_m, options_mom_);        
+
+            warning('method_of_moments:info','Cannot compute the Jacobian for parameter %s - no standard errors available\n %s %s\nCheck your bounds and/or priors, or use a different optimizer.\n',problpar, message_p, message_m)
+            Asympt_Var = NaN(length(xparam),length(xparam));
+            SE_values = NaN(length(xparam),1);
+            return
+        end
+    end
 end
 
 T = options_mom_.nobs; %Number of observations
diff --git a/matlab/mh_autocorrelation_function.m b/matlab/mh_autocorrelation_function.m
index 377de19786043a2d0f8e0312b8ea6e713f13473f..6312a32629fac869f47cad35676893b005a69b42 100644
--- a/matlab/mh_autocorrelation_function.m
+++ b/matlab/mh_autocorrelation_function.m
@@ -95,13 +95,13 @@ hh=dyn_figure(options_.nodisplay,'Name',FigureName);
 
 bar(0:options_.mh_autocorrelation_function_size,autocor,'k');
 axis tight
-% create subdirectory <fname>/graphs if it doesn't exist
-if ~exist(M_.fname, 'dir')
-    mkdir('.',M_.fname);
+% create subdirectory <dname>/graphs if it doesn't exist
+if ~exist(M_.dname, 'dir')
+    mkdir('.',M_.dname);
 end
-if ~exist([M_.fname filesep 'graphs'])
-    mkdir(M_.fname,'graphs');
+if ~exist([M_.dname filesep 'graphs'])
+    mkdir(M_.dname,'graphs');
 end
 
 plot_name=get_the_name(column,0,M_,estim_params_,options_);
-dyn_saveas(hh,[M_.fname, filesep, 'graphs', filesep, 'MH_Autocorrelation_' plot_name],options_.nodisplay,options_.graph_format)
+dyn_saveas(hh,[M_.dname, filesep, 'graphs', filesep, 'MH_Autocorrelation_' plot_name],options_.nodisplay,options_.graph_format)
diff --git a/matlab/missing/mex/mjdgges/mjdgges.m b/matlab/missing/mex/mjdgges/mjdgges.m
index 11d51d62f7709821b04a1a70fcd3fca381e6b262..a2555f2c7ef80dd38e7e42fcd3c6a01780e87958 100644
--- a/matlab/missing/mex/mjdgges/mjdgges.m
+++ b/matlab/missing/mex/mjdgges/mjdgges.m
@@ -1,4 +1,4 @@
-function [ss, tt, zz, sdim, eigval, info] = mjdgges(e, d, qz_criterium, zhreshold)
+function [ss, tt, zz, sdim, eigval, info] = mjdgges(e, d, qz_criterium, zhreshold) % --*-- Unitary tests --*--
 %
 % INPUTS
 %   e            [double] real square (n*n) matrix.
@@ -65,3 +65,19 @@ try
 catch
     info = 1; % Not as precise as lapack's info!
 end
+
+%@test:1
+%$ try
+%$     E =[0,0,0,0,0,0,0,-1,0,0;0,0,0,0,0,0,0,0,-1,0;0,0,0,0,0,0,0,0,0,-0.990099009900990;0,0,0,0,0,0,0,0,0,0.0990099009900990;0,0,0,-1.01010101010101,0,0.0427672955974843,0,0,0,0;0,0,0,0,0,0.128301886792453,-1,0,0,0;0.800000000000000,0,0,0,0,0,0,0,0,0;0,1,0,0,0,0,1,0,0,0;0,0,0.900000000000000,0,0,0,0,0,0,0;0,0,0,-1.01010101010101,-1,0,2,0,-1,0];
+%$     D=[0,0,0,0,-1,0,0,-0.792000000000000,0,0;0,0,0,0,0,0,0,0,-0.990000000000000,0;0,0,0,-0.000493818030899887,0,0,0,0,0,-0.882178217821782;0,0,0,-1.00493818030900,0,0,0,0,0,0.0882178217821782;0,0,0,-1,0.128301886792453,0,0,0,0,0;-1,0,0,0,0,0,-0.990000000000000,0,0,0;1,0,0,0,0,0,0,0,0,0;0,1,0,0,0,0,0,0,0,0;0,0,1,0,0,0,0,0,0,0;0,0,0,0,-1,0,0,0,0,0];
+%$     [ss, tt, w, sdim, dr.eigval, info1]=mjdgges(E, D, 1.000001, 1e-06);
+%$     if sdim==5
+%$         t(1) = 1;
+%$     else 
+%$         t(1) = 0;
+%$     end
+%$ catch
+%$     t(1) = 0;
+%$ end
+%$ T = all(t);
+%@eof:1
\ No newline at end of file
diff --git a/matlab/missing/mex/num_procs/num_procs.m b/matlab/missing/mex/num_procs/num_procs.m
new file mode 100644
index 0000000000000000000000000000000000000000..832841c83f352c168e708e8a028e9b5a8f807729
--- /dev/null
+++ b/matlab/missing/mex/num_procs/num_procs.m
@@ -0,0 +1,29 @@
+function num_logical_cores=num_procs
+% function num_logical_cores=num_procs
+% Dummy function providing fake number of cores as m-file do not use
+% this functionality
+%
+% OUTPUTS
+%    num_logical_cores    [double]     number of logical cores
+%
+% SPECIAL REQUIREMENTS
+%    none
+
+% Copyright (C) 2020 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 <http://www.gnu.org/licenses/>.
+
+num_logical_cores=1;
\ No newline at end of file
diff --git a/matlab/mode_check.m b/matlab/mode_check.m
index ada266663ab826cee03b1923e9517abf65f78d62..17a119f7d85d55e42244b38753065d770172bf3a 100644
--- a/matlab/mode_check.m
+++ b/matlab/mode_check.m
@@ -77,11 +77,11 @@ end
 
 [nbplt,nr,nc,lr,lc,nstar] = pltorg(length(x));
 
-if ~exist([Model.fname filesep 'graphs'],'dir')
-    mkdir(Model.fname,'graphs');
+if ~exist([Model.dname filesep 'graphs'],'dir')
+    mkdir(Model.dname,'graphs');
 end
 if TeX && any(strcmp('eps',cellstr(DynareOptions.graph_format)))
-    fidTeX = fopen([Model.fname, '/graphs/', Model.fname '_CheckPlots.tex'],'w');
+    fidTeX = fopen([Model.dname, '/graphs/', Model.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');
@@ -201,12 +201,12 @@ for plt = 1:nbplt
         text(0.25,0.5,'log-post')
         text(0.69,0.5,'log-lik kernel')
     end
-    dyn_saveas(hh,[Model.fname, '/graphs/', Model.fname '_CheckPlots' int2str(plt) ],DynareOptions.nodisplay,DynareOptions.graph_format);
+    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)))
         % 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.fname, '/graphs/',Model.fname],int2str(plt));
+        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,'\\caption{Check plots.}');
         fprintf(fidTeX,'\\label{Fig:CheckPlots:%s}\n',int2str(plt));
         fprintf(fidTeX,'\\end{figure}\n');
diff --git a/matlab/modules/reporting b/matlab/modules/reporting
index 13c98b256d8d42f62692aa9d48d379e897f2ca5e..57a4d6679636e0caa4f98e5a82fb4e33781643b4 160000
--- a/matlab/modules/reporting
+++ b/matlab/modules/reporting
@@ -1 +1 @@
-Subproject commit 13c98b256d8d42f62692aa9d48d379e897f2ca5e
+Subproject commit 57a4d6679636e0caa4f98e5a82fb4e33781643b4
diff --git a/matlab/ms-sbvar/ms_write_markov_file.m b/matlab/ms-sbvar/ms_write_markov_file.m
index 7eaa5925fd98e2cb93582138c8af537afae7810a..ec6507fd6f21c9195e821ec1f6570089e657b805 100644
--- a/matlab/ms-sbvar/ms_write_markov_file.m
+++ b/matlab/ms-sbvar/ms_write_markov_file.m
@@ -52,6 +52,10 @@ for i_chain = 1:n_chains
     %//=====================================================//
     fprintf(fh,'//== Number of states for state_variable[%d] ==//\n', ...
             i_chain);
+    if ~isfield(options.ms.ms_chain(i_chain),'regime') ...
+                || isempty(options.ms.ms_chain(i_chain).regime)
+        error('Chain %u does not feature any regime states. Did you forget to specify them?',i_chain)
+    end
     n_states = length(options.ms.ms_chain(i_chain).regime);
     fprintf(fh,'%d\n\n',n_states);
 
diff --git a/matlab/non_linear_dsge_likelihood.m b/matlab/non_linear_dsge_likelihood.m
index 2af54fac8eaf9b558b37cd55fa72eb5e0a756770..6206ca11e5ff38489dc72a15b8b21846624ce33a 100644
--- a/matlab/non_linear_dsge_likelihood.m
+++ b/matlab/non_linear_dsge_likelihood.m
@@ -135,14 +135,16 @@ end
 switch DynareOptions.particle.initialization
   case 1% Initial state vector covariance is the ergodic variance associated to the first order Taylor-approximation of the model.
     StateVectorMean = ReducedForm.constant(mf0);
-    StateVectorVariance = lyapunov_symm(dr.ghx(mf0,:), dr.ghu(mf0,:)*Q*dr.ghu(mf0,:)', DynareOptions.lyapunov_fixed_point_tol, ...
+    [A,B] = kalman_transition_matrix(dr,dr.restrict_var_list,dr.restrict_columns,Model.exo_nbr);
+    StateVectorVariance = lyapunov_symm(A, B*Q*B', DynareOptions.lyapunov_fixed_point_tol, ...
                                         DynareOptions.qz_criterium, DynareOptions.lyapunov_complex_threshold, [], DynareOptions.debug);
+    StateVectorVariance = StateVectorVariance(mf0,mf0);
   case 2% Initial state vector covariance is a monte-carlo based estimate of the ergodic variance (consistent with a k-order Taylor-approximation of the model).
     StateVectorMean = ReducedForm.constant(mf0);
     old_DynareOptionsperiods = DynareOptions.periods;
     DynareOptions.periods = 5000;
     y_ = simult(DynareResults.steady_state, dr,Model,DynareOptions,DynareResults);
-    y_ = y_(state_variables_idx,2001:5000);
+    y_ = y_(dr.order_var(state_variables_idx),2001:5000); %state_variables_idx is in dr-order while simult_ is in declaration order
     StateVectorVariance = cov(y_');
     DynareOptions.periods = old_DynareOptionsperiods;
     clear('old_DynareOptionsperiods','y_');
diff --git a/matlab/occbin/call_solve_one_constraint.m b/matlab/occbin/call_solve_one_constraint.m
deleted file mode 100644
index f0caa00e2260d7e24843fc1751c82706a6cd3667..0000000000000000000000000000000000000000
--- a/matlab/occbin/call_solve_one_constraint.m
+++ /dev/null
@@ -1,21 +0,0 @@
-% Solve model, generate model IRFs
-[zdatalinear, zdatapiecewise, zdatass, oobase_, Mbase_ ] = ...
-    solve_one_constraint(modnam,modnamstar,...
-                         constraint, constraint_relax,...
-                         shockssequence,irfshock,nperiods,maxiter);
-
-
-
-% unpack the IRFs
-for i=1:Mbase_.endo_nbr
-    eval([Mbase_.endo_names{i}, '_uncdifference=zdatalinear(:,i);']);
-    eval([Mbase_.endo_names{i}, '_difference=zdatapiecewise(:,i);']);
-    eval([Mbase_.endo_names{i}, '_ss=zdatass(i);']);
-end
-
-
-nparams = length(Mbase_.param_names);
-
-for i = 1:nparams
-    eval([Mbase_.param_names{i}, '= Mbase_.params(i);']);
-end
diff --git a/matlab/occbin/call_solve_two_constraints.m b/matlab/occbin/call_solve_two_constraints.m
deleted file mode 100644
index 96a960989f9fb1ed3e110a668832a1afae2c4a5c..0000000000000000000000000000000000000000
--- a/matlab/occbin/call_solve_two_constraints.m
+++ /dev/null
@@ -1,21 +0,0 @@
-[zdatalinear, zdatapiecewise, zdatass, oobase_, Mbase_] = solve_two_constraints(...
-    modnam_00,modnam_10,modnam_01,modnam_11,...
-    constraint1, constraint2,...
-    constraint_relax1, constraint_relax2,...
-    scalefactormod,irfshock,nperiods,curb_retrench,maxiter);
-
-
-for i=1:Mbase_.endo_nbr
-    eval([Mbase_.endo_names{i}, '_uncdifference=zdatalinear(:,i);']);
-    eval([Mbase_.endo_names{i}, '_difference=zdatapiecewise(:,i);']);
-    eval([Mbase_.endo_names{i}, '_ss=zdatass(i);']);
-end
-
-constraint1_difference = process_constraint(constraint1, '_difference', Mbase_.endo_names,0);
-constraint2_difference = process_constraint(constraint2, '_difference', Mbase_.endo_names,0);
-
-nparams = length(Mbase_.param_names);
-
-for i = 1:nparams
-    eval([Mbase_.param_names{i}, '= Mbase_.params(i);']);
-end
diff --git a/matlab/occbin/evaluate_model.m b/matlab/occbin/evaluate_model.m
deleted file mode 100644
index d5c6685f5a04f759b9081837e9a08377ec814908..0000000000000000000000000000000000000000
--- a/matlab/occbin/evaluate_model.m
+++ /dev/null
@@ -1,19 +0,0 @@
-function [r,g1,g2,g3] = evaluate_model(z,x,M,ss)
-
-ll = M.lead_lag_incidence';
-y = z(find(ll(:)));
-
-switch nargout
-  case 1
-    r = feval([M.fname '.dynamic'],y,x, ...
-              M.params, ss, 1);
-  case 2
-    [r,g1] = feval([M.fname '.dynamic'],y,x, ...
-                   M.params, ss, 1);
-  case 3
-    [r,g1,g2] = feval([M.fname '.dynamic'],y,x, ...
-                      M.params, ss, 1);
-  case 4
-    [r,g1,g2,g3] = feval([M.fname '.dynamic'],y,x, ...
-                         M.params, ss, 1);
-end
\ No newline at end of file
diff --git a/matlab/occbin/get_coef.m b/matlab/occbin/get_coef.m
deleted file mode 100644
index 138198259aee4377c86067d99fa28c9970beda0a..0000000000000000000000000000000000000000
--- a/matlab/occbin/get_coef.m
+++ /dev/null
@@ -1,26 +0,0 @@
-function [coef_y,coef_u] = get_coef(jacobian,M)
-
-ll = M.lead_lag_incidence;
-endo_nbr = M.endo_nbr;
-coef_y = zeros(endo_nbr,3*endo_nbr);
-coef_u = zeros(endo_nbr,M.exo_nbr);
-
-if M.maximum_lag > 0
-    [~,c1,c2] = find(ll(1,:));
-    coef_y(:,c1) = jacobian(:,c2);
-    [~,c1,c2] = find(ll(2,:));
-    coef_y(:,c1+endo_nbr) = jacobian(:,c2);
-    if M.maximum_lead > 0
-        [~,c1,c2] = find(ll(3,:));
-        coef_y(:,c1+2*endo_nbr) = jacobian(:,c2);
-    end
-else
-    [~,c1,c2] = find(ll(1,:));
-    coef_y(:,c1+endo_nbr) = jacobian(:,c2);
-    if M.maximum_lead > 0
-        [~,c1,c2] = find(ll(2,:));
-        coef_y(:,c1+2*endo_nbr) = jacobian(:,c2);
-    end
-end
-
-coef_u = jacobian(:,max(ll(end,:))+1:end);
\ No newline at end of file
diff --git a/matlab/occbin/get_complementarity_conditions.m b/matlab/occbin/get_complementarity_conditions.m
deleted file mode 100644
index f49ae2497c333882338f70d39698a62926031af1..0000000000000000000000000000000000000000
--- a/matlab/occbin/get_complementarity_conditions.m
+++ /dev/null
@@ -1,71 +0,0 @@
-function [lb,ub,eq_index] = get_complementarity_conditions(M,ramsey_policy)
-
-% Copyright (C) 2014-2018 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 <http://www.gnu.org/licenses/>.
-
-ub = inf(M.endo_nbr,1);
-lb = -ub;
-eq_index = (1:M.endo_nbr)';
-if ramsey_policy
-    if isfield(M,'ramsey_model_constraints')
-        rc = M.ramsey_model_constraints;
-        for i = 1:length(rc)
-            switch rc{i}{2}
-              case {'>','>='}
-                lb(rc{i}{1}) = eval(rc{i}{3});
-              case {'<','<='}
-                ub(rc{i}{1}) = eval(rc{i}{3});
-              otherwise
-                error('Wrong operator in get_complementarity_conditions')
-            end
-            eq_index(i) = 1;
-        end
-    end
-end
-
-etags = M.equations_tags;
-for i=1:size(etags,1)
-    if strcmp(etags{i,2},'mcp')
-        str = etags{i,3};
-        kop = strfind(etags{i,3},'<');
-        if ~isempty(kop)
-            k = find(strcmp(strtrim(str(1:kop-1)), M.endo_names));
-            if isempty(k)
-                error(sprintf(['Complementarity condition %s: variable %s is ' ...
-                               'not recognized',etags{i,3},b{1}]))
-            end
-            ub(k) = str2num(str(kop+1:end));
-            eq_index(etags{i,1}) = k;
-            eq_index(k) = etags{i,1};
-        else
-            kop = strfind(etags{i,3},'>');
-            if ~isempty(kop)
-                k = find(strcmp(strtrim(str(1:kop-1)), M.endo_names));
-                if isempty(k)
-                    error(sprintf(['Complementarity condition %s: variable %s is ' ...
-                                   'not recognized',etags{i},b{1}]))
-                end
-                lb(k) = str2num(str(kop+1:end));
-                eq_index(etags{i,1}) = k;
-                eq_index(k) = etags{i,1};
-            else
-                error(sprintf(['Complementarity condition %s can''t be ' ...
-                               'parsed'],etags{i,3}))
-            end
-        end
-    end
-end
diff --git a/matlab/occbin/get_deriv.m b/matlab/occbin/get_deriv.m
deleted file mode 100644
index 1b671c28bafdde347f761a5644cd757e6ede0dc0..0000000000000000000000000000000000000000
--- a/matlab/occbin/get_deriv.m
+++ /dev/null
@@ -1,82 +0,0 @@
-function [hm1,h,hl1,j,resid] = get_deriv(M_,ys_)
-
-iy_ = M_.lead_lag_incidence;
-it_ = 1;
-
-x = zeros(1,M_.exo_nbr);
-
-% For most models, there are leads, lags and current values of variables
-if size(iy_,1)==3
-    % find non-zero columns of hm1
-    lag_cols = find(iy_(1,:)~=0);
-    % find non-zero columns of h
-    con_cols = find(iy_(2,:));
-    % find non-zero columns of hl1
-    lea_cols = find(iy_(3,:));
-
-    % If models either lacks leads or lags, iy_ will have two rows
-    % In this case, we guess that the row with more nonzeros is the row with current variables
-elseif size(iy_,1)==2
-    % if first row has more nonzero entries than the second, assume model lacks lagged variables
-    if length(find(iy_(1,:)))>length(find(iy_(2,:)))
-        warning('Model does not have lagged endogenous variables')
-        con_cols = find(iy_(1,:));
-        lea_cols = find(iy_(2,:));
-        lag_cols = [];
-    else
-        warning('Model does not have expected future endogenous variables')
-        lag_cols = find(iy_(1,:));
-        con_cols = find(iy_(2,:));
-        lea_cols = [];
-    end
-
-end
-
-
-
-% find number of entries for y vector
-ny = length(find(iy_~=0));
-
-% build steady state y
-y = ys_(lag_cols);
-y = [y;ys_(con_cols)];
-y = [y;ys_(lea_cols)];
-
-
-if ismac
-    eval(['[resid,g1]=',M_.fname,'.dynamic(y,x, M_.params, ys_, it_);']);
-    % Older versions of DYNARE for Mac did not include ys_ in the call structure
-    %eval(['[resid,g1]=',M_.fname,'.dynamic(y,x, M_.params, it_);']);
-else
-    eval(['[resid,g1]=',M_.fname,'.dynamic(y,x, M_.params, ys_, it_);']);
-end
-
-
-hm1=zeros(M_.endo_nbr);
-h = hm1;
-hl1 = hm1;
-j = zeros(M_.endo_nbr,M_.exo_nbr);
-
-
-% build hm1
-nlag_cols = length(lag_cols);
-for i=1:nlag_cols
-    hm1(:,lag_cols(i)) = g1(:,i);
-end
-
-% build h
-ncon_cols = length(con_cols);
-for i=1:ncon_cols
-    h(:,con_cols(i)) = g1(:,i+nlag_cols);
-end
-
-% build hl1
-nlea_cols = length(lea_cols);
-for i=1:nlea_cols
-    hl1(:,lea_cols(i)) = g1(:,i+nlag_cols+ncon_cols);
-end
-
-
-for i = 1:M_.exo_nbr
-    j(:,i) =g1(:,i+ny);
-end
diff --git a/matlab/occbin/get_occbin_complementarity_conditions.m b/matlab/occbin/get_occbin_complementarity_conditions.m
deleted file mode 100644
index eb1182288d4c4e0ff31aa3ca2b0d42cf8aaf8ebe..0000000000000000000000000000000000000000
--- a/matlab/occbin/get_occbin_complementarity_conditions.m
+++ /dev/null
@@ -1,74 +0,0 @@
-function [ivar,ieq,lb,ub] = get_occbin_complementarity_conditions(M,ramsey_policy)
-
-% Copyright (C) 2015-2018 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 <http://www.gnu.org/licenses/>.
-
-nrow = 1;
-if ramsey_policy
-    if isfield(M,'ramsey_model_constraints')
-        rc = M.ramsey_model_constraints;
-        for i = 1:length(rc)
-            switch rc{i}{2}
-              case {'>','>='}
-                ivar(nrow) = rc{i}{1};
-                ieq(nrow) = rc{i}{1};
-                lb(nrow) = eval(rc{i}{3});
-              case {'<','<='}
-                ivar(nrow) = rc{i}{1};
-                ieq(nrow) = rc{i}{1};
-                ub(nrow) = eval(rc{i}{3});
-              otherwise
-                error('Wrong operator in get_complementarity_conditions')
-            end
-            nrow = nrow + 1;
-        end
-    end
-end
-
-etags = M.equations_tags;
-for i=1:size(etags,1)
-    if strcmp(etags{i,2},'mcp')
-        str = etags{i,3};
-        kop = strfind(etags{i,3},'<');
-        if ~isempty(kop)
-            k = find(strcmp(strtrim(str(1:kop-1)), M.endo_names));
-            if isempty(k)
-                error(sprintf(['Complementarity condition %s: variable %s is ' ...
-                               'not recognized',etags{i,3},b{1}]))
-            end
-            ivar(nrow) = k;
-            ieq(nrow) = etags{i,1};
-            ub(nrow) = eval(str(kop+1:end));
-        else
-            kop = strfind(etags{i,3},'>');
-            if ~isempty(kop)
-                k = find(strcmp(strtrim(str(1:kop-1)), M.endo_names));
-                if isempty(k)
-                    error(sprintf(['Complementarity condition %s: variable %s is ' ...
-                                   'not recognized',etags{i},b{1}]))
-                end
-                ivar(nrow) = k;
-                ieq(nrow) = etags{i,1};
-                lb(k) = eval(str(kop+1:end));
-            else
-                error(sprintf(['Complementarity condition %s can''t be ' ...
-                               'parsed'],etags{i,3}))
-            end
-        end
-        nrow = nrow + 1;
-    end
-end
diff --git a/matlab/occbin/get_occbin_constraints.m b/matlab/occbin/get_occbin_constraints.m
deleted file mode 100644
index 6723f45423b13e99879900f0ec61413a9ccb9387..0000000000000000000000000000000000000000
--- a/matlab/occbin/get_occbin_constraints.m
+++ /dev/null
@@ -1,88 +0,0 @@
-function [i_base,i_alt,c_base,c_alt] = get_occbin_constraints(M,steady_state,ramsey_policy)
-
-% Copyright (C) 2015 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 <http://www.gnu.org/licenses/>.
-
-nrow = 1;
-if ramsey_policy
-    if isfield(M,'ramsey_model_constraints')
-        rc = M.ramsey_model_constraints;
-        for i = 1:length(rc)
-            switch rc{i}{2}
-              case {'>','>='}
-                ivar(nrow) = rc{i}{1};
-                ieq(nrow) = rc{i}{1};
-                lb(nrow) = eval(rc{i}{3});
-              case {'<','<='}
-                ivar(nrow) = rc{i}{1};
-                ieq(nrow) = rc{i}{1};
-                ub(nrow) = eval(rc{i}{3});
-              otherwise
-                error('Wrong operator in get_complementarity_conditions')
-            end
-            nrow = nrow + 1;
-        end
-    end
-end
-
-i_base = {};
-i_alt = {};
-etags = M.equations_tags;
-m = 1;
-base = true;
-for i=1:size(etags,1)
-    [iv,boundary,operator] = parse_constraint(etags{i,3},M.endo_names,M.params,M.param_names);
-    if strcmp(etags{i,2},'OCCBIN')
-        if base
-            i_alt{m} = 1:M.eq_nbr;
-            i_alt{m}(etags{i,1}) = [];
-            c_base{m,1} = etags{i,1};
-            c_base{m,2} = iv;
-            c_base{m,3} = boundary - steady_state(iv);
-            c_base{m,4} = operator;
-            base = false;
-        else
-            i_base{m} = 1:M.eq_nbr;
-            i_base{m}(etags{i,1}) = [];
-            c_alt{m,1} = etags{i,1};
-            c_alt{m,2} = iv;
-            c_alt{m,3} = boundary - steady_state(iv);
-            c_alt{m,4} = operator;
-            base = true;
-            m = m + 1;
-        end
-    end
-end
-if ~base
-    error('OCCBIN: constraints must come by pair')
-end
-
-function [iv,boundary,operator] = parse_constraint(str,endo_names,params,param_names)
-delim = {'<=','>=','<','>'};
-[c,operator] = strsplit(str,delim);
-operator = operator{1};
-iv = strmatch(strtrim(c{1}),endo_names);
-% try for a number
-boundary = str2num(strtrim(c{2}));
-% if not a number try for a parameter name
-if isempty(boundary)
-    k = strmatch(strtrim(c{2}),param_names);
-    if isempty(k)
-        error(['OCCBIN: illegal constraint ' str]);
-    end
-    boundary = params(k);
-end
diff --git a/matlab/occbin/get_pq.m b/matlab/occbin/get_pq.m
deleted file mode 100644
index 99888b8068b68e26d2ad22461463019e169fb4a7..0000000000000000000000000000000000000000
--- a/matlab/occbin/get_pq.m
+++ /dev/null
@@ -1,28 +0,0 @@
-function [p,q]=get_pq(dr_,nstatic,nfwrd)
-
-nvars = size(dr_.ghx,1);
-nshocks = size(dr_.ghu,2);
-statevar_pos = (nstatic +1):(nvars-nfwrd);
-
-p = zeros(nvars);
-% interlace matrix
-nnotzero = length(statevar_pos);
-for i=1:nnotzero
-    p(:,statevar_pos(i)) = dr_.ghx(:,i);
-end
-
-% reorder p matrix according to order in lgy_
-inverse_order = zeros(nvars,1);
-for i=1:nvars
-    inverse_order(i) = find(i==dr_.order_var);
-end
-
-p_reordered = zeros(nvars);
-q = zeros(nvars,nshocks);
-for i=1:nvars
-    for j=1:nvars
-        p_reordered(i,j)=p(inverse_order(i),inverse_order(j));
-    end
-    q(i,:)=dr_.ghu(inverse_order(i),:);
-end
-p=p_reordered;
\ No newline at end of file
diff --git a/matlab/occbin/get_residuals.m b/matlab/occbin/get_residuals.m
deleted file mode 100644
index f86d05cfb2e6802be178ff5250dfc788943a6473..0000000000000000000000000000000000000000
--- a/matlab/occbin/get_residuals.m
+++ /dev/null
@@ -1,10 +0,0 @@
-function r = get_residuals(ivar,lb,ub,M,oo)
-
-ss = oo.steady_state;
-for i = 1:length(ivar)
-    % only one is different from zero
-    ss(ivar(i)) = lb(i) + ub(i);
-end
-oo.steady_state = ss;
-
-r = evaluate_model(M,oo);
\ No newline at end of file
diff --git a/matlab/occbin/makechart.m b/matlab/occbin/makechart.m
deleted file mode 100644
index 934e8463bf1fb8620ba0ede35d5dc2e27600e329..0000000000000000000000000000000000000000
--- a/matlab/occbin/makechart.m
+++ /dev/null
@@ -1,81 +0,0 @@
-function makechart(titlelist,legendlist,figlabel,ylabels,zdata1,zdata2,zdata3)
-
-
-
-figure
-
-titlelist = char(strrep(cellstr(titlelist),'_','.'));
-
-ndsets=3;       % default, changed below as applicable
-if nargin==5
-    zdata2=nan*zdata1;
-    zdata3=nan*zdata1;
-    ndsets =1;
-elseif nargin == 6
-    zdata3 =nan*zdata1;
-    ndsets=2;
-elseif ((nargin>8) | (nargin <=4))
-    error ('makechart takes 5 to 6 arguments')
-end
-
-nobs = size(zdata1,1);
-xvalues = (1:nobs)';
-
-nvars = size(titlelist,1);
-if nvars==1
-    nrows=1;
-    ncols = 1;
-elseif nvars==2
-    nrows =2;
-    ncols = 1;
-elseif (nvars == 3 | nvars ==4)
-    nrows = 2;
-    ncols =2;
-elseif (nvars==5 |nvars ==6)
-    nrows = 3;
-    ncols = 2;
-elseif (nvars==7 | nvars==8)
-    nrows = 4;
-    ncols = 2;
-elseif (nvars==9 | nvars==10)
-    nrows = 5;
-    ncols = 2;
-else
-    error('too many variables (makechart)')
-end
-
-for i = 1:nvars
-    subplot(nrows,ncols,i)
-    h1=plot(xvalues,zdata1(:,i),'b-','linewidth',2); hold on
-    h1=plot(xvalues,zdata2(:,i),'r--','linewidth',2); hold on
-    h2=plot(xvalues,zdata3(:,i),'b-','LineWidth',3);
-    [x0, x1, y10, y11] = pickaxes(xvalues,zdata1(:,i));
-    [x0, x1, y20, y21] = pickaxes(xvalues,zdata2(:,i));
-    [x0, x1, y30, y31] = pickaxes(xvalues,zdata3(:,i));
-    y0 = min([y10,y20,y30]);
-    y1 = max([y11,y21,y31]);
-    if y0==y1
-        y1=y0+1;
-    end
-
-    axis([x0 x1 y0 y1])
-    set(h1);
-
-    if i==1 && isempty(legendlist)==0
-        legend(legendlist)
-        text('String',figlabel,'Units','normalized','Position',[1.2 1.24],...
-             'FontSize',14,'FontWeight','bold','HorizontalAlignment','center');
-    end
-
-    if i==nvars | i==nvars-1
-        xlabel('Time');
-    end
-    %     set(gca,'XTick',xtick)
-    %     set(gca,'XTickLabel',xticklabel)
-
-    title([num2str(i),'. ',titlelist(i,:)]);
-    ylabel(ylabels(i,:))
-end
-
-% sets printing preferences
-%printpref
diff --git a/matlab/occbin/makechart9.m b/matlab/occbin/makechart9.m
deleted file mode 100644
index 264f9f58f73a0535c61adc47b6ff2954e617553b..0000000000000000000000000000000000000000
--- a/matlab/occbin/makechart9.m
+++ /dev/null
@@ -1,136 +0,0 @@
-function makechart9(titlelist,legendlist,figlabel,yearshock,ylabels,...
-                    zdata1,zdata2,zdata3,zdata4,zdata5,zdata6,zdata7)
-
-
-
-figure
-
-titlelist = char(strrep(cellstr(titlelist),'_','.'));
-
-ndsets=7;       % default, changed below as applicable
-if nargin==6
-    zdata2=nan*zdata1;
-    zdata3=nan*zdata1;
-    zdata4=nan*zdata1;
-    zdata5=nan*zdata1;
-    zdata6=nan*zdata1;
-    zdata7=nan*zdata1;
-    ndsets =1;
-elseif nargin==7
-    zdata3=nan*zdata1;
-    zdata4=nan*zdata1;
-    zdata5=nan*zdata1;
-    zdata6=nan*zdata1;
-    zdata7=nan*zdata1;
-    ndsets =2;
-elseif nargin == 8
-    zdata4 =nan*zdata1;
-    zdata5 =nan*zdata1;
-    zdata6=nan*zdata1;
-    zdata7=nan*zdata1;
-    ndsets=3;
-elseif nargin == 9
-    zdata5 =nan*zdata1;
-    zdata6=nan*zdata1;
-    zdata7=nan*zdata1;
-    ndsets=4;
-elseif nargin == 10
-    zdata6 =nan*zdata1;
-    zdata7=nan*zdata1;
-    ndsets=5;
-elseif nargin == 11
-    zdata7=nan*zdata1;
-    ndsets=6;
-elseif ((nargin>=13) | (nargin <=3))
-    error ('makechart takes 4 to 10 arguments')
-end
-
-nobs = size(zdata1,1);
-
-if yearshock>-100
-    xvalues = yearshock+(0:nobs-1)'/4; % Matteo plot year on x axis
-else
-    xvalues = (1:nobs)'; % Matteo plot year on x axis
-end
-
-nvars = size(titlelist,1);
-if nvars==1
-    nrows=1;
-    ncols = 1;
-elseif nvars==2
-    nrows =2;
-    ncols = 1;
-elseif nvars == 3
-    nrows = 3;
-    ncols = 1;
-elseif nvars==4
-    nrows = 2;
-    ncols = 2;
-elseif (nvars==5 | nvars ==6)
-    nrows = 3;
-    ncols = 2;
-elseif (nvars==7 | nvars==8)
-    nrows = 4;
-    ncols = 2;
-elseif nvars>8 & nvars<=12
-    nrows = 3;
-    ncols = 4;
-elseif nvars>12 & nvars<=15
-    nrows = 5;
-    ncols = 3;
-else
-    error('too many variables (makechart)')
-end
-
-
-for i = 1:nvars
-    subplot(nrows,ncols,i)
-    h1=plot(xvalues,zdata1(:,i),'k',...
-            xvalues,zdata2(:,i),'r',...
-            xvalues,zdata3(:,i),'b',...
-            xvalues,zdata4(:,i),'g',...
-            xvalues,zdata5(:,i),'g',...
-            xvalues,zdata6(:,i),'c',...
-            xvalues,zdata7(:,i),'y');
-    [x0, x1, y10, y11] = pickaxes(xvalues,zdata1(:,i));
-    [x0, x1, y20, y21] = pickaxes(xvalues,zdata2(:,i));
-    [x0, x1, y30, y31] = pickaxes(xvalues,zdata3(:,i));
-    [x0, x1, y40, y41] = pickaxes(xvalues,zdata4(:,i));
-    [x0, x1, y50, y51] = pickaxes(xvalues,zdata5(:,i));
-    [x0, x1, y60, y61] = pickaxes(xvalues,zdata6(:,i));
-    [x0, x1, y70, y71] = pickaxes(xvalues,zdata7(:,i));
-    grid on
-    y0 = min([y10,y20,y30,y40,y50,y60,y70]);
-    y1 = max([y11,y21,y31,y41,y51,y61,y71]);
-    if y0==y1
-        y1=y0+1;
-    end
-
-    axis([x0 x1 y0 y1])
-    set(h1,'linewidth',2);
-    if i==1
-        if numel(strvcat(legendlist(1,:)))
-            h=legend(legendlist,'Location','Northwest');
-            set(h,'Fontsize',8)
-        end
-    end
-    if i==1
-        if nvars>3
-            text('String',figlabel,'Units','normalized','Position',[1.2 1.21],...
-                 'FontSize',13,'FontWeight','bold','HorizontalAlignment','center');
-        else
-            text('String',figlabel,'Units','normalized','Position',[0.4 1.24],...
-                 'FontSize',13,'FontWeight','bold','HorizontalAlignment','center');
-        end
-    end
-
-    %set(gca,'XTick',xtick)
-    %set(gca,'XTickLabel',xticklabel)
-
-    title(titlelist(i,:),'Fontsize',11);
-    ylabel(ylabels(i,:))
-
-end
-
-% sets printing preferences
-%printpref
diff --git a/matlab/occbin/map_regime.m b/matlab/occbin/map_regime.m
deleted file mode 100644
index 702b011f9fb516114539a7c6530ba44fec2bd378..0000000000000000000000000000000000000000
--- a/matlab/occbin/map_regime.m
+++ /dev/null
@@ -1,24 +0,0 @@
-function [regime, regimestart]=map_regime(violvecbool)
-
-nperiods = length(violvecbool)-1;
-
-% analyse violvec and isolate contiguous periods in the other regime.
-regime(1) = violvecbool(1);
-regimeindx = 1;
-regimestart(1) = 1;
-for i=2:nperiods
-    if violvecbool(i)~=regime(regimeindx)
-        regimeindx=regimeindx+1;
-        regime(regimeindx) = violvecbool(i);
-        regimestart(regimeindx)=i;
-    end
-end
-
-
-if (regime(1) == 1 & length(regimestart)==1)
-    warning('Increase nperiods');
-end
-
-if (regime(end)==1)
-    warning('Increase nperiods');
-end
diff --git a/matlab/occbin/mkdata.m b/matlab/occbin/mkdata.m
deleted file mode 100644
index f887f021c5dfdc9a1d6af1c50a29f9e6e5745e35..0000000000000000000000000000000000000000
--- a/matlab/occbin/mkdata.m
+++ /dev/null
@@ -1,63 +0,0 @@
-function [zdata]=mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,scalefactormod,init)
-
-%[nsim, ksim, ysim, isim, csim] = mkdata(nperiods,cofb,endog_)
-
-% given decision rule
-neqs = length(endog_);
-
-if  nargin<9
-    init = zeros(neqs,1);
-end
-
-if  nargin<8
-    scalefactormod=1;
-end
-
-if nargin<7
-    error('Not enough inputs')
-end
-
-history = zeros(neqs,nperiods+1);
-
-nshocks = size(irfshock,1);
-for i = 1:nshocks
-    shockpos = strmatch(irfshock(i,:), exog_,'exact');
-    if ~isempty(shockpos)
-        irfshockpos(i) = shockpos;
-    else
-        error(['Shock ',irfshock(i,:),' is not in the model']);
-    end
-end
-
-
-% generate data
-% history will contain data, the state vector at each period in time will
-% be stored columnwise.
-history = zeros(neqs,nperiods);
-history(:,1)= init;
-
-lengthshock = size(scalefactormod,1);
-
-errvec = zeros(length(exog_), 1);
-
-for i = 2:nperiods+1
-    if i<=(lengthshock+1)
-        for j = 1:nshocks
-            errvec(irfshockpos(j)) = scalefactormod(i-1,j);
-        end
-        history(:,i) = decrulea * history(:,i-1)+decruleb*errvec;
-    else
-        % update endogenous variables
-        history(:,i) = decrulea * history(:,i-1);
-    end
-end
-
-% extract desired variables
-nwish=size(wishlist,1);
-wishpos = zeros(nwish,1);
-
-history=history';
-for i=1:nwish
-    wishpos(i) = strmatch(wishlist(i,:), endog_, 'exact');
-end
-zdata = history(2:end,wishpos);
\ No newline at end of file
diff --git a/matlab/occbin/mkdatap_anticipated.m b/matlab/occbin/mkdatap_anticipated.m
deleted file mode 100644
index e26781c926c629bfaf6ed3535f00f570b832e265..0000000000000000000000000000000000000000
--- a/matlab/occbin/mkdatap_anticipated.m
+++ /dev/null
@@ -1,124 +0,0 @@
-function [zdata]=mkdatap_anticipated(nperiods,decrulea,decruleb,...
-                                     cof,Jbarmat,cofstar,Jstarbarmat,Dstarbarmat,...
-                                     regime,regimestart,violvecbool,...
-                                     endog_,exog_,irfshock,scalefactormod,init)
-
-
-
-nvars = length(endog_);
-
-if nargin<16
-    init=zeros(nvars,1);
-end
-
-if nargin<15
-    scalefactormod=1;
-end
-
-
-nshocks = size(irfshock,1);
-for i = 1:nshocks
-    shockpos = strmatch(irfshock(i,:), exog_, 'exact');
-    if ~isempty(shockpos)
-        irfshockpos(i) = shockpos;
-    else
-        error(['Shock ', irfshock(i,:), ' is not in the model']);
-    end
-end
-
-
-nregimes = length(regime);
-
-Cbarmat = cof(:,1:nvars);
-Bbarmat = cof(:,nvars+1:2*nvars);
-Abarmat = cof(:,2*nvars+1:3*nvars);
-
-
-% cofstar contains the system for the model when the constraint binds
-Cstarbarmat = cofstar(:,1:nvars);
-Bstarbarmat = cofstar(:,nvars+1:2*nvars);
-Astarbarmat = cofstar(:,2*nvars+1:3*nvars);
-
-% get the time-dependent decision rules
-
-Tmax = regimestart(nregimes)-1;  % Tmax is the position of the last period
-                                 % when the constraint binds
-
-if Tmax > 0
-    P = zeros(nvars,nvars,Tmax);
-    D = zeros(nvars,Tmax);
-
-
-    invmat = inv((Astarbarmat*decrulea+Bstarbarmat));
-    P(:,:,Tmax) = -invmat*Cstarbarmat;
-    D(:,Tmax) = -invmat*Dstarbarmat;
-
-
-    % equivalent to pre-multiplying by the inverse above if the target
-    % matrix is invertible. Otherwise it yields the minimum state solution
-    %P(:,:,Tmax) = -(Astarbarmat*decrulea+Bstarbarmat)\Cstarbarmat;
-    %D(:,Tmax) = -(Astarbarmat*decrulea+Bstarbarmat)\Dstarbarmat;
-
-
-    for i = Tmax-1:-1:1
-
-        if violvecbool(i)
-            invmat = inv(Bstarbarmat+Astarbarmat*P(:,:,i+1));
-            P(:,:,i)=-invmat*Cstarbarmat;
-            D(:,i) = -invmat*(Astarbarmat*D(:,i+1)+Dstarbarmat);
-        else
-            invmat = inv(Bbarmat+Abarmat*P(:,:,i+1));
-            P(:,:,i)=-invmat*Cbarmat;
-            D(:,i) = -invmat*(Abarmat*D(:,i+1));
-        end
-    end
-
-    if Tmax > 1
-        if violvecbool(1)
-            E = -invmat*Jstarbarmat;
-        else
-            E = -invmat*Jbarmat;
-        end
-    else
-        invmat = inv(Astarbarmat*decrulea+Bstarbarmat);
-        E = -invmat*Jstarbarmat;
-
-    end
-
-
-end
-
-% generate data
-% history will contain data, the state vector at each period in time will
-% be stored columnwise.
-history = zeros(nvars,nperiods+1);
-history(:,1) = init;
-errvec = zeros(length(exog_), 1);
-
-% deal with predetermined conditions
-for i = 1:nshocks
-    errvec(irfshockpos(i)) = scalefactormod(i);
-end
-
-% deal with shocks
-irfpos =1;
-if irfpos <=Tmax
-    history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+...
-        D(:,irfpos) + E*errvec;
-else
-    history(:,irfpos+1) = decrulea*history(:,irfpos)+decruleb*errvec;
-end
-
-% all other periods
-for irfpos=2:nperiods+1
-    if irfpos <=Tmax
-        history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+...
-            D(:,irfpos);
-    else
-        history(:,irfpos+1) = decrulea*history(:,irfpos);
-    end
-end
-
-
-history=history';
-zdata = history(2:end,:);
\ No newline at end of file
diff --git a/matlab/occbin/mkdatap_anticipated_2constraints.m b/matlab/occbin/mkdatap_anticipated_2constraints.m
deleted file mode 100644
index 496f5a931c8777970f3e991e6012ab455e188aaa..0000000000000000000000000000000000000000
--- a/matlab/occbin/mkdatap_anticipated_2constraints.m
+++ /dev/null
@@ -1,180 +0,0 @@
-function [zdata]=mkdatap_anticipated_2constraints(nperiods,decrulea,decruleb,...
-                                                  cof,Jbarmat,...
-                                                  cof10,Jbarmat10,Dbarmat10,...
-                                                  cof01,Jbarmat01,Dbarmat01,...
-                                                  cof11,Jbarmat11,Dbarmat11,...
-                                                  regime1,regimestart1,...
-                                                  regime2,regimestart2,...
-                                                  violvecbool,endog_,exog_,...
-                                                  irfshock,scalefactormod,init)
-
-
-nvars = size(endog_,1);
-
-
-if nargin<16
-    init=zeros(nvars,1);
-end
-
-if nargin<15
-    scalefactormod=1;
-end
-
-
-nshocks = size(irfshock,1);
-for i = 1:nshocks
-    shockpos = strmatch(irfshock(i,:),exog_,'exact');
-    if ~isempty(shockpos)
-        irfshockpos(i) = shockpos;
-    else
-        error(['Shock ',irfshock(i,:),' is not in the model']);
-    end
-end
-
-
-
-Cbarmat = cof(:,1:nvars);
-Bbarmat = cof(:,nvars+1:2*nvars);
-Abarmat = cof(:,2*nvars+1:3*nvars);
-
-
-% cofstar contains the system for the model when the constraint binds
-
-
-Cbarmat10 = cof10(:,1:nvars);
-Bbarmat10 = cof10(:,nvars+1:2*nvars);
-Abarmat10 = cof10(:,2*nvars+1:3*nvars);
-
-Cbarmat01 = cof01(:,1:nvars);
-Bbarmat01 = cof01(:,nvars+1:2*nvars);
-Abarmat01 = cof01(:,2*nvars+1:3*nvars);
-
-Cbarmat11 = cof11(:,1:nvars);
-Bbarmat11 = cof11(:,nvars+1:2*nvars);
-Abarmat11 = cof11(:,2*nvars+1:3*nvars);
-
-% get the time-dependent decision rules
-nregimes1 = length(regime1);
-nregimes2 = length(regime2);
-
-Tmax = max([regimestart1(nregimes1) regimestart2(nregimes2)])-1;  % Tmax is the position of the last period
-                                                                  % when the constraint binds
-
-if Tmax > 0
-    P = zeros(nvars,nvars,Tmax);
-    D = zeros(nvars,Tmax);
-
-    %     invmat = inv((Astarbarmat*decrulea+Bstarbarmat));
-    %     P(:,:,Tmax) = -invmat*Cstarbarmat;
-    %     D(:,Tmax) = -invmat*Dstarbarmat;
-
-
-    if (violvecbool(Tmax,1) & ~violvecbool(Tmax,2))
-        %XXX fix next three lines
-        invmat = inv((Abarmat10*decrulea+Bbarmat10));
-        P(:,:,Tmax) = -invmat*Cbarmat10;
-        D(:,Tmax) = -invmat*Dbarmat10;
-    elseif (violvecbool(Tmax,1) & violvecbool(Tmax,2))
-        invmat = inv((Abarmat11*decrulea+Bbarmat11));
-        P(:,:,Tmax) = -invmat*Cbarmat11;
-        D(:,Tmax) = -invmat*Dbarmat11;
-    else
-        invmat = inv((Abarmat01*decrulea+Bbarmat01));
-        P(:,:,Tmax) = -invmat*Cbarmat01;
-        D(:,Tmax) = -invmat*Dbarmat01;
-    end
-
-
-
-
-    for i = Tmax-1:-1:1
-
-        if (violvecbool(i,1) & ~violvecbool(i,2))
-            invmat = inv(Bbarmat10+Abarmat10*P(:,:,i+1));
-            P(:,:,i)=-invmat*Cbarmat10;
-            D(:,i) = -invmat*(Abarmat10*D(:,i+1)+Dbarmat10);
-        elseif (~violvecbool(i,1) & violvecbool(i,2))
-            invmat = inv(Bbarmat01+Abarmat01*P(:,:,i+1));
-            P(:,:,i)=-invmat*Cbarmat01;
-            D(:,i) = -invmat*(Abarmat01*D(:,i+1)+Dbarmat01);
-        elseif (violvecbool(i,1) & violvecbool(i,2))
-            invmat = inv(Bbarmat11+Abarmat11*P(:,:,i+1));
-            P(:,:,i)=-invmat*Cbarmat11;
-            D(:,i) = -invmat*(Abarmat11*D(:,i+1)+Dbarmat11);
-        else
-            invmat = inv(Bbarmat+Abarmat*P(:,:,i+1));
-            P(:,:,i)=-invmat*Cbarmat;
-            D(:,i) = -invmat*(Abarmat*D(:,i+1));
-        end
-
-    end
-
-
-    % Double check the appropriate invmat in each case
-    % right now -- inherited from previous loop
-    if Tmax > 1
-
-        if ( ~violvecbool(1,1) & violvecbool(1,2) )
-            E = -invmat*Jbarmat01;
-        elseif ( violvecbool(1,1) & ~violvecbool(1,2) )
-            E = -invmat*Jbarmat10;
-        elseif ( violvecbool(1,1) & violvecbool(1,2) )
-            E = -invmat*Jbarmat11;
-        else
-            E = -invmat*Jbarmat;
-        end
-
-    else  % Tmax is equal to 1
-          %     invmat = inv((Astarbarmat*decrulea+Bstarbarmat));
-          %     E = -invmat*Jstarbarmat;
-
-        if ( ~violvecbool(1,1) & violvecbool(1,2) )
-            invmat = inv((Abarmat01*decrulea+Bbarmat01));
-            E = -invmat*Jbarmat01;
-        elseif ( violvecbool(1,1) & violvecbool(1,2) )
-            invmat = inv((Abarmat11*decrulea+Bbarmat11));
-            E = -invmat*Jbarmat11;
-        else
-            invmat = inv((Abarmat10*decrulea+Bbarmat10));
-            E = -invmat*Jbarmat10;
-
-        end
-
-    end
-
-
-end
-
-% generate data
-% history will contain data, the state vector at each period in time will
-% be stored columnwise.
-history = zeros(nvars,nperiods+1);
-history(:,1) = init;
-errvec = zeros(size(exog_,1),1);
-
-for i = 1:nshocks
-    errvec(irfshockpos(i)) = scalefactormod(i);
-end
-
-% deal with shocks
-irfpos =1;
-if irfpos <=Tmax
-    history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+...
-        D(:,irfpos) + E*errvec;
-else
-    history(:,irfpos+1) = decrulea*history(:,irfpos)+decruleb*errvec;
-end
-
-% all other periods
-for irfpos=2:nperiods+1
-    if irfpos <=Tmax
-        history(:,irfpos+1) = P(:,:,irfpos)* history(:,irfpos)+...
-            D(:,irfpos);
-    else
-        history(:,irfpos+1) = decrulea*history(:,irfpos);
-    end
-end
-
-
-history=history';
-zdata = history(2:end,:);
\ No newline at end of file
diff --git a/matlab/occbin/occbin.m b/matlab/occbin/occbin.m
deleted file mode 100644
index 2e467524f588c8a96986527784bc5eaded035b79..0000000000000000000000000000000000000000
--- a/matlab/occbin/occbin.m
+++ /dev/null
@@ -1,19 +0,0 @@
-function [endo_simul,endo_simul_no_constraint,status] = occbin(M,oo,options)
-% function oo=occbin(M,oo,options) solves linear models with occasionally
-% binding constraints using OCCBIN by L. Guerrieri
-
-status = 1;
-constraint_nbr = sum(strcmp(upper(M.equations_tags(:,2)),'OCCBIN'))/2;
-
-switch(constraint_nbr)
-  case 1
-    [zdatalinear_ zdatapiecewise_ zdatass_ oobase_ ] = ...
-        solve_one_constraint(M,oo,options);
-  case 2
-    [zdatalinear_ zdatapiecewise_ zdatass_ oobase_ ] = ...
-        solve_two_constraints(M,oo,options);
-  otherwise
-    error('OCCBIN can only handle two constraints in a model')
-end
-endo_simul = zdatapiecewise_';
-endo_simul_no_constraint = zdatalinear_';
\ No newline at end of file
diff --git a/matlab/occbin/pickaxes.m b/matlab/occbin/pickaxes.m
deleted file mode 100644
index 26c9b6b1a397d0eb019f20b4670e8c0317e54a8a..0000000000000000000000000000000000000000
--- a/matlab/occbin/pickaxes.m
+++ /dev/null
@@ -1,16 +0,0 @@
-function [x0,x1,y0,y1] = pickaxes(xvalues,yvalues)
-
-x0=xvalues(1);
-nobs = length(xvalues);
-x1=xvalues(nobs);
-
-maxy = max(yvalues);
-miny = min(yvalues);
-
-
-y0 = miny - .05*abs(miny);
-if (miny>0 & y0<0)
-    y0 = 0;
-end
-
-y1 = maxy + .05*abs(maxy);
diff --git a/matlab/occbin/process_constraint.m b/matlab/occbin/process_constraint.m
deleted file mode 100644
index 2d2b35f364299ed84cc072d35311eedeef3675c8..0000000000000000000000000000000000000000
--- a/matlab/occbin/process_constraint.m
+++ /dev/null
@@ -1,38 +0,0 @@
-% this function looks for occurrences of the endogenous variables in
-% endo_names in the input string constraint
-% all occurrences of the endogenous variables are appended a suffix
-% if the invert_switch is true, the direction of the inequality in the
-% constraint is inverted
-
-function constraint1 = process_constraint(constraint,suffix,endo_names,invert_switch)
-
-% create a list of delimiters that can separate parameters and endogenoous
-% variables in the string that expresses the constraint
-delimiters = char(',',';','(',')','+','-','^','*','/',' ','>','<','=');
-
-% split the string that holds the constraint into tokens
-tokens = tokenize(constraint,delimiters);
-
-ntokens = length(tokens);
-
-% search for tokens that match the list of endogenous variables
-for i=1:ntokens
-    if ~isempty(find(strcmp(tokens(i),endo_names)))
-        % when there is a match with an endogenous variable append the
-        % suffix
-        tokens(i) = cellstr([char(tokens(i)),suffix]);
-    end
-
-    % if the invert_switch is true
-    % reverse the direction of the inequality
-    if invert_switch
-        if  strcmp(tokens(i),cellstr('>'))
-            tokens(i) = cellstr('<');
-        elseif strcmp(tokens(i),cellstr('<'))
-            tokens(i) = cellstr('>');
-        end
-    end
-end
-
-% reassemble the tokens to create a string that expresses the constraint
-constraint1 = strmerge(tokens);
\ No newline at end of file
diff --git a/matlab/occbin/setss.m b/matlab/occbin/setss.m
deleted file mode 100644
index fe87642ea61e96ce75701ec5b8d766b1264cfb15..0000000000000000000000000000000000000000
--- a/matlab/occbin/setss.m
+++ /dev/null
@@ -1,13 +0,0 @@
-% Script that retrieves parameter values once model is solved
-
-nendog = length(Mbase_.endo_names);
-
-for i=1:nendog
-    eval([Mbase_.endo_names{i} '_ss = oo_.dr.ys(i); ']);
-end
-
-nparams = length(Mbase_.param_names);
-
-for i = 1:nparams
-    eval([Mbase_.param_names{i},'= M_.params(i);']);
-end
diff --git a/matlab/occbin/solve_no_constraint.m b/matlab/occbin/solve_no_constraint.m
deleted file mode 100644
index db3d457455af0754b2290ef37d404c9658799f7e..0000000000000000000000000000000000000000
--- a/matlab/occbin/solve_no_constraint.m
+++ /dev/null
@@ -1,49 +0,0 @@
-function [zdata_, zdatass_, oobase_, Mbase_ ] = ...
-    solve_no_constraint(modnam,...
-                        shockssequence,irfshock,nperiods)
-
-global M_ oo_
-
-errlist = [];
-
-% solve model
-eval(['dynare ',modnam,' noclearall'])
-oobase_ = oo_;
-Mbase_ = M_;
-
-ys_ = oobase_.dr.ys;
-nvars = numel(ys_);
-zdatass_ = ys_ ;
-
-for i=1:Mbase_.endo_nbr
-    eval([Mbase_.endo_names{i} '_ss = oo_.dr.ys(i); ']);
-end
-
-for i = 1:length(Mbase_.param_names)
-    eval([Mbase_.param_names{i}, '= M_.params(i);']);
-end
-
-
-
-
-
-
-
-[hm1,h,hl1,Jbarmat] = get_deriv(Mbase_,ys_);
-cof = [hm1,h,hl1];
-
-[decrulea,decruleb]=get_pq(oobase_.dr);
-endog_ = M_.endo_names;
-exog_ =  M_.exo_names;
-
-nvars = numel(Mbase_.endo_nbr);
-
-
-nshocks = size(shockssequence,1);
-init = zeros(nvars,1);
-
-wishlist = endog_;
-nwishes = length(wishlist);
-
-
-zdata_ = mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,shockssequence);
diff --git a/matlab/occbin/solve_no_constraint_noclear.m b/matlab/occbin/solve_no_constraint_noclear.m
deleted file mode 100644
index b290786af39427b24849d1fda51b04513f7d8a71..0000000000000000000000000000000000000000
--- a/matlab/occbin/solve_no_constraint_noclear.m
+++ /dev/null
@@ -1,47 +0,0 @@
-function [zdata, oobase_, Mbase_ ] = ...
-    solve_no_constraint_noclear(modnam,...
-                                shockssequence,irfshock,nperiods)
-
-global M_ oo_
-
-errlist = [];
-
-% solve model
-eval(['dynare ',modnam,'  nolog']);
-oobase_ = oo_;
-Mbase_ = M_;
-
-ys_ = oobase_.dr.ys;
-
-for i=1:Mbase_.endo_nbr
-    eval([Mbase_.endo_names{i} '_ss = oo_.dr.ys(i); ']);
-end
-
-for i = 1:length(Mbase_.param_names)
-    eval([Mbase_.param_names{i}, '= M_.params(i);']);
-end
-
-setss
-
-
-
-
-
-[hm1,h,hl1,Jbarmat] = get_deriv(Mbase_,ys_);
-cof = [hm1,h,hl1];
-
-[decrulea,decruleb]=get_pq(oobase_.dr);
-endog_ = M_.endo_names;
-exog_ =  M_.exo_names;
-
-
-nvars = numel(Mbase_.endo_nbr);
-
-nshocks = size(shockssequence,1);
-init = zeros(nvars,1);
-
-wishlist = endog_;
-nwishes = length(wishlist);
-
-
-zdata = mkdata(nperiods,decrulea,decruleb,endog_,exog_,wishlist,irfshock,shockssequence);
diff --git a/matlab/occbin/solve_one_constraint.1.m b/matlab/occbin/solve_one_constraint.1.m
deleted file mode 100644
index b197d452778721d679949c34ecf0be5f03d29e6b..0000000000000000000000000000000000000000
--- a/matlab/occbin/solve_one_constraint.1.m
+++ /dev/null
@@ -1,192 +0,0 @@
-% solve_one_constraint [zdatalinear zdatapiecewise zdatass oo base M base] = solve one constraint(modnam, modnamstar, constraint, constraint relax, shockssequence, irfshock, nperiods, maxiter, init);
-%
-% Inputs:
-% modnam: name of .mod file for the reference regime (excludes the .mod extension).
-% modnamstar: name of .mod file for the alternative regime (excludes the .mod exten- sion).
-% constraint: the constraint (see notes 1 and 2 below). When the condition in constraint evaluates to true, the solution switches from the reference to the alternative regime.
-% constraint relax: when the condition in constraint relax evaluates to true, the solution returns to the reference regime.
-% shockssequence: a sequence of unforeseen shocks under which one wants to solve the model (size T×nshocks).
-% irfshock: label for innovation for IRFs, from Dynare .mod file (one or more of the ?varexo?).
-% nperiods: simulation horizon (can be longer than the sequence of shocks defined in shockssequence; must be long enough to ensure convergence back to the reference model at the end of the simulation horizon and may need to be varied depending on the sequence of shocks).
-% maxiter: maximum number of iterations allowed for the solution algorithm (20 if not specified).
-% init: the initial position for the vector of state variables, in deviation from steady state (if not specified, the default is steady state). The ordering follows the definition order in the .mod files.
-%
-% Outputs:
-% zdatalinear: an array containing paths for all endogenous variables ignoring the occasionally binding constraint (the linear solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
-% zdatapiecewise: an array containing paths for all endogenous variables satisfying the occasionally binding constraint (the occbin/piecewise solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
-% zdatass: theinitialpositionforthevectorofstatevariables,indeviationfromsteady state (if not specified, the default is a vectors of zero implying that the initial conditions coincide with the steady state). The ordering follows the definition order in the .mod files.
-% oobase,Mbase: structures produced by Dynare for the reference model ? see Dynare User Guide.
-
-% Log of changes:
-% 6/17/2013 -- Luca added a trailing underscore to local variables in an
-% attempt to avoid conflicts with parameter names defined in the .mod files
-% to be processed.
-% 6/17/2013 -- Luca replaced external .m file setss.m
-
-
-function [zdatalinear_ zdatapiecewise_ zdatass_ oobase_ Mbase_  ] = ...
-    solve_one_constraint.1(modnam_,modnamstar_,...
-                           constraint_, constraint_relax_,...
-                           shockssequence_,irfshock_,nperiods_,maxiter_,init_)
-
-global M_ oo_
-
-errlist_ = [];
-
-% solve the reference model linearly
-eval(['dynare ',modnam_,' noclearall nolog '])
-oobase_ = oo_;
-Mbase_ = M_;
-
-% import locally the values of parameters assigned in the reference .mod
-% file
-for i_indx_ = 1:Mbase_.param_nbr
-    eval([Mbase_.param_names{i_indx_},'= M_.params(i_indx_);']);
-end
-
-% Create steady state values of the variables if needed for processing the constraint
-for i=1:Mbase_.endo_nbr
-    eval([Mbase_.endo_names{i} '_ss = oobase_.dr.ys(i); ']);
-end
-
-
-% parse the .mod file for the alternative regime
-eval(['dynare ',modnamstar_,' noclearall nolog '])
-oostar_ = oo_;
-Mstar_ = M_;
-
-
-% check inputs
-if ~strcmp(Mbase_.endo_names,Mstar_.endo_names)
-    error('The two .mod files need to have exactly the same endogenous variables declared in the same order')
-end
-
-if ~strcmp(Mbase_.exo_names,Mstar_.exo_names)
-    error('The two .mod files need to have exactly the same exogenous variables declared in the same order')
-end
-
-if ~strcmp(Mbase_.param_names,Mstar_.param_names)
-    warning('The parameter list does not match across .mod files')
-end
-
-% ensure that the two models have the same parameters
-% use the parameters for the base model.
-Mstar_.params = Mbase_.params;
-
-nvars_ = Mbase_.endo_nbr;
-zdatass_ = oobase_.dr.ys;
-
-
-% get the matrices holding the first derivatives for the model
-% each regime is treated separately
-[hm1_,h_,hl1_,Jbarmat_] = get_deriv(Mbase_,zdatass_);
-cof_ = [hm1_,h_,hl1_];
-
-[hm1_,h_,hl1_,Jstarbarmat_,resid_] = get_deriv(Mstar_,zdatass_);
-cofstar_ = [hm1_,h_,hl1_];
-Dstartbarmat_ = resid_;
-
-[decrulea_,decruleb_]=get_pq(oobase_.dr);
-endog_ = M_.endo_names;
-exog_ =  M_.exo_names;
-
-
-% processes the constraints specified in the call to this function
-% uppend a suffix to each endogenous variable
-constraint_difference_ = process_constraint(constraint_,'_difference',Mbase_.endo_names,0);
-
-constraint_relax_difference_ = process_constraint(constraint_relax_,'_difference',Mbase_.endo_names,0);
-
-
-
-nshocks_ = size(shockssequence_,1);
-
-% if necessary, set default values for optional arguments
-if ~exist('init_')
-    init_ = zeros(nvars_,1);
-end
-
-if ~exist('maxiter_')
-    maxiter_ = 20;
-end
-
-if ~exist('nperiods_')
-    nperiods_ = 100;
-end
-
-
-% set some initial conditions and loop through the shocks
-% period by period
-init_orig_ = init_;
-zdatapiecewise_ = zeros(nperiods_,nvars_);
-wishlist_ = endog_;
-nwishes_ = length(wishlist_);
-violvecbool_ = zeros(nperiods_+1,1);
-
-
-for ishock_ = 1:nshocks_
-
-    changes_=1;
-    iter_ = 0;
-
-
-    while (changes_ & iter_<maxiter_)
-        iter_ = iter_ +1;
-
-        % analyze when each regime starts based on current guess
-        [regime regimestart]=map_regime(violvecbool_);
-
-
-        % get the hypothesized piece wise linear solution
-        [zdatalinear_]=mkdatap_anticipated(nperiods_,decrulea_,decruleb_,...
-                                           cof_,Jbarmat_,cofstar_,Jstarbarmat_,Dstartbarmat_,...
-                                           regime,regimestart,violvecbool_,...
-                                           endog_,exog_,irfshock_,shockssequence_(ishock_,:),init_);
-
-        for i_indx_=1:nwishes_
-            eval([deblank(wishlist_{i_indx_}), '_difference=zdatalinear_(:,i_indx_);']);
-        end
-
-
-
-        newviolvecbool_ = eval(constraint_difference_);
-        relaxconstraint_ = eval(constraint_relax_difference_);
-
-
-
-        % check if changes to the hypothesis of the duration for each
-        % regime
-        if (max(newviolvecbool_-violvecbool_>0)) | sum(relaxconstraint_(find(violvecbool_==1))>0)
-            changes_ = 1;
-        else
-            changes_ = 0;
-        end
-
-
-        violvecbool_ = (violvecbool_|newviolvecbool_)-(relaxconstraint_ & violvecbool_);
-
-
-    end
-
-    init_ = zdatalinear_(1,:);
-    zdatapiecewise_(ishock_,:)=init_;
-    init_= init_';
-
-    % reset violvecbool_ for next period's shock -- this resetting is
-    % consistent with expecting no additional shocks
-    violvecbool_=[violvecbool_(2:end);0];
-
-end
-
-% if necessary, fill in the rest of the path with the remainder of the
-% last IRF computed.
-zdatapiecewise_(ishock_+1:end,:)=zdatalinear_(2:nperiods_-ishock_+1,:);
-
-% get the linear responses
-zdatalinear_ = mkdata(max(nperiods_,size(shockssequence_,1)),...
-                      decrulea_,decruleb_,endog_,exog_,...
-                      wishlist_,irfshock_,shockssequence_,init_orig_);
-
-if changes_ ==1
-    display('Did not converge -- increase maxiter_')
-end
diff --git a/matlab/occbin/solve_one_constraint.m b/matlab/occbin/solve_one_constraint.m
deleted file mode 100644
index 5606832a9378e1baaa47ad94365ddac34d735a11..0000000000000000000000000000000000000000
--- a/matlab/occbin/solve_one_constraint.m
+++ /dev/null
@@ -1,200 +0,0 @@
-% solve_one_constraint [zdatalinear zdatapiecewise zdatass oo base M base] = solve one constraint(modnam, modnamstar, constraint, constraint relax, shockssequence, irfshock, nperiods, maxiter, init);
-%
-% Inputs:
-% modnam: name of .mod file for the reference regime (excludes the .mod extension).
-% modnamstar: name of .mod file for the alternative regime (excludes the .mod exten- sion).
-% constraint: the constraint (see notes 1 and 2 below). When the condition in constraint evaluates to true, the solution switches from the reference to the alternative regime.
-% constraint relax: when the condition in constraint relax evaluates to true, the solution returns to the reference regime.
-% shockssequence: a sequence of unforeseen shocks under which one wants to solve the model (size T×nshocks).
-% irfshock: label for innovation for IRFs, from Dynare .mod file (one or more of the ?varexo?).
-% nperiods: simulation horizon (can be longer than the sequence of shocks defined in shockssequence; must be long enough to ensure convergence back to the reference model at the end of the simulation horizon and may need to be varied depending on the sequence of shocks).
-% maxiter: maximum number of iterations allowed for the solution algorithm (20 if not specified).
-% init: the initial position for the vector of state variables, in deviation from steady state (if not specified, the default is steady state). The ordering follows the definition order in the .mod files.
-%
-% Outputs:
-% zdatalinear: an array containing paths for all endogenous variables ignoring the occasionally binding constraint (the linear solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
-% zdatapiecewise: an array containing paths for all endogenous variables satisfying the occasionally binding constraint (the occbin/piecewise solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
-% zdatass: theinitialpositionforthevectorofstatevariables,indeviationfromsteady state (if not specified, the default is a vectors of zero implying that the initial conditions coincide with the steady state). The ordering follows the definition order in the .mod files.
-% oobase,Mbase: structures produced by Dynare for the reference model ? see Dynare User Guide.
-
-% Log of changes:
-% 6/17/2013 -- Luca added a trailing underscore to local variables in an
-% attempt to avoid conflicts with parameter names defined in the .mod files
-% to be processed.
-% 6/17/2013 -- Luca replaced external .m file setss.m
-
-
-function [zdatalinear_, zdatapiecewise_, zdatass_, oobase_, Mbase_  ] = ...
-    solve_one_constraint(modnam_,modnamstar_,...
-                         constraint_, constraint_relax_,...
-                         shockssequence_,irfshock_,nperiods_,maxiter_,init_)
-
-global M_ oo_
-
-errlist_ = [];
-
-% solve the reference model linearly
-eval(['dynare ',modnam_,' noclearall nolog '])
-oobase_ = oo_;
-Mbase_ = M_;
-
-% import locally the values of parameters assigned in the reference .mod
-% file
-for i_indx_ = 1:Mbase_.param_nbr
-    eval([Mbase_.param_names{i_indx_},'= M_.params(i_indx_);']);
-end
-
-% Create steady state values of the variables if needed for processing the constraint
-for i=1:Mbase_.endo_nbr
-    eval([Mbase_.endo_names{i} '_ss = oobase_.dr.ys(i); ']);
-end
-
-
-% parse the .mod file for the alternative regime
-eval(['dynare ',modnamstar_,' noclearall nolog '])
-oostar_ = oo_;
-Mstar_ = M_;
-
-
-% check inputs
-if ~strcmp(Mbase_.endo_names,Mstar_.endo_names)
-    error('The two .mod files need to have exactly the same endogenous variables declared in the same order')
-end
-
-if ~strcmp(Mbase_.exo_names,Mstar_.exo_names)
-    error('The two .mod files need to have exactly the same exogenous variables declared in the same order')
-end
-
-if ~strcmp(Mbase_.param_names,Mstar_.param_names)
-    warning('The parameter list does not match across .mod files')
-end
-
-% ensure that the two models have the same parameters
-% use the parameters for the base model.
-Mstar_.params = Mbase_.params;
-
-nvars_ = Mbase_.endo_nbr;
-zdatass_ = oobase_.dr.ys;
-
-
-% get the matrices holding the first derivatives for the model
-% each regime is treated separately
-[hm1_,h_,hl1_,Jbarmat_] = get_deriv(Mbase_,zdatass_);
-cof_ = [hm1_,h_,hl1_];
-
-[hm1_,h_,hl1_,Jstarbarmat_,resid_] = get_deriv(Mstar_,zdatass_);
-cofstar_ = [hm1_,h_,hl1_];
-Dstartbarmat_ = resid_;
-
-if isfield(Mbase_,'nfwrd')
-    % the latest Dynare distributions have moved nstatic and nfwrd
-    [decrulea_,decruleb_]=get_pq(oobase_.dr,Mbase_.nstatic,Mbase_.nfwrd);
-else
-    [decrulea_,decruleb_]=get_pq(oobase_.dr,oobase_.dr.nstatic,oobase_.dr.nfwrd);
-end
-
-endog_ = M_.endo_names;
-exog_ =  M_.exo_names;
-
-
-% processes the constraints specified in the call to this function
-% uppend a suffix to each endogenous variable
-constraint_difference_ = process_constraint(constraint_,'_difference',Mbase_.endo_names,0);
-
-constraint_relax_difference_ = process_constraint(constraint_relax_,'_difference',Mbase_.endo_names,0);
-
-
-
-nshocks_ = size(shockssequence_,1);
-
-% if necessary, set default values for optional arguments
-if ~exist('init_')
-    init_ = zeros(nvars_,1);
-end
-
-if ~exist('maxiter_')
-    maxiter_ = 20;
-end
-
-if ~exist('nperiods_')
-    nperiods_ = 100;
-end
-
-
-% set some initial conditions and loop through the shocks
-% period by period
-init_orig_ = init_;
-zdatapiecewise_ = zeros(nperiods_,nvars_);
-wishlist_ = endog_;
-nwishes_ = length(wishlist_);
-violvecbool_ = zeros(nperiods_+1,1);
-
-
-for ishock_ = 1:nshocks_
-
-    changes_=1;
-    iter_ = 0;
-
-
-    while (changes_ & iter_<maxiter_)
-        iter_ = iter_ +1;
-
-        % analyze when each regime starts based on current guess
-        [regime, regimestart]=map_regime(violvecbool_);
-
-
-
-        % get the hypothesized piece wise linear solution
-        [zdatalinear_]=mkdatap_anticipated(nperiods_,decrulea_,decruleb_,...
-                                           cof_,Jbarmat_,cofstar_,Jstarbarmat_,Dstartbarmat_,...
-                                           regime,regimestart,violvecbool_,...
-                                           endog_,exog_,irfshock_,shockssequence_(ishock_,:),init_);
-
-        for i_indx_=1:nwishes_
-            eval([wishlist_{i_indx_},'_difference=zdatalinear_(:,i_indx_);']);
-        end
-
-
-
-        newviolvecbool_ = eval(constraint_difference_);
-        relaxconstraint_ = eval(constraint_relax_difference_);
-
-
-
-        % check if changes to the hypothesis of the duration for each
-        % regime
-        if (max(newviolvecbool_-violvecbool_>0)) | sum(relaxconstraint_(find(violvecbool_==1))>0)
-            changes_ = 1;
-        else
-            changes_ = 0;
-        end
-
-
-
-        violvecbool_ = (violvecbool_|newviolvecbool_)-(relaxconstraint_ & violvecbool_);
-
-
-    end
-
-    init_ = zdatalinear_(1,:);
-    zdatapiecewise_(ishock_,:)=init_;
-    init_= init_';
-
-    % reset violvecbool_ for next period's shock -- this resetting is
-    % consistent with expecting no additional shocks
-    violvecbool_=[violvecbool_(2:end);0];
-
-end
-
-% if necessary, fill in the rest of the path with the remainder of the
-% last IRF computed.
-zdatapiecewise_(ishock_+1:end,:)=zdatalinear_(2:nperiods_-ishock_+1,:);
-
-% get the linear responses
-zdatalinear_ = mkdata(max(nperiods_,size(shockssequence_,1)),...
-                      decrulea_,decruleb_,endog_,exog_,...
-                      wishlist_,irfshock_,shockssequence_,init_orig_);
-
-if changes_ ==1
-    display('Did not converge -- increase maxiter_')
-end
diff --git a/matlab/occbin/solve_two_constraints.m b/matlab/occbin/solve_two_constraints.m
deleted file mode 100644
index 33fea1c728b7ae17b019a1ec8310806d78ef3c3f..0000000000000000000000000000000000000000
--- a/matlab/occbin/solve_two_constraints.m
+++ /dev/null
@@ -1,304 +0,0 @@
-% [zdatalinear zdatapiecewise zdatass oo 00 M 00] = solve two constraints(modnam 00,modnam 10,modnam 01,modnam 11,... constraint1, constraint2,... constraint relax1, constraint relax2,... shockssequence,irfshock,nperiods,curb retrench,maxiter,init);
-%
-% Inputs:
-% modnam 00: name of the .mod file for reference regime (excludes the .mod extension). modnam10: name of the .mod file for the alternative regime governed by the first
-% constraint.
-% modnam01: name of the .mod file for the alternative regime governed by the second constraint.
-% modnam 11: name of the .mod file for the case in which both constraints force a switch to their alternative regimes.
-% constraint1: the first constraint (see notes 1 and 2 below). If constraint1 evaluates to true, then the solution switches to the alternative regime for condition 1. In thatcase, if constraint2 (described below) evaluates to false, then the model solution switches to enforcing the conditions for an equilibrium in modnam 10. Otherwise, if constraint2 also evaluates to true, then the model solution switches to enforcing the conditions for an equilibrium in modnam 11.
-% constraint relax1: when the condition in constraint relax1 evaluates to true, the solution returns to the reference regime for constraint1.
-% constraint2: the second constraint (see notes 1 and 2 below). constraint relax2: when the condition in constraint relax2 evaluates to true, the
-% solution returns to the reference regime for constraint2. shockssequence: a sequence of unforeseen shocks under which one wants to solve the
-% model
-% irfshock: label for innovation for IRFs, from Dynare .mod file (one or more of the ?varexo?)
-% nperiods: simulation horizon (can be longer than the sequence of shocks defined in shockssequence; must be long enough to ensure convergence back to the reference model at the end of the simulation horizon and may need to be varied depending on the sequence of shocks).
-% curb retrench:        a scalar equal to 0 or 1. Default is 0. When set to 0, it updates the guess based of regimes based on the previous iteration. When set to 1, it updates in a manner similar to a Gauss-Jacobi scheme, slowing the iterations down by updating the guess of regimes only one period at a time.
-% maxiter: maximum number of iterations allowed for the solution algorithm (20 if not specified).
-% init: the initial position for the vector of state variables, in deviation from steady state (if not specified, the default is a vector of zero implying that the initial conditions coincide with the steady state). The ordering follows the definition order in the .mod files.
-%
-% Outputs:
-% zdatalinear: an array containing paths for all endogenous variables ignoring the occasionally binding constraint (the linear solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
-% zdatapiecewise: an array containing paths for all endogenous variables satisfying the occasionally binding constraint (the occbin/piecewise solution), in deviation from steady state. Each column is a variable, the order is the definition order in the .mod files.
-% zdatass: a vector that holds the steady state values of the endogenous variables ( following the definition order in the .mod file).
-% oo00 , M00 :  structures produced by Dynare for the reference model ? see Dynare User Guide.
-
-
-% Log of changes
-% 6/17/2013 -- Luca added a trailing underscore to local variables in an
-% attempt to avoid conflicts with parameter names defined in the .mod files
-% to be processed.
-% 6/17/2013 -- Luca replaced external .m file setss.m
-
-function [ zdatalinear_, zdatapiecewise_, zdatass_, oo00_ , M00_ ] = ...
-    solve_two_constraints(modnam_00_,modnam_10_,modnam_01_,modnam_11_,...
-                          constrain1_, constrain2_,...
-                          constraint_relax1_, constraint_relax2_,...
-                          shockssequence_,irfshock_,nperiods_,curb_retrench_,maxiter_,init_)
-
-global M_ oo_
-
-
-
-% solve model
-eval(['dynare ',modnam_00_,' noclearall nolog'])
-oo00_ = oo_;
-M00_ = M_;
-
-
-for i=1:M00_.endo_nbr
-    eval([M00_.endo_names{i} '_ss = oo00_.dr.ys(i); ']);
-end
-
-for i_indx_ = 1:M00_.param_nbr
-    eval([M00_.param_names{i_indx_},'= M00_.params(i_indx_);']);
-end
-
-
-
-eval(['dynare ',modnam_10_,' noclearall'])
-oo10_ = oo_;
-M10_ = M_;
-
-eval(['dynare ',modnam_01_,' noclearall'])
-oo01_ = oo_;
-M01_ = M_;
-
-eval(['dynare ',modnam_11_,' noclearall'])
-oo11_ = oo_;
-M11_ = M_;
-
-
-% do some error checking
-
-% check inputs
-if ~strcmp(M00_.endo_names,M10_.endo_names)
-    error([modnam_00_,' and ',modnam_10_,' need to have exactly the same endogenous variables and they need to be declared in the same order'])
-end
-
-if ~strcmp(M00_.exo_names,M10_.exo_names)
-    error([modnam_00_,' and ',modnam_10_,' need to have exactly the same exogenous variables and they need to be declared in the same order'])
-end
-
-if ~strcmp(M00_.param_names,M10_.param_names)
-    warning(['The parameter list does not match across the files ',modnam_00_,' and ',modnam_10_])
-end
-
-
-if ~strcmp(M00_.endo_names,M01_.endo_names)
-    error([modnam_00,' and ',modnam_01_,' need to have exactly the same endogenous variables and they need to be declared in the same order'])
-end
-
-if ~strcmp(M00_.exo_names,M01_.exo_names)
-    error([modnam_00_,' and ',modnam_01_,' need to have exactly the same exogenous variables and they need to be declared in the same order'])
-end
-
-if ~strcmp(M00_.param_names,M01_.param_names)
-    warning(['The parameter list does not match across the files ',modnam_00_,' and ',modnam_01_])
-end
-
-
-if ~strcmp(M00_.endo_names,M11_.endo_names)
-    error([modnam_00_,' and ',modnam_11_,' need to have exactly the same endogenous variables and they need to be declared in the same order'])
-end
-
-if ~strcmp(M00_.exo_names,M11_.exo_names)
-    error([modnam_00_,' and ',modnam_11_,' need to have exactly the same exogenous variables and they need to be declared in the same order'])
-end
-
-if ~strcmp(M00_.param_names,M11_.param_names)
-    warning(['The parameter list does not match across the files ',modnam_00_,' and ',modnam_11_])
-end
-
-
-
-
-
-nvars_ = M00_.endo_nbr;
-zdatass_ = oo00_.dr.ys;
-
-
-[hm1_,h_,hl1_,Jbarmat_] = get_deriv(M00_,zdatass_);
-cof_ = [hm1_,h_,hl1_];
-
-
-M10_.params = M00_.params;
-[hm1_,h_,hl1_,Jbarmat10_,resid_] = get_deriv(M10_,zdatass_);
-cof10_ = [hm1_,h_,hl1_];
-Dbarmat10_ = resid_;
-
-M01_.params = M00_.params;
-[hm1_,h_,hl1_,Jbarmat01_,resid_] = get_deriv(M01_,zdatass_);
-cof01_ = [hm1_,h_,hl1_];
-Dbarmat01_ = resid_;
-
-M11_.params = M00_.params;
-[hm1_,h_,hl1_,Jbarmat11_,resid_] = get_deriv(M11_,zdatass_);
-cof11_ = [hm1_,h_,hl1_];
-Dbarmat11_ = resid_;
-
-
-if isfield(M00_,'nfwrd')  % needed for bakward compatibility with older Dynare releases
-    [decrulea,decruleb]=get_pq(oo00_.dr,M00_.nstatic,M00_.nfwrd);
-else
-    [decrulea,decruleb]=get_pq(oo00_.dr,oo00_.dr.nstatic,oo00_.dr.nfwrd);
-end
-endog_ = M00_.endo_names;
-exog_ =  M00_.exo_names;
-
-
-% processes the constrain so as to uppend a suffix to each
-% endogenous variables
-constraint1_difference_ = process_constraint(constrain1_,'_difference',M00_.endo_names,0);
-
-% when the last argument in process_constraint is set to 1, the
-% direction of the inequality in the constraint is inverted
-constraint_relax1_difference_ = process_constraint(constraint_relax1_,'_difference',M00_.endo_names,0);
-
-
-% processes the constrain so as to uppend a suffix to each
-% endogenous variables
-constraint2_difference_ = process_constraint(constrain2_,'_difference',M00_.endo_names,0);
-
-% when the last argument in process_constraint is set to 1, the
-% direction of the inequality in the constraint is inverted
-constraint_relax2_difference_ = process_constraint(constraint_relax2_,'_difference',M00_.endo_names,0);
-
-
-
-nshocks = size(shockssequence_,1);
-
-
-
-
-if ~exist('init_')
-    init_ = zeros(nvars_,1);
-end
-
-if ~exist('maxiter_')
-    maxiter_ = 20;
-end
-
-if ~exist('curb_retrench_')
-    curb_retrench_ = 0;
-end
-
-init_orig_ = init_;
-
-
-
-
-
-
-zdatapiecewise_ = zeros(nperiods_,nvars_);
-
-
-violvecbool_ = zeros(nperiods_+1,2);  % This sets the first guess for when
-                                      % the constraints are going to hold.
-                                      % The variable is a boolean with two
-                                      % columns. The first column refers to
-                                      % constrain1_; the second to
-                                      % constrain2_.
-                                      % Each row is a period in time.
-                                      % If the boolean is true it indicates
-                                      % the relevant constraint is expected
-                                      % to evaluate to true.
-                                      % The default initial guess is
-                                      % consistent with the base model always
-                                      % holding -- equivalent to the linear
-                                      % solution.
-
-wishlist_ = endog_;
-nwishes_ = length(wishlist_);
-for ishock_ = 1:nshocks
-
-
-    changes_=1;
-    iter_ = 0;
-
-    while (changes_ & iter_<maxiter_)
-        iter_ = iter_ +1;
-
-        % analyse violvec and isolate contiguous periods in the other
-        % regime.
-        [regime1, regimestart1]=map_regime(violvecbool_(:,1));
-        [regime2, regimestart2]=map_regime(violvecbool_(:,2));
-
-
-        [zdatalinear_]=mkdatap_anticipated_2constraints(nperiods_,decrulea,decruleb,...
-                                                        cof_,Jbarmat_,...
-                                                        cof10_,Jbarmat10_,Dbarmat10_,...
-                                                        cof01_,Jbarmat01_,Dbarmat01_,...
-                                                        cof11_,Jbarmat11_,Dbarmat11_,...
-                                                        regime1,regimestart1,...
-                                                        regime2,regimestart2,...
-                                                        violvecbool_,endog_,exog_,...
-                                                        irfshock_,shockssequence_(ishock_,:),init_);
-
-        for i_indx_=1:nwishes_
-            eval([wishlist_{i_indx_}, '_difference=zdatalinear_(:,i_indx_);']);
-        end
-
-
-
-
-        newviolvecbool1_ = eval(constraint1_difference_);
-        relaxconstraint1_ = eval(constraint_relax1_difference_);
-
-        newviolvecbool2_ = eval(constraint2_difference_);
-        relaxconstraint2_ = eval(constraint_relax2_difference_);
-
-
-
-        newviolvecbool_ = [newviolvecbool1_;newviolvecbool2_];
-        relaxconstraint_ = [relaxconstraint1_;relaxconstraint2_];
-
-
-
-        % check if changes_
-        if (max(newviolvecbool_(:)-violvecbool_(:)>0)) | sum(relaxconstraint_(find(violvecbool_==1))>0)
-            changes_ = 1;
-        else
-            changes_ = 0;
-        end
-
-        if curb_retrench_   % apply Gauss-Sidel idea of slowing down the change in the guess
-                            % for the constraint -- only relax one
-                            % period at a time starting from the last
-                            % one when each of the constraints is true.
-            retrench = 0*violvecbool_(:);
-            if ~isempty(find(relaxconstraint1_ & violvecbool_(:,1)))
-                retrenchpos = max(find(relaxconstraint1_ & violvecbool_(:,1)));
-                retrench(retrenchpos) = 1;
-            end
-            if ~isempty(find(relaxconstraint2_ & violvecbool_(:,2)))
-                retrenchpos = max(find(relaxconstraint2_ & violvecbool_(:,2)));
-                retrench(retrenchpos+nperiods_+1) = 1;
-            end
-            violvecbool_ = (violvecbool_(:) | newviolvecbool_(:))-retrench(:);
-        else
-            violvecbool_ = (violvecbool_(:) | newviolvecbool_(:))-(relaxconstraint_(:) & violvecbool_(:));
-        end
-
-        violvecbool_ = reshape(violvecbool_,nperiods_+1,2);
-
-
-
-    end
-    if changes_ ==1
-        display('Did not converge -- increase maxiter')
-    end
-
-    init_ = zdatalinear_(1,:);
-    zdatapiecewise_(ishock_,:)=init_;
-    init_= init_';
-
-    % update the guess for constraint violations for next period
-    % update is consistent with expecting no additional shocks next period
-    violvecbool_=[violvecbool_(2:end,:);zeros(1,2)];
-
-end
-
-
-zdatapiecewise_(ishock_+1:end,:)=zdatalinear_(2:nperiods_-ishock_+1,:);
-
-zdatalinear_ = mkdata(nperiods_,decrulea,decruleb,endog_,exog_,wishlist_,irfshock_,shockssequence_,init_orig_);
diff --git a/matlab/occbin/strmerge.m b/matlab/occbin/strmerge.m
deleted file mode 100644
index 8aebb009956fb505bf4aedf678b07f1e0cf08945..0000000000000000000000000000000000000000
--- a/matlab/occbin/strmerge.m
+++ /dev/null
@@ -1,9 +0,0 @@
-function string = strmerge(tokens)
-
-ntokens = length(tokens);
-
-string = char(tokens(1));
-
-for i=2:ntokens
-    string = [string,char(tokens(i))];
-end
\ No newline at end of file
diff --git a/matlab/occbin/test_constraint.m b/matlab/occbin/test_constraint.m
deleted file mode 100644
index 96e41839a2e1ef8e372e4d63f022d17a279d91ea..0000000000000000000000000000000000000000
--- a/matlab/occbin/test_constraint.m
+++ /dev/null
@@ -1,16 +0,0 @@
-function b=test_constraint(x,constr)
-b = zeros(size(x,1),size(constr,1));
-for i=1:size(constr,1)
-    switch constr{i,4}
-      case '<'
-        b(:,i) = ~(x(:,constr{i,2}) < constr{i,3});
-      case '<='
-        b(:,i) = ~(x(:,constr{i,2}) <= constr{i,3});
-      case '>'
-        b(:,i) = ~(x(:,constr{i,2}) > constr{i,3});
-      case '>='
-        b(:,i) = ~(x(:,constr{i,2}) >= constr{i,3});
-      otherwise
-        error('OCCBIN: wrong inequality sign')
-    end
-end
\ No newline at end of file
diff --git a/matlab/occbin/tokenize.m b/matlab/occbin/tokenize.m
deleted file mode 100644
index 2cd8fb41031491d0a9d812a6d42e55fb2f02c07f..0000000000000000000000000000000000000000
--- a/matlab/occbin/tokenize.m
+++ /dev/null
@@ -1,54 +0,0 @@
-function tokens = tokenize(source,delimiter)
-% syntax
-% tokens = tokenize(source,delimiters)
-%
-% source is a string to be broken into tokens
-% delimiters is a character array of single character delimiters
-% tokens is a cell string array containing the tokens
-
-
-posdelims = [];
-
-% assumes that delimiter cannot be in the first position or the last
-% position
-ndelimiters = size(delimiter,1);
-for i=1:ndelimiters
-    newpositions = strfind(source,delimiter(i,:));
-    if ~isempty(newpositions)
-        posdelims =[posdelims, newpositions];
-    end
-end
-
-% reorder posdelims in ascending order
-posdelims = sort(posdelims);
-
-if isempty(posdelims)
-    tokens = cellstr(source);
-else
-    ndelims = length(posdelims);
-    % build positions for substrings
-    delims = zeros(ndelims+1,2);
-    for i=1:ndelims+1
-        if i==1
-            if posdelims(1) == 1
-                tokens = cellstr(source(1));
-            else
-                delims(i,:) = [1,posdelims(i)-1];
-                tokens = cellstr(source([delims(i,1):delims(i,2)]));
-                tokens = [tokens, source(posdelims(i))];
-            end
-        elseif  i==ndelims+1
-            if (posdelims(i-1) < length(source))
-                delims(i,:) = [posdelims(i-1)+1,length(source)];
-                tokens = [tokens, cellstr(source([delims(i,1):delims(i,2)]))];
-            end
-        else
-            if posdelims(i)>posdelims(i-1)+1
-                delims(i,:) = [posdelims(i-1)+1,posdelims(i)-1];
-                tokens = [tokens, cellstr(source([delims(i,1):delims(i,2)]))];
-            end
-            tokens = [tokens, source(posdelims(i))];
-        end
-    end
-
-end
diff --git a/matlab/optimization/dynare_minimize_objective.m b/matlab/optimization/dynare_minimize_objective.m
index 475392f593fbd46a1a0800af847ebd056544f263..512f3c8dc729eac06549b663c246db4fffdb6d6c 100644
--- a/matlab/optimization/dynare_minimize_objective.m
+++ b/matlab/optimization/dynare_minimize_objective.m
@@ -537,7 +537,13 @@ switch minimizer_algorithm
     if options_.silent_optimizer
         optim_options = optimset(optim_options,'display','off');
     end
-    [opt_par_values,Resnorm,fval,exitflag,OUTPUT,LAMBDA,JACOB] = lsqnonlin(objective_function,start_par_value,bounds(:,1),bounds(:,2),optim_options,varargin{:});
+    if ~isoctave        
+        [opt_par_values,Resnorm,fval,exitflag,OUTPUT,LAMBDA,JACOB] = lsqnonlin(objective_function,start_par_value,bounds(:,1),bounds(:,2),optim_options,varargin{:});
+    else
+        % Under Octave, use a wrapper, since lsqnonlin() does not have a 6th arg
+        func = @(x)objective_function(x,varargin{:});
+        [opt_par_values,Resnorm,fval,exitflag,OUTPUT,LAMBDA,JACOB] = lsqnonlin(func,start_par_value,bounds(:,1),bounds(:,2),optim_options);
+    end    
   otherwise
     if ischar(minimizer_algorithm)
         if exist(minimizer_algorithm)
diff --git a/matlab/particles b/matlab/particles
index cef20151625a8e353e6d3cd089276ee213fde88e..1c3153741fdbec610fbd95f6df4feb80f19e871e 160000
--- a/matlab/particles
+++ b/matlab/particles
@@ -1 +1 @@
-Subproject commit cef20151625a8e353e6d3cd089276ee213fde88e
+Subproject commit 1c3153741fdbec610fbd95f6df4feb80f19e871e
diff --git a/matlab/perfect-foresight-models/linear_perfect_foresight_problem.m b/matlab/perfect-foresight-models/linear_perfect_foresight_problem.m
index 1e73e6b0da902d60aa7974076a7836ba79a98d34..f2a84744a2f4ae5a06a335da2e1cfe77c87d22b2 100644
--- a/matlab/perfect-foresight-models/linear_perfect_foresight_problem.m
+++ b/matlab/perfect-foresight-models/linear_perfect_foresight_problem.m
@@ -16,7 +16,7 @@ function [residuals,JJacobian] = linear_perfect_foresight_problem(y, dynamicjaco
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2015-2019 Dynare Team
+% Copyright (C) 2015-2020 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -55,15 +55,35 @@ for it = maximum_lag+(1:T)
     if nargout == 2
         if T==1 && it==maximum_lag+1
             [rows, cols, vals] = find(dynamicjacobian(:,i_cols_0));
+            if size(dynamicjacobian, 1) == 1 % find() will return row vectors in this case
+                rows = rows';
+                cols = cols';
+                vals = vals';
+            end
             iJacobian{1} = [rows, i_cols_J0(cols), vals];
         elseif it == maximum_lag+1
             [rows,cols,vals] = find(dynamicjacobian(:,i_cols_1));
+            if size(dynamicjacobian, 1) == 1 % find() will return row vectors in this case
+                rows = rows';
+                cols = cols';
+                vals = vals';
+            end
             iJacobian{1} = [offset+rows, i_cols_J1(cols), vals];
         elseif it == maximum_lag+T
             [rows,cols,vals] = find(dynamicjacobian(:,i_cols_T));
+            if size(dynamicjacobian, 1) == 1 % find() will return row vectors in this case
+                rows = rows';
+                cols = cols';
+                vals = vals';
+            end
             iJacobian{T} = [offset+rows, i_cols_J(i_cols_T(cols)), vals];
         else
             [rows,cols,vals] = find(dynamicjacobian(:,i_cols_j));
+            if size(dynamicjacobian, 1) == 1 % find() will return row vectors in this case
+                rows = rows';
+                cols = cols';
+                vals = vals';
+            end
             iJacobian{it-maximum_lag} = [offset+rows, i_cols_J(cols), vals];
             i_cols_J = i_cols_J + ny;
         end
diff --git a/matlab/perfect-foresight-models/make_ex_.m b/matlab/perfect-foresight-models/make_ex_.m
index 39bff68049a22d77a317e9c971d230e4ab22ee3f..3c8922f8062c8df3b36fc5481d4b901fa73c6cee 100644
--- a/matlab/perfect-foresight-models/make_ex_.m
+++ b/matlab/perfect-foresight-models/make_ex_.m
@@ -53,14 +53,14 @@ if isempty(oo_.initval_series)
     end
 elseif M_.exo_nbr > 0
     x = oo_.initval_series{M_.exo_names{:}}.data;
-    oo_.exo_simul = x(1:M_.maximum_lag + options_.periods + M_.maximum_lead,:);
+    oo_.exo_simul = x(M_.orig_maximum_lag-M_.maximum_lag+1:M_.orig_maximum_lag + options_.periods + M_.maximum_lead,:);
     if ~isempty(M_.exo_histval)
         oo_.exo_simul(1:M_.maximum_lag, :) ...
             = M_.exo_histval(:, 1:M_.maximum_lag)';
     end
 elseif M_.exo_det_nbr > 0
     x_det = oo_.initval_series{M_.exo_det_names{:}}.data;
-    oo_.exo_det_simul = x_det(1:M_.maximum_lag + options_.periods + M_.maximum_lead,:);
+    oo_.exo_det_simul = x_det(M_.orig_maximum_lag-M_.maximum_lag+1:M_.orig_maximum_lag + options_.periods + M_.maximum_lead,:);
     if ~isempty(M_.exo_det_histval)
         oo_.exo_det_simul(1:M_.maximum_lag, :) ...
             = M_.exo_det_histval(:, 1:M_.maximum_lag)';
diff --git a/matlab/perfect-foresight-models/make_y_.m b/matlab/perfect-foresight-models/make_y_.m
index 4b3ece6a5b523e0e54d7b06c38cf2204b14f0200..585b69fe89488353db8b43b43a9afb748e2f4a4b 100644
--- a/matlab/perfect-foresight-models/make_y_.m
+++ b/matlab/perfect-foresight-models/make_y_.m
@@ -57,7 +57,7 @@ if isempty(oo_.initval_series)
     end
 else
     y = oo_.initval_series{M_.endo_names{:}}.data;
-    oo_.endo_simul = y(1:M_.maximum_lag + options_.periods + ...
+    oo_.endo_simul = y(M_.orig_maximum_lag - M_.maximum_lag + 1:M_.orig_maximum_lag + options_.periods + ...
                        M_.maximum_lead, :)';
     if ~isempty(M_.endo_histval)
         if ~isempty(ys0_)
@@ -66,4 +66,4 @@ else
         oo_.endo_simul(:,1:M_.maximum_lag) ...
             = M_.endo_histval(:, 1:M_.maximum_lag);
     end
-end
\ No newline at end of file
+end
diff --git a/matlab/perfect-foresight-models/perfect_foresight_mcp_problem.m b/matlab/perfect-foresight-models/perfect_foresight_mcp_problem.m
index 561e0162da6b474fff5766de7d7735e2088a53a8..eea045e1ff68ca3effbb1123fd17cad3ec0372c1 100644
--- a/matlab/perfect-foresight-models/perfect_foresight_mcp_problem.m
+++ b/matlab/perfect-foresight-models/perfect_foresight_mcp_problem.m
@@ -44,7 +44,7 @@ function [residuals,JJacobian] = perfect_foresight_mcp_problem(y, dynamic_functi
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 1996-2019 Dynare Team
+% Copyright (C) 1996-2020 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -82,16 +82,36 @@ for it = maximum_lag+(1:T)
         [res,jacobian] = dynamic_function(YY(i_cols),exo_simul, params, steady_state,it);
         residuals(i_rows) = res(eq_index);
         if T==1 && it==maximum_lag+1
-            [rows, cols, vals] = find(jacobian(:,i_cols_0));
+            [rows, cols, vals] = find(jacobian(eq_index,i_cols_0));
+            if size(jacobian, 1) == 1 % find() will return row vectors in this case
+                rows = rows';
+                cols = cols';
+                vals = vals';
+            end
             iJacobian{1} = [rows, i_cols_J0(cols), vals];
         elseif it == maximum_lag+1
             [rows,cols,vals] = find(jacobian(eq_index,i_cols_1));
+            if numel(eq_index) == 1 % find() will return row vectors in this case
+                rows = rows';
+                cols = cols';
+                vals = vals';
+            end
             iJacobian{1} = [offset+rows, i_cols_J1(cols), vals];
         elseif it == maximum_lag+T
             [rows,cols,vals] = find(jacobian(eq_index,i_cols_T));
+            if numel(eq_index) == 1 % find() will return row vectors in this case
+                rows = rows';
+                cols = cols';
+                vals = vals';
+            end
             iJacobian{T} = [offset+rows, i_cols_J(i_cols_T(cols)), vals];
         else
             [rows,cols,vals] = find(jacobian(eq_index,i_cols_j));
+            if numel(eq_index) == 1 % find() will return row vectors in this case
+                rows = rows';
+                cols = cols';
+                vals = vals';
+            end
             iJacobian{it-maximum_lag} = [offset+rows, i_cols_J(cols), vals];
             i_cols_J = i_cols_J + ny;
         end
diff --git a/matlab/perfect-foresight-models/perfect_foresight_solver_core.m b/matlab/perfect-foresight-models/perfect_foresight_solver_core.m
index ff7616d32c3d572e2c5c31fd3c66e707c6af9ff8..8692300c00761858c52e2e27ca95ce18f8021518 100644
--- a/matlab/perfect-foresight-models/perfect_foresight_solver_core.m
+++ b/matlab/perfect-foresight-models/perfect_foresight_solver_core.m
@@ -75,10 +75,10 @@ else
             oo_.deterministic_simulation.status = false;
         end
     else
-        if M_.maximum_endo_lead == 0 % Purely backward model
+        if M_.maximum_endo_lead == 0 && ~options_.lmmcp.status % Purely backward model
             [oo_.endo_simul, oo_.deterministic_simulation] = ...
                 sim1_purely_backward(oo_.endo_simul, oo_.exo_simul, oo_.steady_state, M_, options_);
-        elseif M_.maximum_endo_lag == 0 % Purely forward model
+        elseif M_.maximum_endo_lag == 0 && ~options_.lmmcp.status % Purely forward model
         [oo_.endo_simul, oo_.deterministic_simulation] = ...
             sim1_purely_forward(oo_.endo_simul, oo_.exo_simul, oo_.steady_state, M_, options_);
         else % General case
@@ -99,8 +99,12 @@ else
                     sim1_lbj(oo_.endo_simul, oo_.exo_simul, oo_.steady_state, M_, options_);
               case 7
                 if options_.linear_approximation
-                    if isequal(options_.solve_algo, 10)
-                        warning('It would be more efficient to set option solve_algo equal to 0!')
+                    if isequal(options_.solve_algo, 10) 
+                        if options_.ramsey_policy && isfield(M_,'ramsey_model_constraints') && ~isempty(M_.ramsey_model_constraints)
+                            warning('Due to ramsey_constraints you should not specify your model as model(linear)!')
+                        else
+                            warning('It would be more efficient to set option solve_algo equal to 0!')
+                        end
                     end
                     [oo_.endo_simul, oo_.deterministic_simulation] = ...
                         solve_stacked_linear_problem(oo_.endo_simul, oo_.exo_simul, oo_.steady_state, oo_.exo_steady_state, M_, options_);
@@ -116,7 +120,9 @@ else
 end
 
 if nargout>1
-    if options_.block && ~options_.bytecode
+    if options_.lmmcp.status
+        maxerror = NaN; % Could be improved
+    elseif options_.block && ~options_.bytecode
         maxerror = oo_.deterministic_simulation.error;
     else
         if options_.bytecode
diff --git a/matlab/perfect-foresight-models/private/initialize_stacked_problem.m b/matlab/perfect-foresight-models/private/initialize_stacked_problem.m
index f127858c97acf92a5381ed472c1b63754ddd9b46..1a7092854369c6a9a147aa2eb7f0335bb4a08a9d 100644
--- a/matlab/perfect-foresight-models/private/initialize_stacked_problem.m
+++ b/matlab/perfect-foresight-models/private/initialize_stacked_problem.m
@@ -30,7 +30,7 @@ function [options, y0, yT, z, i_cols, i_cols_J1, i_cols_T, i_cols_j, i_cols_1, i
 % - i_cols_J0           [double] indices of contemporaneous variables appearing in M.lead_lag_incidence (relevant in problems with periods=1)
 % - dynamicmodel        [handle] function handle to _dynamic-file
 
-% Copyright (C) 2015-2019 Dynare Team
+% Copyright (C) 2015-2020 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -73,22 +73,25 @@ end
 if M.maximum_lag > 0
     y0 = endogenousvariables(:, M.maximum_lag);
 else
-    y0 = NaN(ny, 1);
+    y0 = NaN(M.endo_nbr, 1);
 end
 if M.maximum_lead > 0
     yT = endogenousvariables(:, M.maximum_lag+periods+1);
 else
-    yT = NaN(ny, 1);
+    yT = NaN(M.endo_nbr, 1);
 end
 z = endogenousvariables(:,M.maximum_lag+(1:periods));
 illi = M.lead_lag_incidence';
 [i_cols,~,i_cols_j] = find(illi(:));
-illi = illi(:,2:3);
+if M.maximum_endo_lag == 0
+    i_cols = i_cols + M.endo_nbr;
+end
+illi = illi(:,(1+M.maximum_endo_lag):(1+M.maximum_endo_lag+M.maximum_endo_lead));
 [i_cols_J1,~,i_cols_1] = find(illi(:));
-i_cols_T = nonzeros(M.lead_lag_incidence(1:2,:)');
+i_cols_T = nonzeros(M.lead_lag_incidence(1:(1+M.maximum_endo_lag),:)');
 if periods==1
-    i_cols_0 = nonzeros(M.lead_lag_incidence(2,:)');
-    i_cols_J0 = find(M.lead_lag_incidence(2,:)');
+    i_cols_0 = nonzeros(M.lead_lag_incidence(1+M.maximum_endo_lag,:)');
+    i_cols_J0 = find(M.lead_lag_incidence(1+M.maximum_endo_lag,:)');
 else
     i_cols_0 = [];
     i_cols_J0 = [];
diff --git a/matlab/perfect-foresight-models/sim1_linear.m b/matlab/perfect-foresight-models/sim1_linear.m
index 6f63ca1fa189aca98146da41f96c478f0a1f9966..6f04ee81254280e85280be0a55ebd04d98ffff5f 100644
--- a/matlab/perfect-foresight-models/sim1_linear.m
+++ b/matlab/perfect-foresight-models/sim1_linear.m
@@ -38,7 +38,7 @@ function [endogenousvariables, info] = sim1_linear(endogenousvariables, exogenou
 % to center the variables around the deterministic steady state to solve the
 % perfect foresight model.
 
-% Copyright (C) 2015-2017 Dynare Team
+% Copyright (C) 2015-2020 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -159,16 +159,9 @@ for it = (maximum_lag+1):(maximum_lag+periods)
         nv = length(vv);
         iA(iv+m,:) = [i_rows(rr),i_cols_A(cc),vv];
     end
-    if M.maximum_exo_lag > 0
-        % needed as jacobian for lagged exogenous variables is wrong
-        % in current version of Dynare
-        zz = Y(i_cols);
-        res(i_rows) = dynamicmodel(zz, exogenousvariables, params, steadystate_y, it);
-    else
-        z(jendo) = Y(i_cols);
-        z(jexog) = transpose(exogenousvariables(it,:));
-        res(i_rows) = jacobian*z;
-    end
+    z(jendo) = Y(i_cols);
+    z(jexog) = transpose(exogenousvariables(it,:));
+    res(i_rows) = jacobian*z;
     m = m + nv;
     i_rows = i_rows + ny;
     i_cols = i_cols + ny;
@@ -251,4 +244,4 @@ end
 
 if verbose
     skipline();
-end
\ No newline at end of file
+end
diff --git a/matlab/plot_priors.m b/matlab/plot_priors.m
index 7d8aec8f7c3616807da5d229c4d1d38f92682dfd..881585a4d2f25eb3152a9db2a7cca088a4b33122 100644
--- a/matlab/plot_priors.m
+++ b/matlab/plot_priors.m
@@ -41,11 +41,11 @@ end
 npar = length(bayestopt_.p1);
 [nbplt,nr,nc,lr,lc,nstar] = pltorg(npar);
 
-if ~exist([M_.fname '/graphs'],'dir')
-    mkdir(M_.fname,'graphs');
+if ~exist([M_.dname '/graphs'],'dir')
+    mkdir(M_.dname,'graphs');
 end
 if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
-    fidTeX = fopen([M_.fname, '/graphs/' M_.fname '_Priors.tex'],'w');
+    fidTeX = fopen([M_.dname, '/graphs/' 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');
@@ -73,11 +73,11 @@ for plt = 1:nbplt
         end
         drawnow
     end
-    dyn_saveas(hplt,[M_.fname, '/graphs/' M_.fname '_Priors' int2str(plt)],options_.nodisplay,options_.graph_format);
+    dyn_saveas(hplt,[M_.dname, '/graphs/' 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_.fname, '/graphs/' M_.fname],int2str(plt));
+        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,'\\caption{Priors.}');
         fprintf(fidTeX,'\\label{Fig:Priors:%s}\n',int2str(plt));
         fprintf(fidTeX,'\\end{figure}\n');
diff --git a/matlab/posterior_analysis.m b/matlab/posterior_analysis.m
index 03bff87b8733cae15839ba2351a97d1c797db88a..453d3b5d66351c19368b9aa54b43f88e78849a21 100644
--- a/matlab/posterior_analysis.m
+++ b/matlab/posterior_analysis.m
@@ -66,7 +66,7 @@ switch type
                                              M_.exo_names,arg2,vartan,arg1,options_.mh_conf_sig,oo_,options_);
     if ~all(diag(M_.H)==0)
         if strmatch(arg1,options_.varobs,'exact')
-            if isoctave
+            if isoctave && octave_ver_less_than('6')
                 [observable_name_requested_vars,index_subset,index_observables]=intersect_stable(vartan,options_.varobs);
             else
                 [observable_name_requested_vars,index_subset,index_observables]=intersect(vartan,options_.varobs,'stable');
diff --git a/matlab/pruned_state_space_system.m b/matlab/pruned_state_space_system.m
index 1f180b9ae575e1f1bcd18cb17d0f9112828b6983..c4022c7dbbb39cd28b7bd7ee38aee628d5b6114d 100644
--- a/matlab/pruned_state_space_system.m
+++ b/matlab/pruned_state_space_system.m
@@ -372,7 +372,7 @@ stationary_vars = (1:y_nbr)';
 if ~isempty(Schur_u)
     %base this only on first order, because if first-order is stable so are the higher-order pruned systems
     x = abs(gx*Schur_u);
-    stationary_vars = find(all(x < options.Schur_vec_tol,2));
+    stationary_vars = find(all(x < options.schur_vec_tol,2));
 end
 
 if compute_derivs == 1
diff --git a/matlab/ramsey_policy.m b/matlab/ramsey_policy.m
index 46acdb85464df17891af79b057d17f892607fe24..720e2d83374c929e347f3a55d7c37f57b06430c3 100644
--- a/matlab/ramsey_policy.m
+++ b/matlab/ramsey_policy.m
@@ -44,7 +44,7 @@ end
 oo_.steady_state = oo_.dr.ys;
 
 if ~options_.noprint
-    disp_steady_state(M_,oo_)
+    disp_steady_state(M_,oo_,options_)
     for i=M_.orig_endo_nbr:M_.endo_nbr
         if strmatch('mult_', M_.endo_names{i})
             disp(sprintf('%s \t\t %g', M_.endo_names{i}, oo_.dr.ys(i)));
diff --git a/matlab/rplot.m b/matlab/rplot.m
index 2605e7f5a485b87804e940f4006fb0782c34483b..de200511d31989bc7ecef6f0d909e16082df5c39 100644
--- a/matlab/rplot.m
+++ b/matlab/rplot.m
@@ -37,12 +37,12 @@ if isempty(oo_.endo_simul)
     error('rplot: oo_.endo_simul is empty.')
 end
 
-% create subdirectory <fname>/graphs if it doesn't exist
-if ~exist(M_.fname, 'dir')
-    mkdir('.',M_.fname);
+% create subdirectory <dname>/graphs if it doesn't exist
+if ~exist(M_.dname, 'dir')
+    mkdir('.',M_.dname);
 end
-if ~exist([M_.fname filesep 'graphs'],'dir')
-    mkdir(M_.fname,'graphs');
+if ~exist([M_.dname filesep 'graphs'],'dir')
+    mkdir(M_.dname,'graphs');
 end
 
 ix = (1 - M_.maximum_lag:size(oo_.endo_simul,2)-M_.maximum_lag)';
@@ -69,7 +69,7 @@ else
 end
 
 if options_.TeX && any(strcmp('eps',cellstr(options_.graph_format)))
-    fidTeX = fopen([M_.fname, filesep, 'graphs', filesep, M_.fname '_simulated_trajectories_', num2str(options_.rplottype), '.tex'],'w');
+    fidTeX = fopen([M_.dname, filesep, 'graphs', filesep, M_.fname '_simulated_trajectories_', num2str(options_.rplottype), '.tex'],'w');
     fprintf(fidTeX,'%% TeX eps-loader file generated by rplot.m (Dynare).\n');
     fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
 end
@@ -94,9 +94,9 @@ if options_.rplottype == 0
             legend(s1,'interpreter','none');
         end
     end
-    dyn_saveas(hh,[M_.fname, filesep, 'graphs', filesep, 'SimulatedTrajectory_' s1{1}],options_.nodisplay,options_.graph_format)
+    dyn_saveas(hh,[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_.fname, '/graphs/', 'SimulatedTrajectory_' s1{1}],'Simulated trajectories','SimulatedTrajectory_',s1{1},1)
+        create_TeX_loader(fidTeX,[M_.dname, '/graphs/', 'SimulatedTrajectory_' s1{1}],'Simulated trajectories','SimulatedTrajectory_',s1{1},1)
     end
 elseif options_.rplottype == 1
     for j = 1:size(y,1)
@@ -109,9 +109,9 @@ elseif options_.rplottype == 1
             title(['Plot of ' s1{j}],'Interpreter','none') ;
         end
         xlabel('Periods') ;
-        dyn_saveas(hh,[M_.fname, filesep, 'graphs', filesep, 'SimulatedTrajectory_' s1{j}],options_.nodisplay,options_.graph_format)
+        dyn_saveas(hh,[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_.fname, '/graphs/', 'SimulatedTrajectory_' s1{j}],'Simulated trajectories','SimulatedTrajectory_',s1{j},1);
+            create_TeX_loader(fidTeX,[M_.dname, '/graphs/', 'SimulatedTrajectory_' s1{j}],'Simulated trajectories','SimulatedTrajectory_',s1{j},1);
         end
     end
 elseif options_.rplottype == 2
@@ -137,9 +137,9 @@ elseif options_.rplottype == 2
         end
         axis tight;
     end
-    dyn_saveas(hh,[M_.fname, filesep, 'graphs', filesep, 'SimulatedTrajectory_' s1{1}],options_.nodisplay,options_.graph_format)
+    dyn_saveas(hh,[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_.fname, '/graphs/', 'SimulatedTrajectory_' s1{1}],'Simulated trajectories','SimulatedTrajectory_', s1{1},min(j/nc,1));
+        create_TeX_loader(fidTeX,[M_.dname, '/graphs/', 'SimulatedTrajectory_' s1{1}],'Simulated trajectories','SimulatedTrajectory_', s1{1},min(j/nc,1));
     end
 end
 
diff --git a/matlab/solve_one_boundary.m b/matlab/solve_one_boundary.m
index af9b6559254036cb66925e1816dbea40a5c4549e..f4009b077f29dc95fa67dbd523a632b8a17d74ba 100644
--- a/matlab/solve_one_boundary.m
+++ b/matlab/solve_one_boundary.m
@@ -92,9 +92,10 @@ for it_=start:incr:finish
     g1=spalloc( Blck_size, Blck_size, nze);
     while ~(cvg==1 || iter>maxit_)
         if is_dynamic
-            [r, ~, T(:, it_), g1] = feval(fname, Block_Num, dynvars_from_endo_simul(y, it_, M), x, params, steady_state, T(:, it_), it_, false);
+            [r, yy, T(:, it_), g1] = feval(fname, Block_Num, dynvars_from_endo_simul(y, it_, M), x, params, steady_state, T(:, it_), it_, false);
+            y(:, it_) = yy(M.lead_lag_incidence(M.maximum_endo_lag+1,:));
         else
-            [r, ~, T, g1] = feval(fname, Block_Num, y, x, params, T);
+            [r, y, T, g1] = feval(fname, Block_Num, y, x, params, T);
         end
         if ~isreal(r)
             max_res=(-(max(max(abs(r))))^2)^0.5;
diff --git a/matlab/solve_two_boundaries.m b/matlab/solve_two_boundaries.m
index d1c595f6b6e21d6f117d51dbd9db144fdf7e9995..25524a0173fcc4a9a92d9893f8e864de965ca733 100644
--- a/matlab/solve_two_boundaries.m
+++ b/matlab/solve_two_boundaries.m
@@ -83,7 +83,8 @@ while ~(cvg==1 || iter>maxit_)
     r = NaN(Blck_size, periods);
     g1a = spalloc(Blck_size*periods, Blck_size*periods, nze*periods);
     for it_ = y_kmin+(1:periods)
-        [r(:, it_-y_kmin), ~, T(:, it_), g1]=feval(fname, Block_Num, dynvars_from_endo_simul(y, it_, M), x, params, steady_state, T(:, it_), it_, false);
+        [r(:, it_-y_kmin), yy, T(:, it_), g1]=feval(fname, Block_Num, dynvars_from_endo_simul(y, it_, M), x, params, steady_state, T(:, it_), it_, false);
+        y(:, it_) = yy(M.lead_lag_incidence(M.maximum_endo_lag+1,:));
         if periods == 1
             g1a = g1(:, Blck_size+(1:Blck_size));
         elseif it_ == y_kmin+1
diff --git a/matlab/steady.m b/matlab/steady.m
index cc2502201f79e9d9a08e0d79465d536497268262..b875d66988ebfe68684fe5bdc9119c40eff7f3cd 100644
--- a/matlab/steady.m
+++ b/matlab/steady.m
@@ -81,7 +81,7 @@ end
 
 if info(1) == 0
     if ~options_.noprint
-        disp_steady_state(M_,oo_);
+        disp_steady_state(M_,oo_,options_);
     end
 else
     if ~options_.noprint
diff --git a/matlab/stoch_simul.m b/matlab/stoch_simul.m
index ce517a8af738f32a09e1cfbc04cc0306432f6aeb..218d081791a29a339947bd37dcae86b5dd628370 100644
--- a/matlab/stoch_simul.m
+++ b/matlab/stoch_simul.m
@@ -79,7 +79,7 @@ oo_.dr=set_state_space(dr,M_,options_);
 if PI_PCL_solver
     [oo_.dr, info] = PCL_resol(oo_.steady_state,0);
 elseif options_.discretionary_policy
-    if ~options_.linear
+    if ~options_.order==1
         error('discretionary_policy: only linear-quadratic problems can be solved');
     end
     [~,info,M_,options_,oo_] = discretionary_policy_1(options_.instruments,M_,options_,oo_);
@@ -189,11 +189,11 @@ if ~options_.nomoments
     if PI_PCL_solver
         PCL_Part_info_moments(0, PCL_varobs, oo_.dr, i_var);
     elseif options_.periods == 0
-        if options_.order <= 2
+        if options_.order == 1 || (options_.order == 2 && ~options_.pruning)
             oo_=disp_th_moments(oo_.dr,var_list,M_,options_,oo_);
-        elseif options_.order == 3 && options_.pruning  
+        elseif (ismember(options_.order,[2,3])) && options_.pruning  
             % There is no code for theoretical moments at 3rd order without pruning
-            oo_=disp_th_moments_order3(oo_.dr,M_,options_,i_var,oo_);
+            oo_=disp_th_moments_pruned_state_space(oo_.dr,M_,options_,i_var,oo_);
         end
     else
         oo_=disp_moments(oo_.endo_simul,var_list,M_,options_,oo_);
@@ -204,12 +204,12 @@ end
 if options_.irf
     var_listTeX = M_.endo_names_tex(i_var);
     if ~options_.nograph || (TeX && any(strcmp('eps',cellstr(options_.graph_format))))
-        if ~exist([M_.fname '/graphs'],'dir')
-            mkdir(M_.fname,'graphs');
+        if ~exist([M_.dname '/graphs'],'dir')
+            mkdir(M_.dname,'graphs');
         end
     end
     if TeX && any(strcmp('eps',cellstr(options_.graph_format)))
-        fidTeX = fopen([M_.fname, '/graphs/' M_.fname '_IRF.tex'],'w');
+        fidTeX = fopen([M_.dname, '/graphs/' M_.fname '_IRF.tex'],'w');
         fprintf(fidTeX,'%% TeX eps-loader file generated by stoch_simul.m (Dynare).\n');
         fprintf(fidTeX,['%% ' datestr(now,0) '\n']);
         fprintf(fidTeX,' \n');
@@ -300,11 +300,11 @@ if options_.irf
                             title(deblank(mylist(j,:)),'Interpreter','none');
                         end
                     end
-                    dyn_saveas(hh,[M_.fname, '/graphs/' M_.fname '_IRF_' tit{i}],options_.nodisplay,options_.graph_format);
+                    dyn_saveas(hh,[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');
-                        fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_IRF_%s}\n',options_.figures.textwidth*min(j/nc,1),[M_.fname, '/graphs/' M_.fname],tit{i});
+                        fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_IRF_%s}\n',options_.figures.textwidth*min(j/nc,1),[M_.dname, '/graphs/' M_.fname],tit{i});
                         fprintf(fidTeX,'\\caption{Impulse response functions (orthogonalized shock to $%s$).}\n',titTeX{i});
                         fprintf(fidTeX,'\\label{Fig:IRF:%s}\n', tit{i});
                         fprintf(fidTeX,'\\end{figure}\n');
@@ -333,11 +333,11 @@ if options_.irf
                                 title(deblank(mylist((fig-1)*nstar+plt,:)),'Interpreter','none');
                             end
                         end
-                        dyn_saveas(hh,[M_.fname, '/graphs/'  M_.fname '_IRF_' tit{i} int2str(fig)],options_.nodisplay,options_.graph_format);
+                        dyn_saveas(hh,[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');
-                            fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_IRF_%s%s}\n',options_.figures.textwidth*min(plt/nc,1),[M_.fname, '/graphs/' M_.fname],tit{i},int2str(fig));
+                            fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_IRF_%s%s}\n',options_.figures.textwidth*min(plt/nc,1),[M_.dname, '/graphs/' M_.fname],tit{i},int2str(fig));
                             if options_.relative_irf
                                 fprintf(fidTeX,'\\caption{Relative impulse response functions (orthogonalized shock to $%s$).}', titTeX{i});
                             else
@@ -365,11 +365,11 @@ if options_.irf
                                 title(deblank(mylist((nbplt-1)*nstar+plt,:)),'Interpreter','none');
                             end
                     end
-                    dyn_saveas(hh,[M_.fname, '/graphs/' M_.fname '_IRF_' tit{i} int2str(nbplt) ],options_.nodisplay,options_.graph_format);
+                    dyn_saveas(hh,[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');
-                        fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_IRF_%s%s}\n',options_.figures.textwidth*min(m/lc,1),[M_.fname, '/graphs/' M_.fname],tit{i},int2str(nbplt));
+                        fprintf(fidTeX,'\\includegraphics[width=%2.2f\\textwidth]{%s_IRF_%s%s}\n',options_.figures.textwidth*min(m/lc,1),[M_.dname, '/graphs/' M_.fname],tit{i},int2str(nbplt));
                         if options_.relative_irf
                             fprintf(fidTeX,'\\caption{Relative impulse response functions (orthogonalized shock to $%s$).}', titTeX{i});
                         else
diff --git a/matlab/sylvester3a.m b/matlab/sylvester3a.m
index f286c8bdfc90dff3e289a63af5374073a8bf289a..cddcbc1ef3e63cbef320b52a044dd3acc1f94e4c 100644
--- a/matlab/sylvester3a.m
+++ b/matlab/sylvester3a.m
@@ -1,7 +1,7 @@
 function [x0, flag]=sylvester3a(x0,a,b,c,dd)
 % solves iteratively ax+bxc=d
 
-% Copyright (C) 2005-2017 Dynare Team
+% Copyright (C) 2005-2017,2020 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -25,7 +25,7 @@ for j=1:size(dd,3)
     d = a_1*dd(:,:,j);
     e = 1;
     iter = 1;
-    while e > 1e-8 && iter < 500
+    while all(e > 1e-8) && iter < 500 %use all() to get a logical in case e is empty
         x = d-b*x0(:,:,j)*c;
         e = max(max(abs(x-x0(:,:,j))));
         x0(:,:,j) = x;
diff --git a/matlab/test_for_deep_parameters_calibration.m b/matlab/test_for_deep_parameters_calibration.m
index 722ad65fcd440191b922679b9b5b257fb464f981..224db60efeee1624869d91ec2f373d17f576b9b3 100644
--- a/matlab/test_for_deep_parameters_calibration.m
+++ b/matlab/test_for_deep_parameters_calibration.m
@@ -42,7 +42,7 @@ if ~isempty(plist)
     end
     tmp = dbstack;
     message = [message, ' when using ' tmp(2).name '. '];
-    message = [message, 'If these parameters are not initialized in a steadystate file or a steady_state_model-block, Dynare may not be able to solve the model...'];
+    message = [message, 'If these parameters are not initialized in a steadystate file or a steady_state_model-block, Dynare may not be able to solve the model. Note that simul, perfect_foresight_setup, and perfect_foresight_solver do not automatically call the steady state file.'];
     message_id  = 'Dynare:ParameterCalibration:NaNValues';
     warning('off','backtrace')
     warning(message_id,message);
diff --git a/matlab/th_autocovariances.m b/matlab/th_autocovariances.m
index 66169d4a8e35b7794e0ea841c0fd875a8c2f5bff..29b70ff503fea7a6c2d5de2975452cba6d7c9903 100644
--- a/matlab/th_autocovariances.m
+++ b/matlab/th_autocovariances.m
@@ -143,8 +143,8 @@ if local_order == 2 || options_.hp_filter == 0
     stationary_vars = (1:length(ivar))';
     if ~isempty(u)
         x = abs(ghx*u);
-        iky = iky(find(all(x(iky,:) < options_.Schur_vec_tol,2)));
-        stationary_vars = find(all(x(inv_order_var(ivar(stationary_vars)),:) < options_.Schur_vec_tol,2));
+        iky = iky(find(all(x(iky,:) < options_.schur_vec_tol,2)));
+        stationary_vars = find(all(x(inv_order_var(ivar(stationary_vars)),:) < options_.schur_vec_tol,2));
     end
     aa = ghx(iky,:);
     bb = ghu(iky,:);
diff --git a/matlab/trace_plot.m b/matlab/trace_plot.m
index 310c2c3e89eb0a4e29716e6ae99210c04723b672..ec5d282a44b3f5a940a666797cd30576ee2ba612 100644
--- a/matlab/trace_plot.m
+++ b/matlab/trace_plot.m
@@ -115,12 +115,12 @@ plot(1:TotalNumberOfMhDraws,MovingAverage,'-k','linewidth',2)
 hold off
 axis tight
 legend({'MCMC draw';[num2str(N) ' period moving average']},'Location','NorthWest')
-% create subdirectory <fname>/graphs if it doesn't exist
-if ~exist(M_.fname, 'dir')
-    mkdir('.',M_.fname);
+% create subdirectory <dname>/graphs if it doesn't exist
+if ~exist(M_.dname, 'dir')
+    mkdir('.',M_.dname);
 end
-if ~exist([M_.fname filesep 'graphs'],'dir')
-    mkdir(M_.fname,'graphs');
+if ~exist([M_.dname filesep 'graphs'],'dir')
+    mkdir(M_.dname,'graphs');
 end
 
 %get name for plot
@@ -131,10 +131,10 @@ else
 end
 plot_name=[plot_name,'_blck_',num2str(blck)];
 
-dyn_saveas(hh,[M_.fname, filesep, 'graphs', filesep, 'TracePlot_' plot_name],options_.nodisplay,options_.graph_format)
+dyn_saveas(hh,[M_.dname, filesep, 'graphs', filesep, 'TracePlot_' plot_name],options_.nodisplay,options_.graph_format)
 
 if options_.TeX
-    fid=fopen([M_.fname,'/graphs/',M_.fname,'_TracePlot_' plot_name,'.tex'],'w+');
+    fid=fopen([M_.dname,'/graphs/',M_.fname,'_TracePlot_' plot_name,'.tex'],'w+');
 
     if strcmpi(type,'DeepParameter')
         tex_names=M_.param_names_tex;
@@ -162,7 +162,7 @@ if options_.TeX
 
     fprintf(fid,'%-s\n','\begin{figure}[H]');
     fprintf(fid,'%-s\n','\centering');
-    fprintf(fid,'%-s\n',['  \includegraphics[width=0.8\textwidth]{',[M_.fname, '/graphs/TracePlot_' plot_name],'}\\']);
+    fprintf(fid,'%-s\n',['  \includegraphics[width=0.8\textwidth]{',[M_.dname, '/graphs/TracePlot_' plot_name],'}\\']);
     fprintf(fid,'%-s\n',['    \caption{',FigureName,'}']);
     fprintf(fid,'%-s\n','\end{figure}');
     fclose(fid);
diff --git a/matlab/utilities/general/get_labels_transformed_vars.m b/matlab/utilities/general/get_labels_transformed_vars.m
new file mode 100644
index 0000000000000000000000000000000000000000..6c57c68ca63a0c435fc13c2f8952ddde1185eb06
--- /dev/null
+++ b/matlab/utilities/general/get_labels_transformed_vars.m
@@ -0,0 +1,46 @@
+function labels=get_labels_transformed_vars(endo_names,var_indices,options_,TeX)
+% function labels=get_labels_transformed_vars(endo_names,var_indices,options_,TeX)
+% This function provides the variable labels for table outputs in case of
+% applied transformations like logs
+%
+% INPUTS
+%   endo_names          [cell]        cell array of variable names
+%   var_indices         [double]      vector of variable indices
+%   options_            [structure]   Dynare structure containing the options
+%   TeX                 [boolean]     indicator for TeX-output
+% OUTPUTS
+%   labels              [cell]        cell array of variable labels
+%
+% Copyright (C) 2020 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 <http://www.gnu.org/licenses/>.
+
+if nargin<4
+    TeX=0;
+end
+if options_.loglinear
+    labels=[];
+    for var_iter=1:length(var_indices)
+        if TeX
+            labels{var_iter,1}=['\log(',endo_names{var_indices(var_iter)},')'];
+        else
+            labels{var_iter,1}=['log(',endo_names{var_indices(var_iter)},')'];
+        end
+    end
+else
+    labels = endo_names(var_indices);
+end
+end
\ No newline at end of file
diff --git a/matlab/write_latex_definitions.m b/matlab/write_latex_definitions.m
index 531e799cf6633699a9e381f4c47c6b5eecc18fc7..5f009b3b00ea57ae3a4b04718f30b0293d5dbf42 100644
--- a/matlab/write_latex_definitions.m
+++ b/matlab/write_latex_definitions.m
@@ -39,10 +39,10 @@ else
     M_var_root = {'M_.endo', 'M_.exo', 'M_.exo_det', 'M_.param'};
 end
 
-if ~exist([M_.fname '/latex'],'dir')
-    mkdir(M_.fname,'latex');
+if ~exist([M_.dname '/latex'],'dir')
+    mkdir(M_.dname,'latex');
 end
-fid = fopen([M_.fname, '/latex/' M_.fname '_latex_definitions.tex'], 'w');
+fid = fopen([M_.dname, '/latex/' M_.fname '_latex_definitions.tex'], 'w');
 for i=1:length(tables)
     fprintf(fid, '\\begin{center}\n');
     fprintf(fid, '\\begin{longtable}{ccc}\n');
diff --git a/matlab/write_latex_parameter_table.m b/matlab/write_latex_parameter_table.m
index 52124624031b52d19187f3714c315e9df517117a..6441a0410704de400812ca0272dadb2ef9a8ca71 100644
--- a/matlab/write_latex_parameter_table.m
+++ b/matlab/write_latex_parameter_table.m
@@ -37,11 +37,11 @@ if ~isequal(M_.param_names, M_.param_names_long)
     Long_names_present = true;
 end
 
-if ~exist([M_.fname '/latex'],'dir')
-    mkdir(M_.fname,'latex');
+if ~exist([M_.dname '/latex'],'dir')
+    mkdir(M_.dname,'latex');
 end
 
-fid = fopen([M_.fname, '/latex/' M_.fname '_latex_parameters.tex'], 'w');
+fid = fopen([M_.dname, '/latex/' M_.fname '_latex_parameters.tex'], 'w');
 fprintf(fid, '\\begin{center}\n');
 if Long_names_present==1
     fprintf(fid, '\\begin{longtable}{ccc}\n');
diff --git a/matlab/write_latex_prior_table.m b/matlab/write_latex_prior_table.m
index 3bae6d8c5c4568dfe12349973020e4dff1b8c2d9..5129597f5a264670afaac2af7e7c54777a0ffc91 100644
--- a/matlab/write_latex_prior_table.m
+++ b/matlab/write_latex_prior_table.m
@@ -54,10 +54,10 @@ ub=bounds.ub;
 
 PriorNames = { 'Beta' , 'Gamma' , 'Gaussian' , 'Inv. Gamma' , 'Uniform' , 'Inv. Gamma -- 2', '', 'Weibull' };
 
-if ~exist([M_.fname '/latex'],'dir')
-    mkdir(M_.fname,'latex');
+if ~exist([M_.dname '/latex'],'dir')
+    mkdir(M_.dname,'latex');
 end
-fidTeX = fopen([M_.fname, '/latex/' Model.fname '_priors_table.tex'],'w+');
+fidTeX = fopen([M_.dname, '/latex/' Model.fname '_priors_table.tex'],'w+');
 fprintf(fidTeX,'%% TeX-table generated by Dynare write_latex_prior_table.m.\n');
 fprintf(fidTeX,'%% Prior Information\n');
 fprintf(fidTeX,['%% ' datestr(now,0)]);
diff --git a/mex/build/matlab/configure.ac b/mex/build/matlab/configure.ac
index 24f0b2b13ab37d68657e7ffcbba17fe1d78ca6d9..c9460676a4172feab47f6c316d34f1c8f1b22cb1 100644
--- a/mex/build/matlab/configure.ac
+++ b/mex/build/matlab/configure.ac
@@ -51,7 +51,7 @@ CXXFLAGS="$MATLAB_CXXFLAGS -Wall -Wno-parentheses -Wold-style-cast"
 
 AC_PROG_FC
 AC_PROG_CC
-AC_PROG_CC_C99 # mjdgges DLL now uses C99 features (variable declared in for loop)
+AC_PROG_CC_C99
 AC_PROG_CXX
 AX_CXX_COMPILE_STDCXX_17
 AC_PROG_RANLIB
@@ -59,19 +59,6 @@ AX_PROG_LN_S
 AC_PROG_MKDIR_P
 AM_PROG_AR
 
-case ${host_os} in
-  *darwin*)
-    string=$($CXX --version)
-    if test "${string#*clang}" != "$string"; then
-      CXXFLAGS="$CXXFLAGS -stdlib=libc++"
-      MATLAB_LIBS="$MATLAB_LIBS -lc++"
-      MATLAB_LDFLAGS="$MATLAB_LDFLAGS -Wl,-syslibroot,$(xcrun -sdk macosx --show-sdk-path)"
-    else
-      MATLAB_LIBS="$MATLAB_LIBS -lstdc++"
-    fi
-    ;;
-esac
-
 AX_CXX11_THREAD
 
 # Check for dlopen(), needed by k_order_perturbation DLL
diff --git a/mex/build/octave/configure.ac b/mex/build/octave/configure.ac
index b764c3aa39bac55aaa98d157b8d3e63225435d4c..6f7f9391549c2f5a734ad47b57fcf70750778469 100644
--- a/mex/build/octave/configure.ac
+++ b/mex/build/octave/configure.ac
@@ -1,6 +1,6 @@
 dnl Process this file with autoconf to produce a configure script.
 
-dnl Copyright © 2009-2019 Dynare Team
+dnl Copyright © 2009-2020 Dynare Team
 dnl
 dnl This file is part of Dynare.
 dnl
@@ -28,8 +28,10 @@ test "$ax_enable_octave" != yes && AC_MSG_ERROR([Octave cannot be found])
 
 CC=$($MKOCTFILE -p CC)
 CXX=$($MKOCTFILE -p CXX)
+AR=$($MKOCTFILE -p AR)
+RANLIB=$($MKOCTFILE -p RANLIB)
 CFLAGS="$($MKOCTFILE -p CFLAGS) -Wall -Wno-parentheses"
-FCFLAGS="-g -O2 -Wall"
+FCFLAGS="$($MKOCTFILE -p FFLAGS) -Wall -std=gnu" # Override -std=legacy that is in FFLAGS in Octave 5
 FFLAGS="$($MKOCTFILE -p FFLAGS) -Wall"
 CXXFLAGS="$($MKOCTFILE -p CXXFLAGS) -Wall -Wno-parentheses -Wold-style-cast"
 LDFLAGS="$($MKOCTFILE -p LFLAGS) $($MKOCTFILE -p LDFLAGS)"
@@ -37,8 +39,8 @@ LDFLAGS="$($MKOCTFILE -p LFLAGS) $($MKOCTFILE -p LDFLAGS)"
 AC_CANONICAL_HOST
 case ${host_os} in
   darwin*)
-    CXXFLAGS="$($MKOCTFILE -p ALL_CXXFLAGS) -Wall -Wno-parentheses -Wold-style-cast -O2"
-    LDFLAGS+=" $($MKOCTFILE -p OCTAVE_LIBS)"
+    dnl The mkoctfile from Octave.app 4.4.1 does not add optimization flags in CXXFLAGS
+    CXXFLAGS+=" -O2"
     ;;
 esac
 
@@ -47,7 +49,7 @@ AX_COMPARE_VERSION([$OCTAVE_VERSION], [lt], [4.4], [AC_MSG_ERROR([Your Octave is
 
 AC_PROG_FC
 AC_PROG_CC
-AC_PROG_CC_C99 # mjdgges DLL now uses C99 features (variable declared in for loop)
+AC_PROG_CC_C99
 AC_PROG_CXX
 AX_CXX_COMPILE_STDCXX_17
 AC_PROG_RANLIB
@@ -93,6 +95,15 @@ fi
 AC_CHECK_LIB([umfpack], [umfpack_dl_defaults], [LIBADD_UMFPACK="-lumfpack"], [AC_MSG_ERROR([Can't find UMFPACK])])
 AC_SUBST([LIBADD_UMFPACK])
 
+# On Windows, we want static linking of the external libraries
+case ${host_os} in
+  *mingw32*)
+    GSL_LIBS="-Wl,-Bstatic $GSL_LIBS -Wl,-Bdynamic"
+    LIBADD_MATIO="-Wl,-Bstatic $LIBADD_MATIO -Wl,-Bdynamic"
+    LIBADD_SLICOT="-Wl,-Bstatic $LIBADD_SLICOT -Wl,-Bdynamic"
+    ;;
+esac
+
 # Construct final output message
 if test "$enable_mex_dynareplusplus" = yes; then
    BUILD_GENSYLV_KORDER_DYNSIMUL_MEX_OCTAVE="yes"
diff --git a/mex/build/octave/mex.am b/mex/build/octave/mex.am
index 1d8e1088f73ce2ed0bdc9328bb6c7ff37fc544da..77eccb3e7df62bc644d46f4e619ef933dc10b922 100644
--- a/mex/build/octave/mex.am
+++ b/mex/build/octave/mex.am
@@ -7,8 +7,9 @@ DEFS += -DMEXEXT=\".mex\"
 
 AM_CFLAGS = $(shell $(MKOCTFILE) -p CPICFLAG)
 AM_FFLAGS = $(shell $(MKOCTFILE) -p FPICFLAG)
+AM_FCFLAGS = $(shell $(MKOCTFILE) -p FPICFLAG)
 AM_CXXFLAGS = $(shell $(MKOCTFILE) -p CXXPICFLAG)
-AM_LDFLAGS = $(shell $(MKOCTFILE) -p DL_LDFLAGS)
+AM_LDFLAGS = $(shell $(MKOCTFILE) -p DL_LDFLAGS) -L"$(shell $(MKOCTFILE) -p OCTLIBDIR)"
 
 LIBS += $(shell $(MKOCTFILE) -p OCTAVE_LIBS)
 LIBS += $(shell $(MKOCTFILE) -p BLAS_LIBS)
diff --git a/mex/sources/blas_lapack.F08 b/mex/sources/blas_lapack.F08
index dfbff5cb8e0228f52ff74423d17a62e085dd8cdb..f2a1558b7389f35cb7d6920f800742734f70c9e6 100644
--- a/mex/sources/blas_lapack.F08
+++ b/mex/sources/blas_lapack.F08
@@ -29,7 +29,7 @@ module blas
   interface
      subroutine dgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy)
        import :: blint, real64
-       character :: trans
+       character, intent(in) :: trans
        integer(blint), intent(in) :: m, n, lda, incx, incy
        real(real64), dimension(*), intent(in) :: a, x
        real(real64), intent(in) :: alpha, beta
diff --git a/mex/sources/k_order_perturbation/k_order_perturbation.cc b/mex/sources/k_order_perturbation/k_order_perturbation.cc
index 4ae1151db72937c7deccb497838701d172c7a75b..c091db33993d7dd52bfc88d2c8c6b5fa273d00ff 100644
--- a/mex/sources/k_order_perturbation/k_order_perturbation.cc
+++ b/mex/sources/k_order_perturbation/k_order_perturbation.cc
@@ -121,6 +121,11 @@ extern "C" {
       mexErrMsgTxt("options_.threads.k_order_perturbation be a numeric scalar");
     int num_threads = static_cast<int>(mxGetScalar(num_threads_mx));
 
+    const mxArray *debug_mx = mxGetField(options_mx, 0, "debug");
+    if (!(debug_mx && mxIsLogicalScalar(debug_mx)))
+      mexErrMsgTxt("options_.debug should be a logical scalar");
+    bool debug = static_cast<bool>(mxGetScalar(debug_mx));
+
     // Extract various fields from M_
     const mxArray *fname_mx = mxGetField(M_mx, 0, "fname");
     if (!(fname_mx && mxIsChar(fname_mx) && mxGetM(fname_mx) == 1))
@@ -197,7 +202,10 @@ extern "C" {
 
     try
       {
-        Journal journal(fname + ".jnl");
+        // Journal is not written on-disk, unless options_.debug = true (see #1735)
+        Journal journal;
+        if (debug)
+          journal = Journal{fname + ".jnl"};
 
         std::unique_ptr<DynamicModelAC> dynamicModelFile;
         if (use_dll)
diff --git a/mex/sources/perfect_foresight_problem/perfect_foresight_problem.cc b/mex/sources/perfect_foresight_problem/perfect_foresight_problem.cc
index c813b1697aa54f1236e2d9ad0a398c03f5c0fe28..52fa7e88ed4c7135fb5e33e7504533fff98d95f4 100644
--- a/mex/sources/perfect_foresight_problem/perfect_foresight_problem.cc
+++ b/mex/sources/perfect_foresight_problem/perfect_foresight_problem.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright © 2019 Dynare Team
+ * Copyright © 2019-2020 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -101,7 +101,8 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
 
   // Call <model>.dynamic_g1_nz
   mxArray *g1_nz_plhs[3];
-  mexCallMATLAB(3, g1_nz_plhs, 0, nullptr, (basename + ".dynamic_g1_nz").c_str());
+  if (mexCallMATLAB(3, g1_nz_plhs, 0, nullptr, (basename + ".dynamic_g1_nz").c_str()) != 0)
+    mexErrMsgTxt((std::string{"Could not call "} + basename + ".dynamic_g1_nz").c_str());
   const mxArray *nzij_pred_mx = g1_nz_plhs[0];
   const mxArray *nzij_current_mx = g1_nz_plhs[1];
   const mxArray *nzij_fwrd_mx = g1_nz_plhs[2];
diff --git a/preprocessor b/preprocessor
index ffef9ef0b37cfd71dcecdceffecc6711f2faded9..623855f5741dee9535d233546fc49706fd67b02e 160000
--- a/preprocessor
+++ b/preprocessor
@@ -1 +1 @@
-Subproject commit ffef9ef0b37cfd71dcecdceffecc6711f2faded9
+Subproject commit 623855f5741dee9535d233546fc49706fd67b02e
diff --git a/scripts/dynare.el b/scripts/dynare.el
index a25179886301905ad8d9218dac995a7f4ff51be5..536dc8ded315107228893eea37e7dc7a6598b203 100644
--- a/scripts/dynare.el
+++ b/scripts/dynare.el
@@ -56,7 +56,7 @@
 (defvar dynare-statements
   '("var" "varexo" "varexo_det" "trend_var" "log_trend_var"
     "predetermined_variables" "parameters" "model_local_variable" "periods"
-    "model_info" "estimation" "var_estimation" "set_time" "data" "varobs"
+    "model_info" "estimation" "set_time" "data" "varobs"
     "varexobs" "unit_root_vars" "rplot" "osr_params" "osr" "dynatype"
     "dynasave" "model_comparison" "change_type" "load_params_and_steady_state"
     "save_params_and_steady_state" "write_latex_dynamic_model"
@@ -82,8 +82,7 @@
 ;; Keywords that may appear in blocks, and that begin a statement which will be
 ;; closed by a semicolon
 (defvar dynare-statements-like
-  '("stderr" "values" "restriction" "exclusion" "equation" "crossequations"
-    "covariance" "upper_cholesky" "lower_cholesky")
+  '("stderr" "values" "restriction" "exclusion" "upper_cholesky" "lower_cholesky")
   "Dynare statements-like keywords.")
 
 ;; Those keywords that makes the lexer enter the DYNARE_BLOCK start condition
@@ -97,7 +96,7 @@
       "estimated_params_init" "estimated_params_bounds" "osr_params_bounds"
       "observation_trends" "optim_weights" "homotopy_setup"
       "conditional_forecast_paths" "svar_identification" "moment_calibration"
-      "irf_calibration" "ramsey_constraints" "restrictions" "generate_irfs"
+      "irf_calibration" "ramsey_constraints" "generate_irfs"
       "matched_moments" "verbatim")
     "Dynare block keywords."))
 
diff --git a/tests/.gitignore b/tests/.gitignore
index 39a67982e2bb9f7066190782df394983aa9bc9d7..7b5c438826aa63ae6af5d7cbf06ab5aa013605b8 100644
--- a/tests/.gitignore
+++ b/tests/.gitignore
@@ -50,8 +50,10 @@ wsOct
 !/ep/mean_preserving_spread.m
 !/ep/rbcii_steady_state.m
 !/estimation/fsdat_simul.m
-!/estimation/method_of_moments/RBC_MoM_steady_helper.m
-!/estimation/method_of_moments/RBC_Andreasen_Data_2.mat
+!/estimation/method_of_moments/RBC/RBC_MoM_steady_helper.m
+!/estimation/method_of_moments/RBC/RBC_Andreasen_Data_2.mat
+!/estimation/method_of_moments/AFVRR/AFVRR_data.mat
+!/estimation/method_of_moments/AFVRR/AFVRR_steady_helper.m
 !/expectations/expectation_ss_old_steadystate.m
 !/external_function/extFunDeriv.m
 !/external_function/extFunNoDerivs.m
diff --git a/tests/Makefile.am b/tests/Makefile.am
index 9c46c69852d35148a663dbf85c5308961445a436..ee55632067859ee6627e93f755f5cf67b2b06b94 100644
--- a/tests/Makefile.am
+++ b/tests/Makefile.am
@@ -3,7 +3,10 @@ MODFILES = \
 	optimizers/fs2000_6.mod \
 	moments/example1_hp_test.mod \
 	moments/fs2000_post_moments.mod \
+	moments/example1_order2_pruning.mod \
 	lmmcp/rbcii.mod \
+	lmmcp/purely_backward.mod \
+	lmmcp/purely_forward.mod \
 	ep/rbc_mc.mod \
 	estimation/TaRB/fs2000_tarb.mod \
 	observation_trends_and_prefiltering/MCMC/Trend_loglin_no_prefilt_first_obs_MC.mod \
@@ -48,10 +51,14 @@ MODFILES = \
 	estimation/MH_recover/fs2000_recover_3.mod \
 	estimation/t_proposal/fs2000_student.mod \
 	estimation/tune_mh_jscale/fs2000.mod \
-	estimation/method_of_moments/AnScho_MoM.mod \
-	estimation/method_of_moments/RBC_MoM_Andreasen.mod \
-	estimation/method_of_moments/RBC_MoM_SMM_ME.mod \
-	estimation/method_of_moments/RBC_MoM_prefilter.mod \
+	estimation/method_of_moments/AnScho/AnScho_MoM.mod \
+	estimation/method_of_moments/RBC/RBC_MoM_Andreasen.mod \
+	estimation/method_of_moments/RBC/RBC_MoM_SMM_ME.mod \
+	estimation/method_of_moments/RBC/RBC_MoM_prefilter.mod \
+	estimation/method_of_moments/RBC/RBC_MoM_optimizer.mod \
+	estimation/method_of_moments/AFVRR/AFVRR_M0.mod \
+	estimation/method_of_moments/AFVRR/AFVRR_MFB.mod \
+	estimation/method_of_moments/AFVRR/AFVRR_MFB_RRA.mod \
 	moments/example1_var_decomp.mod \
 	moments/example1_bp_test.mod \
 	moments/test_AR1_spectral_density.mod \
@@ -62,6 +69,8 @@ MODFILES = \
 	ramst.mod \
 	ramst_a.mod \
 	ramst_static_tag.mod \
+	ramst_static_tag_block.mod \
+	ramst_mshocks.mod \
 	on-the-fly/ex1.mod \
 	on-the-fly/ex2.mod \
 	on-the-fly/ex3.mod \
@@ -74,12 +83,13 @@ MODFILES = \
 	example1_with_tags.mod \
 	example1_irf_shocks.mod \
 	example1_abs_sign.mod \
-	example1_macro.mod \
 	example1_mlv.mod \
 	example1long.mod \
 	example2long.mod \
 	example2long_use_dll.mod \
 	t_sgu_ex1.mod \
+	macro_processor/test_ifndef.mod \
+	macro_processor/example1_macro.mod \
 	irfs/example1_unit_std.mod \
 	optimal_policy/OSR/osr_example.mod \
 	optimal_policy/OSR/osr_example_objective_correctness.mod \
@@ -109,6 +119,8 @@ MODFILES = \
 	discretionary_policy/dennis_1.mod \
 	discretionary_policy/dennis_1_estim.mod \
 	discretionary_policy/Gali_discretion.mod \
+	discretionary_policy/Gali_2015_chapter_3.mod \
+	discretionary_policy/Gali_2015_chapter_3_nonlinear.mod \
 	histval_initval_file/ramst_initval_file.mod \
 	histval_initval_file/ramst_data.mod \
 	histval_initval_file/ramst_datafile.mod \
@@ -217,6 +229,7 @@ MODFILES = \
 	identification/rbc_ident/rbc_ident_std_as_structural_par.mod \
 	identification/rbc_ident/rbc_ident_varexo_only.mod \
 	identification/correlated_errors/fs2000_corr.mod \
+	identification/forward_looking/forward_looking.mod \
 	simul/example1.mod \
 	simul/Solow_no_varexo.mod \
 	simul/simul_ZLB_purely_forward.mod \
@@ -292,6 +305,7 @@ MODFILES = \
 	ep/rbcii.mod \
 	ep/linearmodel0.mod \
 	ep/linearmodel1.mod \
+	ep/rbc_bytecode.mod \
 	stochastic_simulations/example1_noprint.mod \
 	stochastic-backward-models/solow_cd.mod \
 	stochastic-backward-models/solow_ces.mod \
@@ -318,6 +332,10 @@ MODFILES = \
 	deterministic_simulations/multiple_lead_lags/sim_lead_lag_aux_vars.mod \
 	deterministic_simulations/multiple_lead_lags/sim_lead_lag.mod \
 	deterministic_simulations/lola_solve_one_boundary.mod \
+	deterministic_simulations/lola_solve_one_boundary_mfs1.mod \
+	deterministic_simulations/lola_solve_one_boundary_mfs2.mod \
+	deterministic_simulations/lola_solve_one_boundary_mfs3.mod \
+	deterministic_simulations/ramst_block_mfs1.mod \
 	deterministic_simulations/linear_approximation/sw.mod \
 	deterministic_simulations/multiple_lead_lags/AR2.mod \
 	deterministic_simulations/multiple_lead_lags/AR2_forward.mod \
@@ -554,8 +572,7 @@ XFAIL_MODFILES = ramst_xfail.mod \
 	estimation/tune_mh_jscale/fs2000_1_xfail.mod \
 	estimation/tune_mh_jscale/fs2000_2_xfail.mod
 
-MFILES = histval_initval_file/ramst_initval_file_data.m \
-	 histval_initval_file_unit_tests.m
+MFILES = histval_initval_file/ramst_initval_file_data.m
 
 # Dependencies
 example1_use_dll.m.trs: example1.m.trs
@@ -671,6 +688,13 @@ deterministic_simulations/rbc_det_stack_solve_algo_7_exo_lead.m.trs: determinist
 deterministic_simulations/rbc_det_stack_solve_algo_7_exo_lead.o.trs: deterministic_simulations/rbc_det.o.trs
 deterministic_simulations/rbc_det_stack_solve_algo_7_exo_lag.m.trs: deterministic_simulations/rbc_det.m.trs
 deterministic_simulations/rbc_det_stack_solve_algo_7_exo_lag.o.trs: deterministic_simulations/rbc_det.o.trs
+deterministic_simulations/lola_solve_one_boundary_mfs1.m.trs: deterministic_simulations/lola_solve_one_boundary.m.trs
+deterministic_simulations/lola_solve_one_boundary_mfs1.o.trs: deterministic_simulations/lola_solve_one_boundary.o.trs
+deterministic_simulations/lola_solve_one_boundary_mfs2.m.trs: deterministic_simulations/lola_solve_one_boundary.m.trs
+deterministic_simulations/lola_solve_one_boundary_mfs2.o.trs: deterministic_simulations/lola_solve_one_boundary.o.trs
+deterministic_simulations/lola_solve_one_boundary_mfs3.m.trs: deterministic_simulations/lola_solve_one_boundary.m.trs
+deterministic_simulations/lola_solve_one_boundary_mfs3.o.trs: deterministic_simulations/lola_solve_one_boundary.o.trs
+
 
 histval_initval_file/ramst_initval_file.m.trs: histval_initval_file/ramst_initval_file_data.m.tls histval_initval_file/ramst_data.m.trs
 histval_initval_file/ramst_initval_file.o.trs: histval_initval_file/ramst_initval_file_data.o.tls histval_initval_file/ramst_data.o.trs
@@ -790,6 +814,8 @@ trend-component-and-var-models/tcm8.o.trs: trend-component-and-var-models/tcm6.o
 
 discretionary_policy/dennis_1_estim.m.trs: discretionary_policy/dennis_1.m.trs
 discretionary_policy/dennis_1_estim.o.trs: discretionary_policy/dennis_1.o.trs
+discretionary_policy/Gali_2015_chapter_3_nonlinear.m.trs: discretionary_policy/Gali_2015_chapter_3.m.trs
+discretionary_policy/Gali_2015_chapter_3_nonlinear.o.trs: discretionary_policy/Gali_2015_chapter_3.o.trs
 
 matrix_notation/deterministic_scalar.m.trs: matrix_notation/deterministic_matrix.m.trs
 matrix_notation/deterministic_scalar.o.trs: matrix_notation/deterministic_matrix.o.trs
@@ -1008,6 +1034,10 @@ particle: m/particle o/particle
 m/particle: $(patsubst %.mod, %.m.trs, $(PARTICLEFILES))
 o/particle: $(patsubst %.mod, %.o.trs, $(PARTICLEFILES))
 
+method_of_moments: m/method_of_moments o/method_of_moments
+m/method_of_moments: $(patsubst %.mod, %.m.trs, $(filter estimation/method_of_moments/%.mod, $(MODFILES)))
+o/method_of_moments: $(patsubst %.mod, %.o.trs, $(filter estimation/method_of_moments/%.mod, $(MODFILES)))
+
 ecb: m/ecb o/ecb
 m/ecb: $(patsubst %.mod, %.m.trs, $(filter ecb/%.mod, $(MODFILES)))
 o/ecb: $(patsubst %.mod, %.o.trs, $(filter ecb/%.mod, $(MODFILES)))
@@ -1177,6 +1207,10 @@ EXTRA_DIST = \
 	lmmcp/sw-common-header.inc \
 	lmmcp/sw-common-footer.inc \
 	estimation/tune_mh_jscale/fs2000.inc \
+	estimation/method_of_moments/RBC/RBC_MoM_common.inc \
+	estimation/method_of_moments/RBC/RBC_MoM_steady_helper.m \
+	estimation/method_of_moments/AFVRR/AFVRR_common.inc \
+	estimation/method_of_moments/AFVRR/AFVRR_steady_helper.m \
 	estimation/univariate/data.csv \
 	estimation/univariate/ols/mc-ols.inc \
 	ecb/SURGibbs/fishdata.csv \
@@ -1197,8 +1231,6 @@ EXTRA_DIST = \
 	ecb/aggregate/3/parameters.inc \
 	ecb/aggregate/3/parameter-values.inc \
 	ecb/aggregate/3/model.inc \
-	estimation/method_of_moments/RBC_MoM_common.inc \
-	estimation/method_of_moments/RBC_MoM_steady_helper.m \
 	histval_initval_file_unit_tests.m \
 	histval_initval_file/my_assert.m \
 	histval_initval_file/ramst_data.xls \
diff --git a/tests/bgp/fs2000/fs2000.mod b/tests/bgp/fs2000/fs2000.mod
index e5ef2fc4994806565f29838bd906f637db6a9d84..4a6da499da949b4f234e69ea926937c4ad56bf3f 100644
--- a/tests/bgp/fs2000/fs2000.mod
+++ b/tests/bgp/fs2000/fs2000.mod
@@ -62,10 +62,19 @@ end;
 verbatim;
 
     bgp.write(M_);
-    options = optimoptions('fsolve','Display','iter','Algorithm','levenberg-marquardt','MaxFunctionEvaluations',1000000,'MaxIterations',100000,'SpecifyObjectiveGradient',true,'FunctionTolerance',1e-6,'StepTolerance',1e-6);
-    y = 1+(rand(M_.endo_nbr,1)-.5)*.5;
+    y = 1+(rand(M_.endo_nbr,1)-.5)*.25;
     g = ones(M_.endo_nbr,1);% 1+(rand(M_.endo_nbr,1)-.5)*.1;
-    [y, fval, exitflag] = fsolve(@fs2000.bgpfun, [y;g], options);
+    if ~isoctave
+        options = optimoptions('fsolve','Display','iter','Algorithm','levenberg-marquardt','MaxFunctionEvaluations',1000000,'MaxIterations',100000,'SpecifyObjectiveGradient',true,'FunctionTolerance',1e-6,'StepTolerance',1e-6);
+        [y, fval, exitflag] = fsolve(@fs2000.bgpfun, [y;g], options);
+    else
+        options = optimset('Display','iter','Algorithm','levenberg-marquardt','MaxFunEvals',1000000,'MaxIter',100000,'GradObj','on','TolFun',1e-6,'TolX',1e-6);
+        h=str2func('fs2000.bgpfun'); %workaround for https://savannah.gnu.org/bugs/?46659 still present in Octave 5
+        [y, fval, exitflag] = fsolve(h, [y;g], options);
+    end
+    if exitflag<1
+        error('Solution not found')
+    end
     y(1:M_.orig_endo_nbr)
     y(M_.endo_nbr+(1:M_.orig_endo_nbr))
 
diff --git a/tests/bgp/ramsey-1/ramsey.mod b/tests/bgp/ramsey-1/ramsey.mod
index 0a66aa14f190fcdd2d0addcd62d47bfb220cb8b6..42595edec09aaf3f288ef3f92d999501aee0d60d 100644
--- a/tests/bgp/ramsey-1/ramsey.mod
+++ b/tests/bgp/ramsey-1/ramsey.mod
@@ -17,7 +17,7 @@ verbatim;
 
     bgp.write(M_);
     if isoctave
-        options = optimset('Display', 'iter', 'MaxFunEvals', 1000000,'MaxIter',100000,'Jacobian','on','TolFun',1e-6,'TolX',1e-6);
+        options = optimset('Display', 'iter', 'MaxFunEvals', 1000000,'MaxIter',100000,'Jacobian','on','TolFun',1e-7,'TolX',1e-7);
     else
         options = optimoptions('fsolve','Display','iter','Algorithm','levenberg-marquardt','MaxFunctionEvaluations',1000000,'MaxIterations',100000,'SpecifyObjectiveGradient',true,'FunctionTolerance',1e-6,'StepTolerance',1e-6);
     end
@@ -28,7 +28,7 @@ verbatim;
     else
         fun = @ramsey.bgpfun;
     end
-    y = 1+(rand(M_.endo_nbr,1)-.5)*.5;
+    y = 1+(rand(M_.endo_nbr,1)-.5)*.25;
     g = ones(M_.endo_nbr,1);% 1+(rand(M_.endo_nbr,1)-.5)*.1;
     [y, fval, exitflag] = fsolve(fun, [y;g], options);
     assert(max(abs(y(M_.endo_nbr+(1:M_.orig_endo_nbr))-1.02))<1e-6)
diff --git a/tests/conditional_variance_decomposition/example1.mod b/tests/conditional_variance_decomposition/example1.mod
index 039fa99ab478e4996662de23c8322e0c6c490a06..880a465e8ba433126f9a46d21cefb324682615a5 100644
--- a/tests/conditional_variance_decomposition/example1.mod
+++ b/tests/conditional_variance_decomposition/example1.mod
@@ -76,7 +76,7 @@ for i=1:nvar
     SubsetOfVariables(i) = i_tmp;
 end
 
-if isoctave
+if isoctave && octave_ver_less_than('6')
     [observable_pos,index_observables,index_subset]=intersect_stable(SubsetOfVariables,options_.varobs_id);
 else
     [observable_pos,index_observables,index_subset]=intersect(SubsetOfVariables,options_.varobs_id,'stable');
@@ -114,7 +114,7 @@ if max(abs(sum(oo_.variance_decomposition,2)-100))>2
     error(['Variance decomposition at order ',num2str(options_.order),' does not work'])
 end
 
-if isoctave
+if isoctave && octave_ver_less_than('6')
     [observable_pos,index_observables,index_subset]=intersect_stable(SubsetOfVariables,options_.varobs_id);
 else
     [observable_pos,index_observables,index_subset]=intersect(SubsetOfVariables,options_.varobs_id,'stable');
diff --git a/tests/deterministic_simulations/lola_solve_one_boundary.mod b/tests/deterministic_simulations/lola_solve_one_boundary.mod
index a293647fcd4fcfa26d219caef9887cfa1042585b..6930b4d7240974198371bffd9a3a762c02e2c171 100644
--- a/tests/deterministic_simulations/lola_solve_one_boundary.mod
+++ b/tests/deterministic_simulations/lola_solve_one_boundary.mod
@@ -972,7 +972,8 @@ end;
 % Numerical Simulation, Control Parameters
 % *******************************************
 
-simul(periods=125,maxit=100);
+perfect_foresight_setup(periods=125);
+perfect_foresight_solver(maxit=100);
 
 if ~oo_.deterministic_simulation.status
    error('Perfect foresight simulation failed')
diff --git a/tests/deterministic_simulations/lola_solve_one_boundary_mfs1.mod b/tests/deterministic_simulations/lola_solve_one_boundary_mfs1.mod
new file mode 100644
index 0000000000000000000000000000000000000000..2554539c56a44748aabdb6b94f8164f9e9a0c8c7
--- /dev/null
+++ b/tests/deterministic_simulations/lola_solve_one_boundary_mfs1.mod
@@ -0,0 +1,987 @@
+// Tests option mfs=1 with block
+
+load lola_data.mat
+
+% ====================================================
+% declarations var -- varexo -- para   
+% ====================================================
+
+@#define nbr_work_generations=9
+@#define nbr_early_generations=2
+@#define nbr_generations=16
+
+parameters
+length_period age_early;
+
+length_period=5;
+age_early=55;
+
+@#define wt=[1]
+
+@#define wg=0:nbr_work_generations-1
+@#define ag=0:nbr_generations-1
+@#define fwg=0:nbr_work_generations-nbr_early_generations-1
+@#define nbwg=1:nbr_work_generations-1
+@#define nbg=1:nbr_generations-1
+@#define rg=nbr_work_generations:nbr_generations-1
+@#define erg=nbr_work_generations-nbr_early_generations:nbr_work_generations-1
+@#define endg=[nbr_generations-1]
+@#define endw=[nbr_work_generations-1]
+
+@#for i in wg
+var 
+n@{i} u@{i} Omega@{i} w@{i} dWHN@{i} dWFN@{i} 
+n@{i}_f u@{i}_f Omega@{i}_f w@{i}_f dWFN@{i}_f
+i@{i} lambda@{i} i@{i}_f lambda@{i}_f eta@{i};
+parameters
+Du@{i} Dn@{i} h@{i} h@{i}_f chi@{i} eta@{i}b; 
+varexo
+eps_eta@{i};
+@#endfor
+
+@#for i in ag
+var 
+c@{i} s@{i} P@{i} P@{i}_f;
+varexo
+beta@{i} beta@{i}_f PD@{i};
+@#endfor
+
+@#for i in erg
+var 
+WE@{i} De_@{i};
+parameters
+De_@{i}b; 
+varexo
+eps_De_@{i};
+@#endfor
+
+var   
+wb wb_f 
+Omega Omega_f Omega_hf 
+V M qq p 
+N N_f 
+Q RR H K Y gdp nx FH pi
+ct st wshare rr 
+gamma mc phii D DH DF X bs bsY P00_f
+
+rhou rhoe rhol tauw tauc tauf tauk g 
+TFP gh rrb
+theta tau1 om1 om2 om2s Ds phijs
+
+DepRatio DepRatio_n DepRatio_d ZARA Ptot Ptot_f sleep du de dl inA inB in 
+NBR NBRY NBR2 tauw2 tauf2 tauc2
+PensCorr_L PensCorr_F;
+
+parameters 
+rho phi delta alpha beta ann 
+fc nu aa 
+
+rhoub rhoeb rholb tauwb taucb taufb taukb gb  
+TFPb ghb rrbb
+thetab tau1b om1b om2b om2sb Dsb phijsb
+
+NBRYb bsY_iss;
+
+varexo
+P00 P00_foP00
+
+eps_rhol eps_tauw eps_tauf eps_tauc eps_tauk
+eps_rhoe eps_rhou eps_TFP eps_gh eps_theta eps_g
+eps_Ds eps_phijs eps_PensCorr_L eps_PensCorr_F;
+
+
+% ============================================================
+% initialization
+% ============================================================
+
+@#for i in wg
+set_param_value('Du@{i}',Du@{i});
+set_param_value('Dn@{i}',Dn@{i});
+set_param_value('h@{i}',h@{i});
+set_param_value('h@{i}_f',h@{i}_f);
+set_param_value('chi@{i}',chi@{i});
+set_param_value('eta@{i}b',eta@{i}b);
+@#endfor
+
+@#for i in erg
+set_param_value('De_@{i}b',De_@{i}b);
+@#endfor
+
+set_param_value('rho',rho);
+set_param_value('phi',phi);
+set_param_value('delta',delta);
+set_param_value('alpha',alpha);
+set_param_value('beta',beta);
+set_param_value('ann',ann);
+set_param_value('fc',fc);
+set_param_value('nu',nu);
+set_param_value('aa',aa);
+
+set_param_value('rhoub',rhoub);
+set_param_value('rhoeb',rhoeb);
+set_param_value('rholb',rholb);
+set_param_value('tauwb',tauwb);
+set_param_value('taucb',taucb);
+set_param_value('taufb',taufb);
+set_param_value('taukb',taukb);
+set_param_value('gb',gb);
+
+set_param_value('TFPb',TFPb);
+set_param_value('ghb',ghb);
+set_param_value('rrbb',rrbb);
+
+set_param_value('thetab',thetab);
+set_param_value('tau1b',tau1b);
+set_param_value('om1b',om1b);
+set_param_value('om2b',om2b);
+set_param_value('om2sb',om2sb);
+set_param_value('Dsb',Dsb);
+set_param_value('phijsb',phijsb);
+
+set_param_value('bsY_iss',bsY_iss);
+
+NBRYb=NBR_iss/(phii_iss*gdp_iss);
+
+
+% =======================================================
+model(block, mfs=1);
+% ======================================================
+
+%  Labor Market Variables in the home country
+%  ------------------------------------------ 
+
+@#for i in fwg
+0=lambda@{i};
+@#endfor
+
+@#for i in wg
+1=n@{i}+u@{i}+i@{i};
+@#endfor   
+                            
+i0=lambda0;
+@#for i in nbwg
+i@{i}=lambda@{i-1}(-1)+lambda@{i}*(1-lambda@{i-1}(-1));
+@#endfor 
+
+P0=beta0*P00+PD0;
+@#for i in nbg
+P@{i}=beta@{i}*P@{i-1}(-1)+PD@{i};
+@#endfor
+
+Omega0=P0;
+@#for i in nbwg
+Omega@{i}=(1-lambda@{i})*( 1-lambda@{i-1}(-1)-(1-chi@{i})*n@{i-1}(-1))*P@{i};
+@#endfor 
+
+n0=p;
+@#for i in nbwg
+n@{i}=(1-lambda@{i})*((1-p)*(1-chi@{i})*n@{i-1}(-1)+p*(1-lambda@{i-1}(-1)));
+@#endfor 
+
+N=
+@#for i in wg
++n@{i}*P@{i}
+@#endfor
+;
+
+%  Labor Market Variables in the foreign country
+%  --------------------------------------------- 
+
+@#for i in wg
+1=n@{i}_f+u@{i}_f+i@{i}_f;
+@#endfor    
+                            
+i0_f=lambda0_f;
+@#for i in nbwg
+i@{i}_f=lambda@{i-1}_f(-1)+lambda@{i}_f*(1-lambda@{i-1}_f(-1));
+@#endfor
+
+% -----------  reproduction cross-border   --------------------
+
+P00_f=P00_foP00*P00;
+
+P0_f=beta0_f*P00_f;
+@#for i in nbg
+P@{i}_f=beta@{i}_f*P@{i-1}_f(-1);
+@#endfor 
+
+Omega0_f=P0_f;
+@#for i in nbwg
+Omega@{i}_f=(1-lambda@{i}_f)*(1-lambda@{i-1}_f(-1)-(1-chi@{i})*n@{i-1}_f(-1))*P@{i}_f;
+@#endfor 
+
+n0_f=p;
+@#for i in nbwg
+n@{i}_f=(1-lambda@{i}_f)*((1-p)*(1-chi@{i})*n@{i-1}_f(-1)+p*(1-lambda@{i-1}_f(-1)));
+@#endfor
+
+N_f=
+@#for i in wg
++n@{i}_f*P@{i}_f
+@#endfor
+;
+
+%  Matching
+% ----------
+
+Omega=
+@#for i in wg
++Omega@{i}
+@#endfor
+;
+
+Omega_f=
+@#for i in wg
++Omega@{i}_f
+@#endfor
+;
+
+Omega_hf=Omega+Omega_f;
+ 
+M=V*Omega_hf/(V^nu+Omega_hf^nu)^(1/nu);
+
+qq=M/V;
+p=M/Omega_hf;
+
+%  Flow Budget Constraints (no bequests)
+% --------------------------------------
+
+rhou*w0*u0+ (1-tauw)*w0*n0 = (1+tauc)*c0+s0;
+@#for i in nbwg
+(1+rr*(1-tauk))/(beta@{i})^ann*s@{i-1}(-1)/(1+gh)+rhou*w@{i}*u@{i}+rhoe*w@{i}*i@{i}+(1-tauw)*w@{i}*n@{i}=(1+tauc)*c@{i}+s@{i};
+@#endfor
+@#for i in rg
+(1+rr*(1-tauk))/(beta@{i})^ann*s@{i-1}(-1)/(1+gh)+rhol*wb=(1+tauc)*c@{i}+s@{i};
+@#endfor
+@#for i in endg
+s@{i}=0;
+@#endfor
+
+wb=
+@#for i in wg
++w@{i}/@{nbr_work_generations}
+@#endfor
+;
+
+%  Euler Conditions
+% ------------------
+
+@#for i in nbg
+1/(1+tauc)/c@{i-1}=beta*(1+rr(+1)*(1-tauk(+1)))/(1+tauc(+1))/c@{i}(+1)*(beta@{i})^(1-ann)/(1+gh);
+@#endfor
+
+
+%  Optimal Participation Rates (Early Retirement)
+%  ----------------------------------------------
+
+@#for i in erg
+WE@{i} = 0;
+@#endfor 
+
+@#for i in erg
+@#if i in endw
+WE@{i} = ((De_@{i}b*i@{i}^(phi-1))+Du@{i}+(rhoe-rhou)*w@{i}/(1+tauc)/c@{i})*(1-i@{i})-((1-tauw-rhou)*w@{i}/(1+tauc)/c@{i}-(Dn@{i}-Du@{i}))*n@{i};
+@#else  
+WE@{i} = ((De_@{i}b*i@{i}^(phi-1))+Du@{i}+(rhoe-rhou)*w@{i}/(1+tauc)/c@{i})*(1-i@{i})-((1-tauw-rhou)*w@{i}/(1+tauc)/c@{i}-(Dn@{i}-Du@{i}))*n@{i}+ beta*beta@{i+1}*WE@{i+1};
+@#endif
+@#endfor  
+
+%  Household Surplus
+% -------------------
+
+@#for i in wg
+@#if i in endw
+dWHN@{i} = w@{i}*(1-tauw-rhou)/(1+tauc)-(Dn@{i}-Du@{i})*c@{i};
+@#else  
+dWHN@{i} = w@{i}*(1-tauw-rhou)/(1+tauc)-(Dn@{i}-Du@{i})*c@{i} + beta*beta@{i+1}*c@{i}/c@{i+1}(+1)*dWHN@{i+1}(+1)*(1-p(+1))*(1-chi@{i+1})*(1-lambda@{i+1}(+1));
+@#endif
+@#endfor    
+
+%  Foreign household
+%  ------------------------
+%  participation and wages
+% ........................
+
+@#for i in wg
+lambda@{i}=lambda@{i}_f;
+w@{i}_f=w@{i}; 
+@#endfor
+
+wb_f=
+@#for i in wg
++w@{i}_f/@{nbr_work_generations}
+@#endfor
+;
+
+%  Firm's Behavior
+% -------------------
+
+H=
+@#for i in wg
++h@{i}*n@{i}*P@{i}+h@{i}_f*n@{i}_f*P@{i}_f
+@#endfor
+;
+
+wshare=(1+tauf)*(
+@#for i in wg
++w@{i}*n@{i}*P@{i}+w@{i}_f*n@{i}_f*P@{i}_f
+@#endfor
+)/(phii*gdp);
+
+Y=TFP*H^(1-alpha)*(K)^alpha;
+gdp= TFP*H^(1-alpha)*(K)^alpha-aa*V/phii-fc/phii;
+pi = phii*gdp - wshare*phii*gdp - (rr+delta)*K(-1)/(1+gh);
+(rr(+1)+delta)/(1+rr(+1)*(1-tauk(+1))) = mc*TFP*alpha*(H/(K))^(1-alpha);
+FH=TFP*(1-alpha)*((K)/H)^alpha;
+
+RR=1+rr*(1-tauk);
+rr=rrb+tau1*(exp(bsY_iss-bsY)-1);
+
+%  Firm's Surplus
+%  ---------------------
+
+@#for i in wg
+@#if i in endw
+dWFN@{i} = h@{i}*mc*FH-(1+tauf)*w@{i};
+dWFN@{i}_f = h@{i}_f*mc*FH-(1+tauf)*w@{i}_f;
+@#else  
+dWFN@{i} = h@{i}*mc*FH-(1+tauf)*w@{i} + beta@{i+1}/RR(+1)*dWFN@{i+1}(+1)*(1-chi@{i+1})*(1-lambda@{i+1}(+1))*(1+gh);
+dWFN@{i}_f = h@{i}_f*mc*FH-(1+tauf)*w@{i}_f + beta@{i+1}_f/RR(+1)*dWFN@{i+1}_f(+1)*(1-chi@{i+1})*(1-lambda@{i+1}_f(+1))*(1+gh);
+@#endif
+@#endfor
+
+%  Free Entry Condition
+%  ---------------------
+
+aa=qq/Omega_hf*(
+@#for i in wg
++Omega@{i}*dWFN@{i}+Omega@{i}_f*dWFN@{i}_f
+@#endfor
+);
+
+%  Wage Determination (Rent Sharing)
+%  -----------------------------------
+
+@#for i in wg
+(1-eta@{i})*dWHN@{i}  =  eta@{i}*((1-tauw)/(1+tauf)/(1+tauc))*dWFN@{i};
+@#endfor
+
+%  Equilibrium Conditions
+%  ----------------------
+
+ct=
+@#for i in ag
++c@{i}*P@{i}
+@#endfor
+;
+
+st=
+@#for i in ag
++s@{i}*P@{i}
+@#endfor
+;
+
+%  Non-Arbitrage condition (physical capital-shares)
+% .........................
+
+Q(+1)+pi(+1)=(1+rr(+1))*Q/(1+gh);
+
+%  New Open Economy Macroeconomics (NOEM)
+%  ---------------------------------------
+
+phii=mc/theta;
+D= ct + K-(1-delta)*K(-1)/(1+gh)  + g*gdp*phii + fc+aa*V;
+DH=(1/om1*phii)^(1/(rho-1))*D;
+X=(1/om2s*phii/gamma)^(1/(rho-1))*Ds;
+DF=(1/om2*gamma*phijs)^(1/(rho-1))*D;
+nx=phii*X-phijs*gamma*DF;     
+bsY=bs/(phii*gdp);
+Y=DH+X;
+phii*gdp=ct + K-(1-delta)*K(-1)/(1+gh) + g*gdp*phii+nx;
+
+st=K+Q +bs ;
+
+%  Policies
+%  ----------
+
+rhou=rhoub*eps_rhou;
+rhoe=rhoeb*eps_rhoe;
+rhol=rholb*eps_rhol;
+g=gb*eps_g;
+
+@#for i in erg
+De_@{i}=De_@{i}b*eps_De_@{i};
+@#endfor
+
+TFP=TFPb*eps_TFP;
+gh=ghb*eps_gh;
+
+@#for i in wg
+eta@{i}=eta@{i}b*eps_eta@{i};
+@#endfor
+
+rrb=rrbb;
+
+theta=thetab*eps_theta;
+tau1=tau1b;
+om1=om1b;
+om2=om2b;
+om2s=om2sb;
+Ds=Dsb*eps_Ds;
+phijs=phijsb*eps_phijs;
+
+
+% ----------- RefDR scenario 
+
+DepRatio_n=
+@#for i in rg
++P@{i}
+@#endfor
+;
+DepRatio_d=
+@#for i in wg
++P@{i}
+@#endfor
+;
+
+DepRatio=DepRatio_n/DepRatio_d;
+
+ZARA=age_early+length_period*(
+@#for i in erg
++1-i@{i}
+@#endfor  
+);
+
+% ----------- WGEM 
+
+Ptot=
+@#for i in ag
++P@{i}
+@#endfor
+;
+Ptot_f=
+@#for i in ag
++P@{i}_f
+@#endfor
+;
+
+sleep=(1+rr)*(
+@#for i in nbg
++1/beta@{i}*(1-1/beta@{i}^(ann-1))*s@{i-1}(-1)*P@{i}
+@#endfor  
+)/(1+gh);
+
+du=rhou*(
+@#for i in wg
++w@{i}*u@{i}*P@{i}
+@#endfor  
+);
+
+de=rhoe*(
+@#for i in erg
++w@{i}*i@{i}*P@{i}+w@{i}_f*i@{i}_f*P@{i}_f
+@#endfor  
+);
+
+dl=
+@#for i in rg
++rhol*wb*PensCorr_L*P@{i}+rhol*wb_f*(N_f/(N+N_f))*PensCorr_F*P@{i}_f
+@#endfor  
+;
+
+PensCorr_L=eps_PensCorr_L; 
+PensCorr_F=eps_PensCorr_F;   
+
+inA=(tauw+tauf)*(
+@#for i in wg
++n@{i}*w@{i}*P@{i}+n@{i}_f*w@{i}_f*P@{i}_f
+@#endfor  
+);
+
+inB=tauk*rr*(
+@#for i in nbg
++1/beta@{i}^ann*s@{i-1}(-1)*P@{i}
+@#endfor  
+)/(1+gh);
+
+in=tauc*ct+inA+inB+sleep;
+NBR=g*phii*gdp+(du+de+dl)-(in);
+NBRY=NBR/(phii*gdp);
+
+% ----------- WGEM Adjustment variable ---------------
+
+tauf2=tauf;
+tauw2=tauw;
+NBR2=NBR;
+tauc2=tauc;
+tauf=taufb*eps_tauf;
+%----- WGEM: adjustment through tauc
+tauc=taucb*eps_tauc;
+%----- WGEM: adjustment through tauk
+tauk=taukb*eps_tauk;
+%----- WGEM: adjustment through tauw
+tauw=tauwb*eps_tauw;
+
+end;
+
+%==================================
+initval;
+%==================================
+
+@#for i in wg
+n@{i}=n@{i}_iss;
+n@{i}_f=n@{i}_f_iss;
+u@{i}=u@{i}_iss;
+u@{i}_f=u@{i}_f_iss;
+Omega@{i}=Omega@{i}_iss;
+Omega@{i}_f=Omega@{i}_f_iss;
+w@{i}=w@{i}_iss;
+w@{i}_f=w@{i}_f_iss;
+dWHN@{i}=dWHN@{i}_iss;
+dWFN@{i}=dWFN@{i}_iss;
+dWFN@{i}_f=dWFN@{i}_f_iss;
+eps_eta@{i}=eps_eta@{i}_iss;
+eta@{i}=eta@{i}b*eps_eta@{i};
+@#endfor
+
+@#for i in erg
+i@{i}=i@{i}_iss;
+lambda@{i}=lambda@{i}_iss;
+i@{i}_f=i@{i}_f_iss;
+lambda@{i}_f=lambda@{i}_f_iss;
+WE@{i}=0;
+eps_De_@{i}=eps_De_@{i}_iss;
+De_@{i}=De_@{i}b*eps_De_@{i}_iss;
+@#endfor
+
+@#for i in fwg
+i@{i}=0;
+lambda@{i}=0;
+i@{i}_f=0;
+lambda@{i}_f=0;
+@#endfor
+
+@#for i in ag
+@#if i in endg
+s@{i}=0;
+@#else
+s@{i}=s@{i}_iss;
+@#endif
+@#endfor
+
+@#for i in ag
+beta@{i}=beta@{i}_iss;
+beta@{i}_f=beta@{i}_f_iss;
+PD@{i}=PD@{i}_iss;
+c@{i}=c@{i}_iss;
+P@{i}=P@{i}_iss;
+P@{i}_f=P@{i}_f_iss;
+@#endfor
+
+wb          =   wb_iss;
+wb_f        =   wb_f_iss;
+Omega       =   Omega_iss;
+Omega_f     =   Omega_f_iss;
+Omega_hf    =   Omega_hf_iss;
+V        	=	V_iss	;
+M        	=	M_iss	;
+qq       	=	qq_iss	;
+p        	=	p_iss	;
+N        	=	N_iss	;
+N_f      	=	N_f_iss	;
+Q        	=	Q_iss	;
+RR       	=	RR_iss	;
+H        	=	H_iss	;
+K        	=	K_iss	;
+Y        	=	Y_iss	;
+gdp      	=	gdp_iss	;
+nx       	=	nx_iss	;
+FH       	=	FH_iss	;
+pi       	=	pi_iss	;
+ct       	=	ct_iss	;
+st       	=	st_iss	;
+wshare   	=	wshare_iss	;
+rr       	=	rr_iss	;
+
+gamma    	=	gamma_iss	;
+mc       	=	mc_iss	;
+phii     	=	phii_iss	;
+D        	=	D_iss	;
+DH       	=	DH_iss	;
+DF       	=	DF_iss	;
+X        	=	X_iss	;
+bs       	=	bs_iss	;
+bsY      	=	bsY_iss	;
+P00_f       =   P00_f_iss;
+
+eps_rhol=eps_rhol_iss;
+eps_rhoe=eps_rhoe_iss;
+eps_rhou=eps_rhou_iss;
+rhou=rhoub*eps_rhou_iss;
+rhoe=rhoeb*eps_rhoe_iss;
+rhol=rholb*eps_rhol_iss;
+eps_tauc=eps_tauc_iss;
+eps_tauk=eps_tauk_iss;
+eps_tauw=eps_tauw_iss;
+eps_tauf=eps_tauf_iss;
+tauw=tauwb*eps_tauw;
+tauc=taucb*eps_tauc;
+tauf=taufb*eps_tauf;
+tauk=taukb*eps_tauk;
+eps_theta=eps_theta_iss;
+eps_gh=eps_gh_iss;
+eps_TFP=eps_TFP_iss;
+eps_g=eps_g_iss;
+g=gb*eps_g_iss;
+TFP=TFPb*eps_TFP_iss;
+gh=ghb*eps_gh_iss;
+theta=thetab*eps_theta_iss;
+
+rrb=rrbb;
+tau1=tau1b;
+om1=om1b;
+om2=om2b;
+om2s=om2sb;
+
+eps_Ds=1;
+eps_phijs=1;
+Ds=Dsb*eps_Ds;
+phijs=phijsb*eps_phijs;
+
+eps_PensCorr_F=eps_PensCorr_F_iss;
+eps_PensCorr_L=eps_PensCorr_L_iss;
+PensCorr_F=eps_PensCorr_F_iss;
+PensCorr_L=eps_PensCorr_L_iss;
+
+P00	        =	P00_iss	;
+P00_foP00	=	P00_foP00_iss	;
+
+DepRatio_n=
+@#for i in rg
++P@{i}
+@#endfor
+;
+DepRatio_d=
+@#for i in wg
++P@{i}
+@#endfor
+;
+
+DepRatio=DepRatio_n/DepRatio_d;
+
+ZARA=age_early+length_period*(
+@#for i in erg
++1-i@{i}
+@#endfor  
+);
+
+Ptot=Ptot_iss;
+Ptot_f=Ptot_f_iss;
+sleep=sleep_iss;
+du=du_iss;
+de=de_iss;
+dl=dl_iss;
+
+inA=inA_iss;%(tauw+tauf)*(
+%@#for i in wg
+%+n@{i}*w@{i}*P@{i}+n@{i}_f*w@{i}_f*P@{i}_f
+%@#endfor  
+%);
+
+inB=inB_iss;%tauk*rr*(
+%@#for i in nbg
+%+1/beta@{i}^ann*s@{i-1}*P@{i}
+%@#endfor  
+%)/(1+gh);
+
+in=in_iss;%tauc*ct+inA+inB+sleep;
+NBR=NBR_iss;%g*phii*gdp+(du+de+dl)-(in);
+NBRY=NBR/(phii*gdp);
+NBR2=NBR;
+tauf2=tauf;
+tauw2=tauw;
+tauc2=tauc;
+
+end;
+
+%========================================================
+% compute initial steady state and check eigenvalues 
+%========================================================
+
+resid;
+steady(solve_algo=3);
+check;
+
+%========================================================
+endval;
+%========================================================
+
+@#for i in wg
+n@{i}=n@{i}_fss;
+n@{i}_f=n@{i}_f_fss;
+u@{i}=u@{i}_fss;
+u@{i}_f=u@{i}_f_fss;
+Omega@{i}=Omega@{i}_fss;
+Omega@{i}_f=Omega@{i}_f_fss;
+w@{i}=w@{i}_fss;
+w@{i}_f=w@{i}_f_fss;
+dWHN@{i}=dWHN@{i}_fss;
+dWFN@{i}=dWFN@{i}_fss;
+dWFN@{i}_f=dWFN@{i}_f_fss;
+eps_eta@{i}=eps_eta@{i}_fss;
+eta@{i}=eta@{i}b*eps_eta@{i};
+@#endfor
+
+@#for i in erg
+i@{i}=i@{i}_fss;
+lambda@{i}=lambda@{i}_fss;
+i@{i}_f=i@{i}_f_fss;
+lambda@{i}_f=lambda@{i}_f_fss;
+WE@{i}=0;
+eps_De_@{i}=eps_De_@{i}_fss;
+De_@{i}=De_@{i}b*eps_De_@{i}_fss;
+@#endfor
+
+@#for i in fwg
+i@{i}=0;
+lambda@{i}=0;
+i@{i}_f=0;
+lambda@{i}_f=0;
+@#endfor
+
+@#for i in ag
+@#if i in endg
+s@{i}=0;
+@#else
+s@{i}=s@{i}_fss;
+@#endif
+@#endfor
+
+@#for i in ag
+beta@{i}=beta@{i}_fss;
+beta@{i}_f=beta@{i}_f_fss;
+PD@{i}=PD@{i}_fss;
+c@{i}=c@{i}_fss;
+P@{i}=P@{i}_fss;
+P@{i}_f=P@{i}_f_fss;
+@#endfor
+
+wb          =   wb_fss;
+wb_f        =   wb_f_fss;
+Omega       =   Omega_fss;
+Omega_f     =   Omega_f_fss;
+Omega_hf    =   Omega_hf_fss;
+V        	=	V_fss	;
+M        	=	M_fss	;
+qq       	=	qq_fss	;
+p        	=	p_fss	;
+N        	=	N_fss	;
+N_f      	=	N_f_fss	;
+Q        	=	Q_fss	;
+RR       	=	RR_fss	;
+H        	=	H_fss	;
+K        	=	K_fss	;
+Y        	=	Y_fss	;
+gdp      	=	gdp_fss	;
+nx       	=	nx_fss	;
+FH       	=	FH_fss	;
+pi       	=	pi_fss	;
+ct       	=	ct_fss	;
+st       	=	st_fss	;
+wshare   	=	wshare_fss	;
+rr       	=	rr_fss	;
+
+gamma    	=	gamma_fss	;
+mc       	=	mc_fss	;
+phii     	=	phii_fss	;
+D        	=	D_fss	;
+DH       	=	DH_fss	;
+DF       	=	DF_fss	;
+X        	=	X_fss	;
+bs       	=	bs_fss	;
+bsY      	=	bsY_fss	;
+P00_f       =   P00_f_fss;
+
+eps_rhol=eps_rhol_fss;
+eps_rhoe=eps_rhoe_fss;
+eps_rhou=eps_rhou_fss;
+rhou=rhoub*eps_rhou_fss;
+rhoe=rhoeb*eps_rhoe_fss;
+rhol=rholb*eps_rhol_fss;
+eps_tauc=eps_tauc_fss;
+eps_tauk=eps_tauk_fss;
+eps_tauw=eps_tauw_fss;
+eps_tauf=eps_tauf_fss;
+tauw=tauwb*eps_tauw;
+tauc=taucb*eps_tauc;
+tauf=taufb*eps_tauf;
+tauk=taukb*eps_tauk;
+eps_theta=eps_theta_fss;
+eps_gh=eps_gh_fss;
+eps_TFP=eps_TFP_fss;
+eps_g=eps_g_fss;
+g=gb*eps_g_fss;
+TFP=TFPb*eps_TFP_fss;
+gh=ghb*eps_gh_fss;
+theta=thetab*eps_theta_fss;
+
+rrb=rrbb;
+tau1=tau1b;
+om1=om1b;
+om2=om2b;
+om2s=om2sb;
+
+eps_Ds=1;
+eps_phijs=1;
+Ds=Dsb*eps_Ds;
+phijs=phijsb*eps_phijs;
+
+eps_PensCorr_F=eps_PensCorr_F_fss;
+eps_PensCorr_L=eps_PensCorr_L_fss;
+PensCorr_F=eps_PensCorr_F_fss;
+PensCorr_L=eps_PensCorr_L_fss;
+
+P00	        =	P00_fss	;
+P00_foP00	=	P00_foP00_fss	;
+
+DepRatio_n=
+@#for i in rg
++P@{i}
+@#endfor
+;
+DepRatio_d=
+@#for i in wg
++P@{i}
+@#endfor
+;
+
+DepRatio=DepRatio_n/DepRatio_d;
+
+ZARA=age_early+length_period*(
+@#for i in erg
++1-i@{i}
+@#endfor  
+);
+
+Ptot=
+@#for i in ag
++P@{i}
+@#endfor
+;
+Ptot_f=
+@#for i in ag
++P@{i}_f
+@#endfor
+;
+
+sleep=(1+rr)*(
+@#for i in nbg
++1/beta@{i}*(1-1/beta@{i}^(ann-1))*s@{i-1}*P@{i}
+@#endfor  
+)/(1+gh);
+
+du=rhou*(
+@#for i in wg
++w@{i}*u@{i}*P@{i}
+@#endfor  
+);
+
+de=rhoe*(
+@#for i in erg
++w@{i}*i@{i}*P@{i}+w@{i}_f*i@{i}_f*P@{i}_f
+@#endfor  
+);
+
+dl=
+@#for i in rg
++rhol*wb*PensCorr_L*P@{i}+rhol*wb_f*(N_f/(N+N_f))*PensCorr_F*P@{i}_f
+@#endfor  
+;
+
+inA=(tauw+tauf)*(
+@#for i in wg
++n@{i}*w@{i}*P@{i}+n@{i}_f*w@{i}_f*P@{i}_f
+@#endfor  
+);
+
+inB=tauk*rr*(
+@#for i in nbg
++1/beta@{i}^ann*s@{i-1}*P@{i}
+@#endfor  
+)/(1+gh);
+
+in=tauc*ct+inA+inB+sleep;
+NBR=g*phii*gdp+(du+de+dl)-(in);
+NBRY=NBR/(phii*gdp);
+NBR2=NBR;
+tauf2=tauf;
+tauw2=tauw;
+tauc2=tauc;
+
+end;
+
+%========================================================
+% compute final steady state and check eigenvalues 
+%========================================================
+
+resid;
+steady(solve_algo=3);
+check;
+
+
+% ===================================================
+shocks;     
+% ===================================================
+
+var P00;																																																			
+   periods 1:99;																																																			
+   values (se_P00);																																																			
+ 
+@#for i in nbg
+var beta@{i};																																																			
+   periods  1:99;																																																			
+   values (se_beta@{i});
+var beta@{i}_f;																																																			
+   periods  1:99;																																																			
+   values (se_beta@{i}_f);
+var PD@{i};																																																			
+   periods  1:99;																																																			
+   values (se_PD@{i});
+@#endfor  
+																																																			
+var P00_foP00;																																																			
+   periods 1:99;																																																			
+   values (se_P00_foP00);	 																																																
+
+var eps_g;																																																			
+   periods 1:99;																																																			
+   values (se_eps_g);	
+
+var eps_PensCorr_F;																																																			
+   periods 1:99;																																																			
+   values (se_eps_PensCorr_F);	
+
+var eps_PensCorr_L;																																																			
+   periods 1:99;																																																			
+   values (se_eps_PensCorr_L);	
+
+end;
+
+% *******************************************
+% Numerical Simulation, Control Parameters
+% *******************************************
+
+model_info;
+
+perfect_foresight_setup(periods=125);
+perfect_foresight_solver(maxit=100);
+
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
+mfs0=load('lola_solve_one_boundary_results');
+
+if max(max(oo_.endo_simul-mfs0.oo_.endo_simul)) > options_.dynatol.x
+   error('Inconsistency with mfs=0')
+end
diff --git a/tests/deterministic_simulations/lola_solve_one_boundary_mfs2.mod b/tests/deterministic_simulations/lola_solve_one_boundary_mfs2.mod
new file mode 100644
index 0000000000000000000000000000000000000000..7d569e20a1370a08c95bcde81c5f915a99712e8a
--- /dev/null
+++ b/tests/deterministic_simulations/lola_solve_one_boundary_mfs2.mod
@@ -0,0 +1,985 @@
+// Tests option mfs=2 with block
+
+load lola_data.mat
+
+% ====================================================
+% declarations var -- varexo -- para   
+% ====================================================
+
+@#define nbr_work_generations=9
+@#define nbr_early_generations=2
+@#define nbr_generations=16
+
+parameters
+length_period age_early;
+
+length_period=5;
+age_early=55;
+
+@#define wt=[1]
+
+@#define wg=0:nbr_work_generations-1
+@#define ag=0:nbr_generations-1
+@#define fwg=0:nbr_work_generations-nbr_early_generations-1
+@#define nbwg=1:nbr_work_generations-1
+@#define nbg=1:nbr_generations-1
+@#define rg=nbr_work_generations:nbr_generations-1
+@#define erg=nbr_work_generations-nbr_early_generations:nbr_work_generations-1
+@#define endg=[nbr_generations-1]
+@#define endw=[nbr_work_generations-1]
+
+@#for i in wg
+var 
+n@{i} u@{i} Omega@{i} w@{i} dWHN@{i} dWFN@{i} 
+n@{i}_f u@{i}_f Omega@{i}_f w@{i}_f dWFN@{i}_f
+i@{i} lambda@{i} i@{i}_f lambda@{i}_f eta@{i};
+parameters
+Du@{i} Dn@{i} h@{i} h@{i}_f chi@{i} eta@{i}b; 
+varexo
+eps_eta@{i};
+@#endfor
+
+@#for i in ag
+var 
+c@{i} s@{i} P@{i} P@{i}_f;
+varexo
+beta@{i} beta@{i}_f PD@{i};
+@#endfor
+
+@#for i in erg
+var 
+WE@{i} De_@{i};
+parameters
+De_@{i}b; 
+varexo
+eps_De_@{i};
+@#endfor
+
+var   
+wb wb_f 
+Omega Omega_f Omega_hf 
+V M qq p 
+N N_f 
+Q RR H K Y gdp nx FH pi
+ct st wshare rr 
+gamma mc phii D DH DF X bs bsY P00_f
+
+rhou rhoe rhol tauw tauc tauf tauk g 
+TFP gh rrb
+theta tau1 om1 om2 om2s Ds phijs
+
+DepRatio DepRatio_n DepRatio_d ZARA Ptot Ptot_f sleep du de dl inA inB in 
+NBR NBRY NBR2 tauw2 tauf2 tauc2
+PensCorr_L PensCorr_F;
+
+parameters 
+rho phi delta alpha beta ann 
+fc nu aa 
+
+rhoub rhoeb rholb tauwb taucb taufb taukb gb  
+TFPb ghb rrbb
+thetab tau1b om1b om2b om2sb Dsb phijsb
+
+NBRYb bsY_iss;
+
+varexo
+P00 P00_foP00
+
+eps_rhol eps_tauw eps_tauf eps_tauc eps_tauk
+eps_rhoe eps_rhou eps_TFP eps_gh eps_theta eps_g
+eps_Ds eps_phijs eps_PensCorr_L eps_PensCorr_F;
+
+
+% ============================================================
+% initialization
+% ============================================================
+
+@#for i in wg
+set_param_value('Du@{i}',Du@{i});
+set_param_value('Dn@{i}',Dn@{i});
+set_param_value('h@{i}',h@{i});
+set_param_value('h@{i}_f',h@{i}_f);
+set_param_value('chi@{i}',chi@{i});
+set_param_value('eta@{i}b',eta@{i}b);
+@#endfor
+
+@#for i in erg
+set_param_value('De_@{i}b',De_@{i}b);
+@#endfor
+
+set_param_value('rho',rho);
+set_param_value('phi',phi);
+set_param_value('delta',delta);
+set_param_value('alpha',alpha);
+set_param_value('beta',beta);
+set_param_value('ann',ann);
+set_param_value('fc',fc);
+set_param_value('nu',nu);
+set_param_value('aa',aa);
+
+set_param_value('rhoub',rhoub);
+set_param_value('rhoeb',rhoeb);
+set_param_value('rholb',rholb);
+set_param_value('tauwb',tauwb);
+set_param_value('taucb',taucb);
+set_param_value('taufb',taufb);
+set_param_value('taukb',taukb);
+set_param_value('gb',gb);
+
+set_param_value('TFPb',TFPb);
+set_param_value('ghb',ghb);
+set_param_value('rrbb',rrbb);
+
+set_param_value('thetab',thetab);
+set_param_value('tau1b',tau1b);
+set_param_value('om1b',om1b);
+set_param_value('om2b',om2b);
+set_param_value('om2sb',om2sb);
+set_param_value('Dsb',Dsb);
+set_param_value('phijsb',phijsb);
+
+set_param_value('bsY_iss',bsY_iss);
+
+NBRYb=NBR_iss/(phii_iss*gdp_iss);
+
+
+% =======================================================
+model(block, mfs=2);
+% ======================================================
+
+%  Labor Market Variables in the home country
+%  ------------------------------------------ 
+
+@#for i in fwg
+0=lambda@{i};
+@#endfor
+
+@#for i in wg
+1=n@{i}+u@{i}+i@{i};
+@#endfor   
+                            
+i0=lambda0;
+@#for i in nbwg
+i@{i}=lambda@{i-1}(-1)+lambda@{i}*(1-lambda@{i-1}(-1));
+@#endfor 
+
+P0=beta0*P00+PD0;
+@#for i in nbg
+P@{i}=beta@{i}*P@{i-1}(-1)+PD@{i};
+@#endfor
+
+Omega0=P0;
+@#for i in nbwg
+Omega@{i}=(1-lambda@{i})*( 1-lambda@{i-1}(-1)-(1-chi@{i})*n@{i-1}(-1))*P@{i};
+@#endfor 
+
+n0=p;
+@#for i in nbwg
+n@{i}=(1-lambda@{i})*((1-p)*(1-chi@{i})*n@{i-1}(-1)+p*(1-lambda@{i-1}(-1)));
+@#endfor 
+
+N=
+@#for i in wg
++n@{i}*P@{i}
+@#endfor
+;
+
+%  Labor Market Variables in the foreign country
+%  --------------------------------------------- 
+
+@#for i in wg
+1=n@{i}_f+u@{i}_f+i@{i}_f;
+@#endfor    
+                            
+i0_f=lambda0_f;
+@#for i in nbwg
+i@{i}_f=lambda@{i-1}_f(-1)+lambda@{i}_f*(1-lambda@{i-1}_f(-1));
+@#endfor
+
+% -----------  reproduction cross-border   --------------------
+
+P00_f=P00_foP00*P00;
+
+P0_f=beta0_f*P00_f;
+@#for i in nbg
+P@{i}_f=beta@{i}_f*P@{i-1}_f(-1);
+@#endfor 
+
+Omega0_f=P0_f;
+@#for i in nbwg
+Omega@{i}_f=(1-lambda@{i}_f)*(1-lambda@{i-1}_f(-1)-(1-chi@{i})*n@{i-1}_f(-1))*P@{i}_f;
+@#endfor 
+
+n0_f=p;
+@#for i in nbwg
+n@{i}_f=(1-lambda@{i}_f)*((1-p)*(1-chi@{i})*n@{i-1}_f(-1)+p*(1-lambda@{i-1}_f(-1)));
+@#endfor
+
+N_f=
+@#for i in wg
++n@{i}_f*P@{i}_f
+@#endfor
+;
+
+%  Matching
+% ----------
+
+Omega=
+@#for i in wg
++Omega@{i}
+@#endfor
+;
+
+Omega_f=
+@#for i in wg
++Omega@{i}_f
+@#endfor
+;
+
+Omega_hf=Omega+Omega_f;
+ 
+M=V*Omega_hf/(V^nu+Omega_hf^nu)^(1/nu);
+
+qq=M/V;
+p=M/Omega_hf;
+
+%  Flow Budget Constraints (no bequests)
+% --------------------------------------
+
+rhou*w0*u0+ (1-tauw)*w0*n0 = (1+tauc)*c0+s0;
+@#for i in nbwg
+(1+rr*(1-tauk))/(beta@{i})^ann*s@{i-1}(-1)/(1+gh)+rhou*w@{i}*u@{i}+rhoe*w@{i}*i@{i}+(1-tauw)*w@{i}*n@{i}=(1+tauc)*c@{i}+s@{i};
+@#endfor
+@#for i in rg
+(1+rr*(1-tauk))/(beta@{i})^ann*s@{i-1}(-1)/(1+gh)+rhol*wb=(1+tauc)*c@{i}+s@{i};
+@#endfor
+@#for i in endg
+s@{i}=0;
+@#endfor
+
+wb=
+@#for i in wg
++w@{i}/@{nbr_work_generations}
+@#endfor
+;
+
+%  Euler Conditions
+% ------------------
+
+@#for i in nbg
+1/(1+tauc)/c@{i-1}=beta*(1+rr(+1)*(1-tauk(+1)))/(1+tauc(+1))/c@{i}(+1)*(beta@{i})^(1-ann)/(1+gh);
+@#endfor
+
+
+%  Optimal Participation Rates (Early Retirement)
+%  ----------------------------------------------
+
+@#for i in erg
+WE@{i} = 0;
+@#endfor 
+
+@#for i in erg
+@#if i in endw
+WE@{i} = ((De_@{i}b*i@{i}^(phi-1))+Du@{i}+(rhoe-rhou)*w@{i}/(1+tauc)/c@{i})*(1-i@{i})-((1-tauw-rhou)*w@{i}/(1+tauc)/c@{i}-(Dn@{i}-Du@{i}))*n@{i};
+@#else  
+WE@{i} = ((De_@{i}b*i@{i}^(phi-1))+Du@{i}+(rhoe-rhou)*w@{i}/(1+tauc)/c@{i})*(1-i@{i})-((1-tauw-rhou)*w@{i}/(1+tauc)/c@{i}-(Dn@{i}-Du@{i}))*n@{i}+ beta*beta@{i+1}*WE@{i+1};
+@#endif
+@#endfor  
+
+%  Household Surplus
+% -------------------
+
+@#for i in wg
+@#if i in endw
+dWHN@{i} = w@{i}*(1-tauw-rhou)/(1+tauc)-(Dn@{i}-Du@{i})*c@{i};
+@#else  
+dWHN@{i} = w@{i}*(1-tauw-rhou)/(1+tauc)-(Dn@{i}-Du@{i})*c@{i} + beta*beta@{i+1}*c@{i}/c@{i+1}(+1)*dWHN@{i+1}(+1)*(1-p(+1))*(1-chi@{i+1})*(1-lambda@{i+1}(+1));
+@#endif
+@#endfor    
+
+%  Foreign household
+%  ------------------------
+%  participation and wages
+% ........................
+
+@#for i in wg
+lambda@{i}=lambda@{i}_f;
+w@{i}_f=w@{i}; 
+@#endfor
+
+wb_f=
+@#for i in wg
++w@{i}_f/@{nbr_work_generations}
+@#endfor
+;
+
+%  Firm's Behavior
+% -------------------
+
+H=
+@#for i in wg
++h@{i}*n@{i}*P@{i}+h@{i}_f*n@{i}_f*P@{i}_f
+@#endfor
+;
+
+wshare=(1+tauf)*(
+@#for i in wg
++w@{i}*n@{i}*P@{i}+w@{i}_f*n@{i}_f*P@{i}_f
+@#endfor
+)/(phii*gdp);
+
+Y=TFP*H^(1-alpha)*(K)^alpha;
+gdp= TFP*H^(1-alpha)*(K)^alpha-aa*V/phii-fc/phii;
+pi = phii*gdp - wshare*phii*gdp - (rr+delta)*K(-1)/(1+gh);
+(rr(+1)+delta)/(1+rr(+1)*(1-tauk(+1))) = mc*TFP*alpha*(H/(K))^(1-alpha);
+FH=TFP*(1-alpha)*((K)/H)^alpha;
+
+RR=1+rr*(1-tauk);
+rr=rrb+tau1*(exp(bsY_iss-bsY)-1);
+
+%  Firm's Surplus
+%  ---------------------
+
+@#for i in wg
+@#if i in endw
+dWFN@{i} = h@{i}*mc*FH-(1+tauf)*w@{i};
+dWFN@{i}_f = h@{i}_f*mc*FH-(1+tauf)*w@{i}_f;
+@#else  
+dWFN@{i} = h@{i}*mc*FH-(1+tauf)*w@{i} + beta@{i+1}/RR(+1)*dWFN@{i+1}(+1)*(1-chi@{i+1})*(1-lambda@{i+1}(+1))*(1+gh);
+dWFN@{i}_f = h@{i}_f*mc*FH-(1+tauf)*w@{i}_f + beta@{i+1}_f/RR(+1)*dWFN@{i+1}_f(+1)*(1-chi@{i+1})*(1-lambda@{i+1}_f(+1))*(1+gh);
+@#endif
+@#endfor
+
+%  Free Entry Condition
+%  ---------------------
+
+aa=qq/Omega_hf*(
+@#for i in wg
++Omega@{i}*dWFN@{i}+Omega@{i}_f*dWFN@{i}_f
+@#endfor
+);
+
+%  Wage Determination (Rent Sharing)
+%  -----------------------------------
+
+@#for i in wg
+(1-eta@{i})*dWHN@{i}  =  eta@{i}*((1-tauw)/(1+tauf)/(1+tauc))*dWFN@{i};
+@#endfor
+
+%  Equilibrium Conditions
+%  ----------------------
+
+ct=
+@#for i in ag
++c@{i}*P@{i}
+@#endfor
+;
+
+st=
+@#for i in ag
++s@{i}*P@{i}
+@#endfor
+;
+
+%  Non-Arbitrage condition (physical capital-shares)
+% .........................
+
+Q(+1)+pi(+1)=(1+rr(+1))*Q/(1+gh);
+
+%  New Open Economy Macroeconomics (NOEM)
+%  ---------------------------------------
+
+phii=mc/theta;
+D= ct + K-(1-delta)*K(-1)/(1+gh)  + g*gdp*phii + fc+aa*V;
+DH=(1/om1*phii)^(1/(rho-1))*D;
+X=(1/om2s*phii/gamma)^(1/(rho-1))*Ds;
+DF=(1/om2*gamma*phijs)^(1/(rho-1))*D;
+nx=phii*X-phijs*gamma*DF;     
+bsY=bs/(phii*gdp);
+Y=DH+X;
+phii*gdp=ct + K-(1-delta)*K(-1)/(1+gh) + g*gdp*phii+nx;
+
+st=K+Q +bs ;
+
+%  Policies
+%  ----------
+
+rhou=rhoub*eps_rhou;
+rhoe=rhoeb*eps_rhoe;
+rhol=rholb*eps_rhol;
+g=gb*eps_g;
+
+@#for i in erg
+De_@{i}=De_@{i}b*eps_De_@{i};
+@#endfor
+
+TFP=TFPb*eps_TFP;
+gh=ghb*eps_gh;
+
+@#for i in wg
+eta@{i}=eta@{i}b*eps_eta@{i};
+@#endfor
+
+rrb=rrbb;
+
+theta=thetab*eps_theta;
+tau1=tau1b;
+om1=om1b;
+om2=om2b;
+om2s=om2sb;
+Ds=Dsb*eps_Ds;
+phijs=phijsb*eps_phijs;
+
+
+% ----------- RefDR scenario 
+
+DepRatio_n=
+@#for i in rg
++P@{i}
+@#endfor
+;
+DepRatio_d=
+@#for i in wg
++P@{i}
+@#endfor
+;
+
+DepRatio=DepRatio_n/DepRatio_d;
+
+ZARA=age_early+length_period*(
+@#for i in erg
++1-i@{i}
+@#endfor  
+);
+
+% ----------- WGEM 
+
+Ptot=
+@#for i in ag
++P@{i}
+@#endfor
+;
+Ptot_f=
+@#for i in ag
++P@{i}_f
+@#endfor
+;
+
+sleep=(1+rr)*(
+@#for i in nbg
++1/beta@{i}*(1-1/beta@{i}^(ann-1))*s@{i-1}(-1)*P@{i}
+@#endfor  
+)/(1+gh);
+
+du=rhou*(
+@#for i in wg
++w@{i}*u@{i}*P@{i}
+@#endfor  
+);
+
+de=rhoe*(
+@#for i in erg
++w@{i}*i@{i}*P@{i}+w@{i}_f*i@{i}_f*P@{i}_f
+@#endfor  
+);
+
+dl=
+@#for i in rg
++rhol*wb*PensCorr_L*P@{i}+rhol*wb_f*(N_f/(N+N_f))*PensCorr_F*P@{i}_f
+@#endfor  
+;
+
+PensCorr_L=eps_PensCorr_L; 
+PensCorr_F=eps_PensCorr_F;   
+
+inA=(tauw+tauf)*(
+@#for i in wg
++n@{i}*w@{i}*P@{i}+n@{i}_f*w@{i}_f*P@{i}_f
+@#endfor  
+);
+
+inB=tauk*rr*(
+@#for i in nbg
++1/beta@{i}^ann*s@{i-1}(-1)*P@{i}
+@#endfor  
+)/(1+gh);
+
+in=tauc*ct+inA+inB+sleep;
+NBR=g*phii*gdp+(du+de+dl)-(in);
+NBRY=NBR/(phii*gdp);
+
+% ----------- WGEM Adjustment variable ---------------
+
+tauf2=tauf;
+tauw2=tauw;
+NBR2=NBR;
+tauc2=tauc;
+tauf=taufb*eps_tauf;
+%----- WGEM: adjustment through tauc
+tauc=taucb*eps_tauc;
+%----- WGEM: adjustment through tauk
+tauk=taukb*eps_tauk;
+%----- WGEM: adjustment through tauw
+tauw=tauwb*eps_tauw;
+
+end;
+
+%==================================
+initval;
+%==================================
+
+@#for i in wg
+n@{i}=n@{i}_iss;
+n@{i}_f=n@{i}_f_iss;
+u@{i}=u@{i}_iss;
+u@{i}_f=u@{i}_f_iss;
+Omega@{i}=Omega@{i}_iss;
+Omega@{i}_f=Omega@{i}_f_iss;
+w@{i}=w@{i}_iss;
+w@{i}_f=w@{i}_f_iss;
+dWHN@{i}=dWHN@{i}_iss;
+dWFN@{i}=dWFN@{i}_iss;
+dWFN@{i}_f=dWFN@{i}_f_iss;
+eps_eta@{i}=eps_eta@{i}_iss;
+eta@{i}=eta@{i}b*eps_eta@{i};
+@#endfor
+
+@#for i in erg
+i@{i}=i@{i}_iss;
+lambda@{i}=lambda@{i}_iss;
+i@{i}_f=i@{i}_f_iss;
+lambda@{i}_f=lambda@{i}_f_iss;
+WE@{i}=0;
+eps_De_@{i}=eps_De_@{i}_iss;
+De_@{i}=De_@{i}b*eps_De_@{i}_iss;
+@#endfor
+
+@#for i in fwg
+i@{i}=0;
+lambda@{i}=0;
+i@{i}_f=0;
+lambda@{i}_f=0;
+@#endfor
+
+@#for i in ag
+@#if i in endg
+s@{i}=0;
+@#else
+s@{i}=s@{i}_iss;
+@#endif
+@#endfor
+
+@#for i in ag
+beta@{i}=beta@{i}_iss;
+beta@{i}_f=beta@{i}_f_iss;
+PD@{i}=PD@{i}_iss;
+c@{i}=c@{i}_iss;
+P@{i}=P@{i}_iss;
+P@{i}_f=P@{i}_f_iss;
+@#endfor
+
+wb          =   wb_iss;
+wb_f        =   wb_f_iss;
+Omega       =   Omega_iss;
+Omega_f     =   Omega_f_iss;
+Omega_hf    =   Omega_hf_iss;
+V        	=	V_iss	;
+M        	=	M_iss	;
+qq       	=	qq_iss	;
+p        	=	p_iss	;
+N        	=	N_iss	;
+N_f      	=	N_f_iss	;
+Q        	=	Q_iss	;
+RR       	=	RR_iss	;
+H        	=	H_iss	;
+K        	=	K_iss	;
+Y        	=	Y_iss	;
+gdp      	=	gdp_iss	;
+nx       	=	nx_iss	;
+FH       	=	FH_iss	;
+pi       	=	pi_iss	;
+ct       	=	ct_iss	;
+st       	=	st_iss	;
+wshare   	=	wshare_iss	;
+rr       	=	rr_iss	;
+
+gamma    	=	gamma_iss	;
+mc       	=	mc_iss	;
+phii     	=	phii_iss	;
+D        	=	D_iss	;
+DH       	=	DH_iss	;
+DF       	=	DF_iss	;
+X        	=	X_iss	;
+bs       	=	bs_iss	;
+bsY      	=	bsY_iss	;
+P00_f       =   P00_f_iss;
+
+eps_rhol=eps_rhol_iss;
+eps_rhoe=eps_rhoe_iss;
+eps_rhou=eps_rhou_iss;
+rhou=rhoub*eps_rhou_iss;
+rhoe=rhoeb*eps_rhoe_iss;
+rhol=rholb*eps_rhol_iss;
+eps_tauc=eps_tauc_iss;
+eps_tauk=eps_tauk_iss;
+eps_tauw=eps_tauw_iss;
+eps_tauf=eps_tauf_iss;
+tauw=tauwb*eps_tauw;
+tauc=taucb*eps_tauc;
+tauf=taufb*eps_tauf;
+tauk=taukb*eps_tauk;
+eps_theta=eps_theta_iss;
+eps_gh=eps_gh_iss;
+eps_TFP=eps_TFP_iss;
+eps_g=eps_g_iss;
+g=gb*eps_g_iss;
+TFP=TFPb*eps_TFP_iss;
+gh=ghb*eps_gh_iss;
+theta=thetab*eps_theta_iss;
+
+rrb=rrbb;
+tau1=tau1b;
+om1=om1b;
+om2=om2b;
+om2s=om2sb;
+
+eps_Ds=1;
+eps_phijs=1;
+Ds=Dsb*eps_Ds;
+phijs=phijsb*eps_phijs;
+
+eps_PensCorr_F=eps_PensCorr_F_iss;
+eps_PensCorr_L=eps_PensCorr_L_iss;
+PensCorr_F=eps_PensCorr_F_iss;
+PensCorr_L=eps_PensCorr_L_iss;
+
+P00	        =	P00_iss	;
+P00_foP00	=	P00_foP00_iss	;
+
+DepRatio_n=
+@#for i in rg
++P@{i}
+@#endfor
+;
+DepRatio_d=
+@#for i in wg
++P@{i}
+@#endfor
+;
+
+DepRatio=DepRatio_n/DepRatio_d;
+
+ZARA=age_early+length_period*(
+@#for i in erg
++1-i@{i}
+@#endfor  
+);
+
+Ptot=Ptot_iss;
+Ptot_f=Ptot_f_iss;
+sleep=sleep_iss;
+du=du_iss;
+de=de_iss;
+dl=dl_iss;
+
+inA=inA_iss;%(tauw+tauf)*(
+%@#for i in wg
+%+n@{i}*w@{i}*P@{i}+n@{i}_f*w@{i}_f*P@{i}_f
+%@#endfor  
+%);
+
+inB=inB_iss;%tauk*rr*(
+%@#for i in nbg
+%+1/beta@{i}^ann*s@{i-1}*P@{i}
+%@#endfor  
+%)/(1+gh);
+
+in=in_iss;%tauc*ct+inA+inB+sleep;
+NBR=NBR_iss;%g*phii*gdp+(du+de+dl)-(in);
+NBRY=NBR/(phii*gdp);
+NBR2=NBR;
+tauf2=tauf;
+tauw2=tauw;
+tauc2=tauc;
+
+end;
+
+%========================================================
+% compute initial steady state and check eigenvalues 
+%========================================================
+
+resid;
+steady(solve_algo=3);
+check;
+
+%========================================================
+endval;
+%========================================================
+
+@#for i in wg
+n@{i}=n@{i}_fss;
+n@{i}_f=n@{i}_f_fss;
+u@{i}=u@{i}_fss;
+u@{i}_f=u@{i}_f_fss;
+Omega@{i}=Omega@{i}_fss;
+Omega@{i}_f=Omega@{i}_f_fss;
+w@{i}=w@{i}_fss;
+w@{i}_f=w@{i}_f_fss;
+dWHN@{i}=dWHN@{i}_fss;
+dWFN@{i}=dWFN@{i}_fss;
+dWFN@{i}_f=dWFN@{i}_f_fss;
+eps_eta@{i}=eps_eta@{i}_fss;
+eta@{i}=eta@{i}b*eps_eta@{i};
+@#endfor
+
+@#for i in erg
+i@{i}=i@{i}_fss;
+lambda@{i}=lambda@{i}_fss;
+i@{i}_f=i@{i}_f_fss;
+lambda@{i}_f=lambda@{i}_f_fss;
+WE@{i}=0;
+eps_De_@{i}=eps_De_@{i}_fss;
+De_@{i}=De_@{i}b*eps_De_@{i}_fss;
+@#endfor
+
+@#for i in fwg
+i@{i}=0;
+lambda@{i}=0;
+i@{i}_f=0;
+lambda@{i}_f=0;
+@#endfor
+
+@#for i in ag
+@#if i in endg
+s@{i}=0;
+@#else
+s@{i}=s@{i}_fss;
+@#endif
+@#endfor
+
+@#for i in ag
+beta@{i}=beta@{i}_fss;
+beta@{i}_f=beta@{i}_f_fss;
+PD@{i}=PD@{i}_fss;
+c@{i}=c@{i}_fss;
+P@{i}=P@{i}_fss;
+P@{i}_f=P@{i}_f_fss;
+@#endfor
+
+wb          =   wb_fss;
+wb_f        =   wb_f_fss;
+Omega       =   Omega_fss;
+Omega_f     =   Omega_f_fss;
+Omega_hf    =   Omega_hf_fss;
+V        	=	V_fss	;
+M        	=	M_fss	;
+qq       	=	qq_fss	;
+p        	=	p_fss	;
+N        	=	N_fss	;
+N_f      	=	N_f_fss	;
+Q        	=	Q_fss	;
+RR       	=	RR_fss	;
+H        	=	H_fss	;
+K        	=	K_fss	;
+Y        	=	Y_fss	;
+gdp      	=	gdp_fss	;
+nx       	=	nx_fss	;
+FH       	=	FH_fss	;
+pi       	=	pi_fss	;
+ct       	=	ct_fss	;
+st       	=	st_fss	;
+wshare   	=	wshare_fss	;
+rr       	=	rr_fss	;
+
+gamma    	=	gamma_fss	;
+mc       	=	mc_fss	;
+phii     	=	phii_fss	;
+D        	=	D_fss	;
+DH       	=	DH_fss	;
+DF       	=	DF_fss	;
+X        	=	X_fss	;
+bs       	=	bs_fss	;
+bsY      	=	bsY_fss	;
+P00_f       =   P00_f_fss;
+
+eps_rhol=eps_rhol_fss;
+eps_rhoe=eps_rhoe_fss;
+eps_rhou=eps_rhou_fss;
+rhou=rhoub*eps_rhou_fss;
+rhoe=rhoeb*eps_rhoe_fss;
+rhol=rholb*eps_rhol_fss;
+eps_tauc=eps_tauc_fss;
+eps_tauk=eps_tauk_fss;
+eps_tauw=eps_tauw_fss;
+eps_tauf=eps_tauf_fss;
+tauw=tauwb*eps_tauw;
+tauc=taucb*eps_tauc;
+tauf=taufb*eps_tauf;
+tauk=taukb*eps_tauk;
+eps_theta=eps_theta_fss;
+eps_gh=eps_gh_fss;
+eps_TFP=eps_TFP_fss;
+eps_g=eps_g_fss;
+g=gb*eps_g_fss;
+TFP=TFPb*eps_TFP_fss;
+gh=ghb*eps_gh_fss;
+theta=thetab*eps_theta_fss;
+
+rrb=rrbb;
+tau1=tau1b;
+om1=om1b;
+om2=om2b;
+om2s=om2sb;
+
+eps_Ds=1;
+eps_phijs=1;
+Ds=Dsb*eps_Ds;
+phijs=phijsb*eps_phijs;
+
+eps_PensCorr_F=eps_PensCorr_F_fss;
+eps_PensCorr_L=eps_PensCorr_L_fss;
+PensCorr_F=eps_PensCorr_F_fss;
+PensCorr_L=eps_PensCorr_L_fss;
+
+P00	        =	P00_fss	;
+P00_foP00	=	P00_foP00_fss	;
+
+DepRatio_n=
+@#for i in rg
++P@{i}
+@#endfor
+;
+DepRatio_d=
+@#for i in wg
++P@{i}
+@#endfor
+;
+
+DepRatio=DepRatio_n/DepRatio_d;
+
+ZARA=age_early+length_period*(
+@#for i in erg
++1-i@{i}
+@#endfor  
+);
+
+Ptot=
+@#for i in ag
++P@{i}
+@#endfor
+;
+Ptot_f=
+@#for i in ag
++P@{i}_f
+@#endfor
+;
+
+sleep=(1+rr)*(
+@#for i in nbg
++1/beta@{i}*(1-1/beta@{i}^(ann-1))*s@{i-1}*P@{i}
+@#endfor  
+)/(1+gh);
+
+du=rhou*(
+@#for i in wg
++w@{i}*u@{i}*P@{i}
+@#endfor  
+);
+
+de=rhoe*(
+@#for i in erg
++w@{i}*i@{i}*P@{i}+w@{i}_f*i@{i}_f*P@{i}_f
+@#endfor  
+);
+
+dl=
+@#for i in rg
++rhol*wb*PensCorr_L*P@{i}+rhol*wb_f*(N_f/(N+N_f))*PensCorr_F*P@{i}_f
+@#endfor  
+;
+
+inA=(tauw+tauf)*(
+@#for i in wg
++n@{i}*w@{i}*P@{i}+n@{i}_f*w@{i}_f*P@{i}_f
+@#endfor  
+);
+
+inB=tauk*rr*(
+@#for i in nbg
++1/beta@{i}^ann*s@{i-1}*P@{i}
+@#endfor  
+)/(1+gh);
+
+in=tauc*ct+inA+inB+sleep;
+NBR=g*phii*gdp+(du+de+dl)-(in);
+NBRY=NBR/(phii*gdp);
+NBR2=NBR;
+tauf2=tauf;
+tauw2=tauw;
+tauc2=tauc;
+
+end;
+
+%========================================================
+% compute final steady state and check eigenvalues 
+%========================================================
+
+resid;
+steady(solve_algo=3);
+check;
+
+
+% ===================================================
+shocks;     
+% ===================================================
+
+var P00;																																																			
+   periods 1:99;																																																			
+   values (se_P00);																																																			
+ 
+@#for i in nbg
+var beta@{i};																																																			
+   periods  1:99;																																																			
+   values (se_beta@{i});
+var beta@{i}_f;																																																			
+   periods  1:99;																																																			
+   values (se_beta@{i}_f);
+var PD@{i};																																																			
+   periods  1:99;																																																			
+   values (se_PD@{i});
+@#endfor  
+																																																			
+var P00_foP00;																																																			
+   periods 1:99;																																																			
+   values (se_P00_foP00);	 																																																
+
+var eps_g;																																																			
+   periods 1:99;																																																			
+   values (se_eps_g);	
+
+var eps_PensCorr_F;																																																			
+   periods 1:99;																																																			
+   values (se_eps_PensCorr_F);	
+
+var eps_PensCorr_L;																																																			
+   periods 1:99;																																																			
+   values (se_eps_PensCorr_L);	
+
+end;
+
+% *******************************************
+% Numerical Simulation, Control Parameters
+% *******************************************
+
+perfect_foresight_setup(periods=125);
+perfect_foresight_solver(maxit=100);
+
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
+mfs0=load('lola_solve_one_boundary_results');
+
+if max(max(oo_.endo_simul-mfs0.oo_.endo_simul)) > options_.dynatol.x
+   error('Inconsistency with mfs=0')
+end
diff --git a/tests/deterministic_simulations/lola_solve_one_boundary_mfs3.mod b/tests/deterministic_simulations/lola_solve_one_boundary_mfs3.mod
new file mode 100644
index 0000000000000000000000000000000000000000..2a64bd222a446c02abf07026d71939cf35e5feaa
--- /dev/null
+++ b/tests/deterministic_simulations/lola_solve_one_boundary_mfs3.mod
@@ -0,0 +1,985 @@
+// Tests option mfs=3 with block
+
+load lola_data.mat
+
+% ====================================================
+% declarations var -- varexo -- para   
+% ====================================================
+
+@#define nbr_work_generations=9
+@#define nbr_early_generations=2
+@#define nbr_generations=16
+
+parameters
+length_period age_early;
+
+length_period=5;
+age_early=55;
+
+@#define wt=[1]
+
+@#define wg=0:nbr_work_generations-1
+@#define ag=0:nbr_generations-1
+@#define fwg=0:nbr_work_generations-nbr_early_generations-1
+@#define nbwg=1:nbr_work_generations-1
+@#define nbg=1:nbr_generations-1
+@#define rg=nbr_work_generations:nbr_generations-1
+@#define erg=nbr_work_generations-nbr_early_generations:nbr_work_generations-1
+@#define endg=[nbr_generations-1]
+@#define endw=[nbr_work_generations-1]
+
+@#for i in wg
+var 
+n@{i} u@{i} Omega@{i} w@{i} dWHN@{i} dWFN@{i} 
+n@{i}_f u@{i}_f Omega@{i}_f w@{i}_f dWFN@{i}_f
+i@{i} lambda@{i} i@{i}_f lambda@{i}_f eta@{i};
+parameters
+Du@{i} Dn@{i} h@{i} h@{i}_f chi@{i} eta@{i}b; 
+varexo
+eps_eta@{i};
+@#endfor
+
+@#for i in ag
+var 
+c@{i} s@{i} P@{i} P@{i}_f;
+varexo
+beta@{i} beta@{i}_f PD@{i};
+@#endfor
+
+@#for i in erg
+var 
+WE@{i} De_@{i};
+parameters
+De_@{i}b; 
+varexo
+eps_De_@{i};
+@#endfor
+
+var   
+wb wb_f 
+Omega Omega_f Omega_hf 
+V M qq p 
+N N_f 
+Q RR H K Y gdp nx FH pi
+ct st wshare rr 
+gamma mc phii D DH DF X bs bsY P00_f
+
+rhou rhoe rhol tauw tauc tauf tauk g 
+TFP gh rrb
+theta tau1 om1 om2 om2s Ds phijs
+
+DepRatio DepRatio_n DepRatio_d ZARA Ptot Ptot_f sleep du de dl inA inB in 
+NBR NBRY NBR2 tauw2 tauf2 tauc2
+PensCorr_L PensCorr_F;
+
+parameters 
+rho phi delta alpha beta ann 
+fc nu aa 
+
+rhoub rhoeb rholb tauwb taucb taufb taukb gb  
+TFPb ghb rrbb
+thetab tau1b om1b om2b om2sb Dsb phijsb
+
+NBRYb bsY_iss;
+
+varexo
+P00 P00_foP00
+
+eps_rhol eps_tauw eps_tauf eps_tauc eps_tauk
+eps_rhoe eps_rhou eps_TFP eps_gh eps_theta eps_g
+eps_Ds eps_phijs eps_PensCorr_L eps_PensCorr_F;
+
+
+% ============================================================
+% initialization
+% ============================================================
+
+@#for i in wg
+set_param_value('Du@{i}',Du@{i});
+set_param_value('Dn@{i}',Dn@{i});
+set_param_value('h@{i}',h@{i});
+set_param_value('h@{i}_f',h@{i}_f);
+set_param_value('chi@{i}',chi@{i});
+set_param_value('eta@{i}b',eta@{i}b);
+@#endfor
+
+@#for i in erg
+set_param_value('De_@{i}b',De_@{i}b);
+@#endfor
+
+set_param_value('rho',rho);
+set_param_value('phi',phi);
+set_param_value('delta',delta);
+set_param_value('alpha',alpha);
+set_param_value('beta',beta);
+set_param_value('ann',ann);
+set_param_value('fc',fc);
+set_param_value('nu',nu);
+set_param_value('aa',aa);
+
+set_param_value('rhoub',rhoub);
+set_param_value('rhoeb',rhoeb);
+set_param_value('rholb',rholb);
+set_param_value('tauwb',tauwb);
+set_param_value('taucb',taucb);
+set_param_value('taufb',taufb);
+set_param_value('taukb',taukb);
+set_param_value('gb',gb);
+
+set_param_value('TFPb',TFPb);
+set_param_value('ghb',ghb);
+set_param_value('rrbb',rrbb);
+
+set_param_value('thetab',thetab);
+set_param_value('tau1b',tau1b);
+set_param_value('om1b',om1b);
+set_param_value('om2b',om2b);
+set_param_value('om2sb',om2sb);
+set_param_value('Dsb',Dsb);
+set_param_value('phijsb',phijsb);
+
+set_param_value('bsY_iss',bsY_iss);
+
+NBRYb=NBR_iss/(phii_iss*gdp_iss);
+
+
+% =======================================================
+model(block, mfs=3);
+% ======================================================
+
+%  Labor Market Variables in the home country
+%  ------------------------------------------ 
+
+@#for i in fwg
+0=lambda@{i};
+@#endfor
+
+@#for i in wg
+1=n@{i}+u@{i}+i@{i};
+@#endfor   
+                            
+i0=lambda0;
+@#for i in nbwg
+i@{i}=lambda@{i-1}(-1)+lambda@{i}*(1-lambda@{i-1}(-1));
+@#endfor 
+
+P0=beta0*P00+PD0;
+@#for i in nbg
+P@{i}=beta@{i}*P@{i-1}(-1)+PD@{i};
+@#endfor
+
+Omega0=P0;
+@#for i in nbwg
+Omega@{i}=(1-lambda@{i})*( 1-lambda@{i-1}(-1)-(1-chi@{i})*n@{i-1}(-1))*P@{i};
+@#endfor 
+
+n0=p;
+@#for i in nbwg
+n@{i}=(1-lambda@{i})*((1-p)*(1-chi@{i})*n@{i-1}(-1)+p*(1-lambda@{i-1}(-1)));
+@#endfor 
+
+N=
+@#for i in wg
++n@{i}*P@{i}
+@#endfor
+;
+
+%  Labor Market Variables in the foreign country
+%  --------------------------------------------- 
+
+@#for i in wg
+1=n@{i}_f+u@{i}_f+i@{i}_f;
+@#endfor    
+                            
+i0_f=lambda0_f;
+@#for i in nbwg
+i@{i}_f=lambda@{i-1}_f(-1)+lambda@{i}_f*(1-lambda@{i-1}_f(-1));
+@#endfor
+
+% -----------  reproduction cross-border   --------------------
+
+P00_f=P00_foP00*P00;
+
+P0_f=beta0_f*P00_f;
+@#for i in nbg
+P@{i}_f=beta@{i}_f*P@{i-1}_f(-1);
+@#endfor 
+
+Omega0_f=P0_f;
+@#for i in nbwg
+Omega@{i}_f=(1-lambda@{i}_f)*(1-lambda@{i-1}_f(-1)-(1-chi@{i})*n@{i-1}_f(-1))*P@{i}_f;
+@#endfor 
+
+n0_f=p;
+@#for i in nbwg
+n@{i}_f=(1-lambda@{i}_f)*((1-p)*(1-chi@{i})*n@{i-1}_f(-1)+p*(1-lambda@{i-1}_f(-1)));
+@#endfor
+
+N_f=
+@#for i in wg
++n@{i}_f*P@{i}_f
+@#endfor
+;
+
+%  Matching
+% ----------
+
+Omega=
+@#for i in wg
++Omega@{i}
+@#endfor
+;
+
+Omega_f=
+@#for i in wg
++Omega@{i}_f
+@#endfor
+;
+
+Omega_hf=Omega+Omega_f;
+ 
+M=V*Omega_hf/(V^nu+Omega_hf^nu)^(1/nu);
+
+qq=M/V;
+p=M/Omega_hf;
+
+%  Flow Budget Constraints (no bequests)
+% --------------------------------------
+
+rhou*w0*u0+ (1-tauw)*w0*n0 = (1+tauc)*c0+s0;
+@#for i in nbwg
+(1+rr*(1-tauk))/(beta@{i})^ann*s@{i-1}(-1)/(1+gh)+rhou*w@{i}*u@{i}+rhoe*w@{i}*i@{i}+(1-tauw)*w@{i}*n@{i}=(1+tauc)*c@{i}+s@{i};
+@#endfor
+@#for i in rg
+(1+rr*(1-tauk))/(beta@{i})^ann*s@{i-1}(-1)/(1+gh)+rhol*wb=(1+tauc)*c@{i}+s@{i};
+@#endfor
+@#for i in endg
+s@{i}=0;
+@#endfor
+
+wb=
+@#for i in wg
++w@{i}/@{nbr_work_generations}
+@#endfor
+;
+
+%  Euler Conditions
+% ------------------
+
+@#for i in nbg
+1/(1+tauc)/c@{i-1}=beta*(1+rr(+1)*(1-tauk(+1)))/(1+tauc(+1))/c@{i}(+1)*(beta@{i})^(1-ann)/(1+gh);
+@#endfor
+
+
+%  Optimal Participation Rates (Early Retirement)
+%  ----------------------------------------------
+
+@#for i in erg
+WE@{i} = 0;
+@#endfor 
+
+@#for i in erg
+@#if i in endw
+WE@{i} = ((De_@{i}b*i@{i}^(phi-1))+Du@{i}+(rhoe-rhou)*w@{i}/(1+tauc)/c@{i})*(1-i@{i})-((1-tauw-rhou)*w@{i}/(1+tauc)/c@{i}-(Dn@{i}-Du@{i}))*n@{i};
+@#else  
+WE@{i} = ((De_@{i}b*i@{i}^(phi-1))+Du@{i}+(rhoe-rhou)*w@{i}/(1+tauc)/c@{i})*(1-i@{i})-((1-tauw-rhou)*w@{i}/(1+tauc)/c@{i}-(Dn@{i}-Du@{i}))*n@{i}+ beta*beta@{i+1}*WE@{i+1};
+@#endif
+@#endfor  
+
+%  Household Surplus
+% -------------------
+
+@#for i in wg
+@#if i in endw
+dWHN@{i} = w@{i}*(1-tauw-rhou)/(1+tauc)-(Dn@{i}-Du@{i})*c@{i};
+@#else  
+dWHN@{i} = w@{i}*(1-tauw-rhou)/(1+tauc)-(Dn@{i}-Du@{i})*c@{i} + beta*beta@{i+1}*c@{i}/c@{i+1}(+1)*dWHN@{i+1}(+1)*(1-p(+1))*(1-chi@{i+1})*(1-lambda@{i+1}(+1));
+@#endif
+@#endfor    
+
+%  Foreign household
+%  ------------------------
+%  participation and wages
+% ........................
+
+@#for i in wg
+lambda@{i}=lambda@{i}_f;
+w@{i}_f=w@{i}; 
+@#endfor
+
+wb_f=
+@#for i in wg
++w@{i}_f/@{nbr_work_generations}
+@#endfor
+;
+
+%  Firm's Behavior
+% -------------------
+
+H=
+@#for i in wg
++h@{i}*n@{i}*P@{i}+h@{i}_f*n@{i}_f*P@{i}_f
+@#endfor
+;
+
+wshare=(1+tauf)*(
+@#for i in wg
++w@{i}*n@{i}*P@{i}+w@{i}_f*n@{i}_f*P@{i}_f
+@#endfor
+)/(phii*gdp);
+
+Y=TFP*H^(1-alpha)*(K)^alpha;
+gdp= TFP*H^(1-alpha)*(K)^alpha-aa*V/phii-fc/phii;
+pi = phii*gdp - wshare*phii*gdp - (rr+delta)*K(-1)/(1+gh);
+(rr(+1)+delta)/(1+rr(+1)*(1-tauk(+1))) = mc*TFP*alpha*(H/(K))^(1-alpha);
+FH=TFP*(1-alpha)*((K)/H)^alpha;
+
+RR=1+rr*(1-tauk);
+rr=rrb+tau1*(exp(bsY_iss-bsY)-1);
+
+%  Firm's Surplus
+%  ---------------------
+
+@#for i in wg
+@#if i in endw
+dWFN@{i} = h@{i}*mc*FH-(1+tauf)*w@{i};
+dWFN@{i}_f = h@{i}_f*mc*FH-(1+tauf)*w@{i}_f;
+@#else  
+dWFN@{i} = h@{i}*mc*FH-(1+tauf)*w@{i} + beta@{i+1}/RR(+1)*dWFN@{i+1}(+1)*(1-chi@{i+1})*(1-lambda@{i+1}(+1))*(1+gh);
+dWFN@{i}_f = h@{i}_f*mc*FH-(1+tauf)*w@{i}_f + beta@{i+1}_f/RR(+1)*dWFN@{i+1}_f(+1)*(1-chi@{i+1})*(1-lambda@{i+1}_f(+1))*(1+gh);
+@#endif
+@#endfor
+
+%  Free Entry Condition
+%  ---------------------
+
+aa=qq/Omega_hf*(
+@#for i in wg
++Omega@{i}*dWFN@{i}+Omega@{i}_f*dWFN@{i}_f
+@#endfor
+);
+
+%  Wage Determination (Rent Sharing)
+%  -----------------------------------
+
+@#for i in wg
+(1-eta@{i})*dWHN@{i}  =  eta@{i}*((1-tauw)/(1+tauf)/(1+tauc))*dWFN@{i};
+@#endfor
+
+%  Equilibrium Conditions
+%  ----------------------
+
+ct=
+@#for i in ag
++c@{i}*P@{i}
+@#endfor
+;
+
+st=
+@#for i in ag
++s@{i}*P@{i}
+@#endfor
+;
+
+%  Non-Arbitrage condition (physical capital-shares)
+% .........................
+
+Q(+1)+pi(+1)=(1+rr(+1))*Q/(1+gh);
+
+%  New Open Economy Macroeconomics (NOEM)
+%  ---------------------------------------
+
+phii=mc/theta;
+D= ct + K-(1-delta)*K(-1)/(1+gh)  + g*gdp*phii + fc+aa*V;
+DH=(1/om1*phii)^(1/(rho-1))*D;
+X=(1/om2s*phii/gamma)^(1/(rho-1))*Ds;
+DF=(1/om2*gamma*phijs)^(1/(rho-1))*D;
+nx=phii*X-phijs*gamma*DF;     
+bsY=bs/(phii*gdp);
+Y=DH+X;
+phii*gdp=ct + K-(1-delta)*K(-1)/(1+gh) + g*gdp*phii+nx;
+
+st=K+Q +bs ;
+
+%  Policies
+%  ----------
+
+rhou=rhoub*eps_rhou;
+rhoe=rhoeb*eps_rhoe;
+rhol=rholb*eps_rhol;
+g=gb*eps_g;
+
+@#for i in erg
+De_@{i}=De_@{i}b*eps_De_@{i};
+@#endfor
+
+TFP=TFPb*eps_TFP;
+gh=ghb*eps_gh;
+
+@#for i in wg
+eta@{i}=eta@{i}b*eps_eta@{i};
+@#endfor
+
+rrb=rrbb;
+
+theta=thetab*eps_theta;
+tau1=tau1b;
+om1=om1b;
+om2=om2b;
+om2s=om2sb;
+Ds=Dsb*eps_Ds;
+phijs=phijsb*eps_phijs;
+
+
+% ----------- RefDR scenario 
+
+DepRatio_n=
+@#for i in rg
++P@{i}
+@#endfor
+;
+DepRatio_d=
+@#for i in wg
++P@{i}
+@#endfor
+;
+
+DepRatio=DepRatio_n/DepRatio_d;
+
+ZARA=age_early+length_period*(
+@#for i in erg
++1-i@{i}
+@#endfor  
+);
+
+% ----------- WGEM 
+
+Ptot=
+@#for i in ag
++P@{i}
+@#endfor
+;
+Ptot_f=
+@#for i in ag
++P@{i}_f
+@#endfor
+;
+
+sleep=(1+rr)*(
+@#for i in nbg
++1/beta@{i}*(1-1/beta@{i}^(ann-1))*s@{i-1}(-1)*P@{i}
+@#endfor  
+)/(1+gh);
+
+du=rhou*(
+@#for i in wg
++w@{i}*u@{i}*P@{i}
+@#endfor  
+);
+
+de=rhoe*(
+@#for i in erg
++w@{i}*i@{i}*P@{i}+w@{i}_f*i@{i}_f*P@{i}_f
+@#endfor  
+);
+
+dl=
+@#for i in rg
++rhol*wb*PensCorr_L*P@{i}+rhol*wb_f*(N_f/(N+N_f))*PensCorr_F*P@{i}_f
+@#endfor  
+;
+
+PensCorr_L=eps_PensCorr_L; 
+PensCorr_F=eps_PensCorr_F;   
+
+inA=(tauw+tauf)*(
+@#for i in wg
++n@{i}*w@{i}*P@{i}+n@{i}_f*w@{i}_f*P@{i}_f
+@#endfor  
+);
+
+inB=tauk*rr*(
+@#for i in nbg
++1/beta@{i}^ann*s@{i-1}(-1)*P@{i}
+@#endfor  
+)/(1+gh);
+
+in=tauc*ct+inA+inB+sleep;
+NBR=g*phii*gdp+(du+de+dl)-(in);
+NBRY=NBR/(phii*gdp);
+
+% ----------- WGEM Adjustment variable ---------------
+
+tauf2=tauf;
+tauw2=tauw;
+NBR2=NBR;
+tauc2=tauc;
+tauf=taufb*eps_tauf;
+%----- WGEM: adjustment through tauc
+tauc=taucb*eps_tauc;
+%----- WGEM: adjustment through tauk
+tauk=taukb*eps_tauk;
+%----- WGEM: adjustment through tauw
+tauw=tauwb*eps_tauw;
+
+end;
+
+%==================================
+initval;
+%==================================
+
+@#for i in wg
+n@{i}=n@{i}_iss;
+n@{i}_f=n@{i}_f_iss;
+u@{i}=u@{i}_iss;
+u@{i}_f=u@{i}_f_iss;
+Omega@{i}=Omega@{i}_iss;
+Omega@{i}_f=Omega@{i}_f_iss;
+w@{i}=w@{i}_iss;
+w@{i}_f=w@{i}_f_iss;
+dWHN@{i}=dWHN@{i}_iss;
+dWFN@{i}=dWFN@{i}_iss;
+dWFN@{i}_f=dWFN@{i}_f_iss;
+eps_eta@{i}=eps_eta@{i}_iss;
+eta@{i}=eta@{i}b*eps_eta@{i};
+@#endfor
+
+@#for i in erg
+i@{i}=i@{i}_iss;
+lambda@{i}=lambda@{i}_iss;
+i@{i}_f=i@{i}_f_iss;
+lambda@{i}_f=lambda@{i}_f_iss;
+WE@{i}=0;
+eps_De_@{i}=eps_De_@{i}_iss;
+De_@{i}=De_@{i}b*eps_De_@{i}_iss;
+@#endfor
+
+@#for i in fwg
+i@{i}=0;
+lambda@{i}=0;
+i@{i}_f=0;
+lambda@{i}_f=0;
+@#endfor
+
+@#for i in ag
+@#if i in endg
+s@{i}=0;
+@#else
+s@{i}=s@{i}_iss;
+@#endif
+@#endfor
+
+@#for i in ag
+beta@{i}=beta@{i}_iss;
+beta@{i}_f=beta@{i}_f_iss;
+PD@{i}=PD@{i}_iss;
+c@{i}=c@{i}_iss;
+P@{i}=P@{i}_iss;
+P@{i}_f=P@{i}_f_iss;
+@#endfor
+
+wb          =   wb_iss;
+wb_f        =   wb_f_iss;
+Omega       =   Omega_iss;
+Omega_f     =   Omega_f_iss;
+Omega_hf    =   Omega_hf_iss;
+V        	=	V_iss	;
+M        	=	M_iss	;
+qq       	=	qq_iss	;
+p        	=	p_iss	;
+N        	=	N_iss	;
+N_f      	=	N_f_iss	;
+Q        	=	Q_iss	;
+RR       	=	RR_iss	;
+H        	=	H_iss	;
+K        	=	K_iss	;
+Y        	=	Y_iss	;
+gdp      	=	gdp_iss	;
+nx       	=	nx_iss	;
+FH       	=	FH_iss	;
+pi       	=	pi_iss	;
+ct       	=	ct_iss	;
+st       	=	st_iss	;
+wshare   	=	wshare_iss	;
+rr       	=	rr_iss	;
+
+gamma    	=	gamma_iss	;
+mc       	=	mc_iss	;
+phii     	=	phii_iss	;
+D        	=	D_iss	;
+DH       	=	DH_iss	;
+DF       	=	DF_iss	;
+X        	=	X_iss	;
+bs       	=	bs_iss	;
+bsY      	=	bsY_iss	;
+P00_f       =   P00_f_iss;
+
+eps_rhol=eps_rhol_iss;
+eps_rhoe=eps_rhoe_iss;
+eps_rhou=eps_rhou_iss;
+rhou=rhoub*eps_rhou_iss;
+rhoe=rhoeb*eps_rhoe_iss;
+rhol=rholb*eps_rhol_iss;
+eps_tauc=eps_tauc_iss;
+eps_tauk=eps_tauk_iss;
+eps_tauw=eps_tauw_iss;
+eps_tauf=eps_tauf_iss;
+tauw=tauwb*eps_tauw;
+tauc=taucb*eps_tauc;
+tauf=taufb*eps_tauf;
+tauk=taukb*eps_tauk;
+eps_theta=eps_theta_iss;
+eps_gh=eps_gh_iss;
+eps_TFP=eps_TFP_iss;
+eps_g=eps_g_iss;
+g=gb*eps_g_iss;
+TFP=TFPb*eps_TFP_iss;
+gh=ghb*eps_gh_iss;
+theta=thetab*eps_theta_iss;
+
+rrb=rrbb;
+tau1=tau1b;
+om1=om1b;
+om2=om2b;
+om2s=om2sb;
+
+eps_Ds=1;
+eps_phijs=1;
+Ds=Dsb*eps_Ds;
+phijs=phijsb*eps_phijs;
+
+eps_PensCorr_F=eps_PensCorr_F_iss;
+eps_PensCorr_L=eps_PensCorr_L_iss;
+PensCorr_F=eps_PensCorr_F_iss;
+PensCorr_L=eps_PensCorr_L_iss;
+
+P00	        =	P00_iss	;
+P00_foP00	=	P00_foP00_iss	;
+
+DepRatio_n=
+@#for i in rg
++P@{i}
+@#endfor
+;
+DepRatio_d=
+@#for i in wg
++P@{i}
+@#endfor
+;
+
+DepRatio=DepRatio_n/DepRatio_d;
+
+ZARA=age_early+length_period*(
+@#for i in erg
++1-i@{i}
+@#endfor  
+);
+
+Ptot=Ptot_iss;
+Ptot_f=Ptot_f_iss;
+sleep=sleep_iss;
+du=du_iss;
+de=de_iss;
+dl=dl_iss;
+
+inA=inA_iss;%(tauw+tauf)*(
+%@#for i in wg
+%+n@{i}*w@{i}*P@{i}+n@{i}_f*w@{i}_f*P@{i}_f
+%@#endfor  
+%);
+
+inB=inB_iss;%tauk*rr*(
+%@#for i in nbg
+%+1/beta@{i}^ann*s@{i-1}*P@{i}
+%@#endfor  
+%)/(1+gh);
+
+in=in_iss;%tauc*ct+inA+inB+sleep;
+NBR=NBR_iss;%g*phii*gdp+(du+de+dl)-(in);
+NBRY=NBR/(phii*gdp);
+NBR2=NBR;
+tauf2=tauf;
+tauw2=tauw;
+tauc2=tauc;
+
+end;
+
+%========================================================
+% compute initial steady state and check eigenvalues 
+%========================================================
+
+resid;
+steady(solve_algo=3);
+check;
+
+%========================================================
+endval;
+%========================================================
+
+@#for i in wg
+n@{i}=n@{i}_fss;
+n@{i}_f=n@{i}_f_fss;
+u@{i}=u@{i}_fss;
+u@{i}_f=u@{i}_f_fss;
+Omega@{i}=Omega@{i}_fss;
+Omega@{i}_f=Omega@{i}_f_fss;
+w@{i}=w@{i}_fss;
+w@{i}_f=w@{i}_f_fss;
+dWHN@{i}=dWHN@{i}_fss;
+dWFN@{i}=dWFN@{i}_fss;
+dWFN@{i}_f=dWFN@{i}_f_fss;
+eps_eta@{i}=eps_eta@{i}_fss;
+eta@{i}=eta@{i}b*eps_eta@{i};
+@#endfor
+
+@#for i in erg
+i@{i}=i@{i}_fss;
+lambda@{i}=lambda@{i}_fss;
+i@{i}_f=i@{i}_f_fss;
+lambda@{i}_f=lambda@{i}_f_fss;
+WE@{i}=0;
+eps_De_@{i}=eps_De_@{i}_fss;
+De_@{i}=De_@{i}b*eps_De_@{i}_fss;
+@#endfor
+
+@#for i in fwg
+i@{i}=0;
+lambda@{i}=0;
+i@{i}_f=0;
+lambda@{i}_f=0;
+@#endfor
+
+@#for i in ag
+@#if i in endg
+s@{i}=0;
+@#else
+s@{i}=s@{i}_fss;
+@#endif
+@#endfor
+
+@#for i in ag
+beta@{i}=beta@{i}_fss;
+beta@{i}_f=beta@{i}_f_fss;
+PD@{i}=PD@{i}_fss;
+c@{i}=c@{i}_fss;
+P@{i}=P@{i}_fss;
+P@{i}_f=P@{i}_f_fss;
+@#endfor
+
+wb          =   wb_fss;
+wb_f        =   wb_f_fss;
+Omega       =   Omega_fss;
+Omega_f     =   Omega_f_fss;
+Omega_hf    =   Omega_hf_fss;
+V        	=	V_fss	;
+M        	=	M_fss	;
+qq       	=	qq_fss	;
+p        	=	p_fss	;
+N        	=	N_fss	;
+N_f      	=	N_f_fss	;
+Q        	=	Q_fss	;
+RR       	=	RR_fss	;
+H        	=	H_fss	;
+K        	=	K_fss	;
+Y        	=	Y_fss	;
+gdp      	=	gdp_fss	;
+nx       	=	nx_fss	;
+FH       	=	FH_fss	;
+pi       	=	pi_fss	;
+ct       	=	ct_fss	;
+st       	=	st_fss	;
+wshare   	=	wshare_fss	;
+rr       	=	rr_fss	;
+
+gamma    	=	gamma_fss	;
+mc       	=	mc_fss	;
+phii     	=	phii_fss	;
+D        	=	D_fss	;
+DH       	=	DH_fss	;
+DF       	=	DF_fss	;
+X        	=	X_fss	;
+bs       	=	bs_fss	;
+bsY      	=	bsY_fss	;
+P00_f       =   P00_f_fss;
+
+eps_rhol=eps_rhol_fss;
+eps_rhoe=eps_rhoe_fss;
+eps_rhou=eps_rhou_fss;
+rhou=rhoub*eps_rhou_fss;
+rhoe=rhoeb*eps_rhoe_fss;
+rhol=rholb*eps_rhol_fss;
+eps_tauc=eps_tauc_fss;
+eps_tauk=eps_tauk_fss;
+eps_tauw=eps_tauw_fss;
+eps_tauf=eps_tauf_fss;
+tauw=tauwb*eps_tauw;
+tauc=taucb*eps_tauc;
+tauf=taufb*eps_tauf;
+tauk=taukb*eps_tauk;
+eps_theta=eps_theta_fss;
+eps_gh=eps_gh_fss;
+eps_TFP=eps_TFP_fss;
+eps_g=eps_g_fss;
+g=gb*eps_g_fss;
+TFP=TFPb*eps_TFP_fss;
+gh=ghb*eps_gh_fss;
+theta=thetab*eps_theta_fss;
+
+rrb=rrbb;
+tau1=tau1b;
+om1=om1b;
+om2=om2b;
+om2s=om2sb;
+
+eps_Ds=1;
+eps_phijs=1;
+Ds=Dsb*eps_Ds;
+phijs=phijsb*eps_phijs;
+
+eps_PensCorr_F=eps_PensCorr_F_fss;
+eps_PensCorr_L=eps_PensCorr_L_fss;
+PensCorr_F=eps_PensCorr_F_fss;
+PensCorr_L=eps_PensCorr_L_fss;
+
+P00	        =	P00_fss	;
+P00_foP00	=	P00_foP00_fss	;
+
+DepRatio_n=
+@#for i in rg
++P@{i}
+@#endfor
+;
+DepRatio_d=
+@#for i in wg
++P@{i}
+@#endfor
+;
+
+DepRatio=DepRatio_n/DepRatio_d;
+
+ZARA=age_early+length_period*(
+@#for i in erg
++1-i@{i}
+@#endfor  
+);
+
+Ptot=
+@#for i in ag
++P@{i}
+@#endfor
+;
+Ptot_f=
+@#for i in ag
++P@{i}_f
+@#endfor
+;
+
+sleep=(1+rr)*(
+@#for i in nbg
++1/beta@{i}*(1-1/beta@{i}^(ann-1))*s@{i-1}*P@{i}
+@#endfor  
+)/(1+gh);
+
+du=rhou*(
+@#for i in wg
++w@{i}*u@{i}*P@{i}
+@#endfor  
+);
+
+de=rhoe*(
+@#for i in erg
++w@{i}*i@{i}*P@{i}+w@{i}_f*i@{i}_f*P@{i}_f
+@#endfor  
+);
+
+dl=
+@#for i in rg
++rhol*wb*PensCorr_L*P@{i}+rhol*wb_f*(N_f/(N+N_f))*PensCorr_F*P@{i}_f
+@#endfor  
+;
+
+inA=(tauw+tauf)*(
+@#for i in wg
++n@{i}*w@{i}*P@{i}+n@{i}_f*w@{i}_f*P@{i}_f
+@#endfor  
+);
+
+inB=tauk*rr*(
+@#for i in nbg
++1/beta@{i}^ann*s@{i-1}*P@{i}
+@#endfor  
+)/(1+gh);
+
+in=tauc*ct+inA+inB+sleep;
+NBR=g*phii*gdp+(du+de+dl)-(in);
+NBRY=NBR/(phii*gdp);
+NBR2=NBR;
+tauf2=tauf;
+tauw2=tauw;
+tauc2=tauc;
+
+end;
+
+%========================================================
+% compute final steady state and check eigenvalues 
+%========================================================
+
+resid;
+steady(solve_algo=3);
+check;
+
+
+% ===================================================
+shocks;     
+% ===================================================
+
+var P00;																																																			
+   periods 1:99;																																																			
+   values (se_P00);																																																			
+ 
+@#for i in nbg
+var beta@{i};																																																			
+   periods  1:99;																																																			
+   values (se_beta@{i});
+var beta@{i}_f;																																																			
+   periods  1:99;																																																			
+   values (se_beta@{i}_f);
+var PD@{i};																																																			
+   periods  1:99;																																																			
+   values (se_PD@{i});
+@#endfor  
+																																																			
+var P00_foP00;																																																			
+   periods 1:99;																																																			
+   values (se_P00_foP00);	 																																																
+
+var eps_g;																																																			
+   periods 1:99;																																																			
+   values (se_eps_g);	
+
+var eps_PensCorr_F;																																																			
+   periods 1:99;																																																			
+   values (se_eps_PensCorr_F);	
+
+var eps_PensCorr_L;																																																			
+   periods 1:99;																																																			
+   values (se_eps_PensCorr_L);	
+
+end;
+
+% *******************************************
+% Numerical Simulation, Control Parameters
+% *******************************************
+
+perfect_foresight_setup(periods=125);
+perfect_foresight_solver(maxit=100);
+
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
+mfs0=load('lola_solve_one_boundary_results');
+
+if max(max(oo_.endo_simul-mfs0.oo_.endo_simul)) > options_.dynatol.x
+   error('Inconsistency with mfs=0')
+end
diff --git a/tests/deterministic_simulations/multiple_lead_lags/sim_exo_lead_lag.mod b/tests/deterministic_simulations/multiple_lead_lags/sim_exo_lead_lag.mod
index 1beb0d40086d5f8a640a928cd477d59627ae5df8..fa0c3d384e21d57bbe2c69dc91d55e071b80e9bb 100644
--- a/tests/deterministic_simulations/multiple_lead_lags/sim_exo_lead_lag.mod
+++ b/tests/deterministic_simulations/multiple_lead_lags/sim_exo_lead_lag.mod
@@ -1,4 +1,4 @@
-// Same model as sim_exo_lead_lag_aux_vars.mod, but no auxiliary variables to deal with leads and lags
+// Same model as sim_exo_lead_lag_aux_vars.mod, but no user-crafted auxiliary variables to deal with leads and lags
 
 var c k z_forward z_backward;
 varexo x;
@@ -53,7 +53,7 @@ end
 clear base_results
 base_results_aux_vars=load('sim_exo_lead_lag_aux_vars_results.mat');
 
-if max(abs(base_results_aux_vars.oo_.endo_simul(strmatch('x_lag_3',base_results_aux_vars.M_.endo_names,'exact'),1:end-base_results_aux_vars.M_.maximum_lead-1)' -...
-    oo_.exo_simul(1:end-M_.maximum_lead-M_.maximum_lag,strmatch('x', M_.exo_names, 'exact'))))>1e-8 
+if max(abs(base_results_aux_vars.oo_.endo_simul(strmatch('x_lag_3',base_results_aux_vars.M_.endo_names,'exact'),base_results_aux_vars.M_.maximum_lag+3:end-base_results_aux_vars.M_.maximum_lead)' -...
+    oo_.exo_simul(M_.maximum_lag:end-M_.maximum_lead-3,strmatch('x', M_.exo_names, 'exact'))))>1e-8
     error('Translation of aux vars is wrong')
-end
\ No newline at end of file
+end
diff --git a/tests/deterministic_simulations/multiple_lead_lags/sim_lead_lag.mod b/tests/deterministic_simulations/multiple_lead_lags/sim_lead_lag.mod
index e068856ef1231354e2839cb4244500e014f95fae..d39ce7c7b859d8e945413ca56b18932af430f122 100644
--- a/tests/deterministic_simulations/multiple_lead_lags/sim_lead_lag.mod
+++ b/tests/deterministic_simulations/multiple_lead_lags/sim_lead_lag.mod
@@ -1,4 +1,4 @@
-// Same model as sim_lead_lag_aux_vars.mod, but no auxiliary variables to deal with leads and lags
+// Same model as sim_lead_lag_aux_vars.mod, but no user-crafted auxiliary variables to deal with leads and lags
 
 var c k z_forward z_backward;
 varexo x;
@@ -57,7 +57,7 @@ end
 clear base_results
 base_results_aux_vars=load('sim_lead_lag_aux_vars_results.mat');
 
-if max(abs(base_results_aux_vars.oo_.endo_simul(strmatch('x_lag_3',base_results_aux_vars.M_.endo_names,'exact'),1:end-base_results_aux_vars.M_.maximum_lead-1)' -...
-    oo_.exo_simul(1:end-M_.maximum_lead-M_.maximum_lag,strmatch('x', M_.exo_names, 'exact'))))>1e-8 
+if max(abs(base_results_aux_vars.oo_.endo_simul(strmatch('x_lag_3',base_results_aux_vars.M_.endo_names,'exact'),base_results_aux_vars.M_.maximum_lag+3:end-base_results_aux_vars.M_.maximum_lead)' -...
+    oo_.exo_simul(M_.maximum_lag:end-M_.maximum_lead-3,strmatch('x', M_.exo_names, 'exact'))))>1e-8
     error('Translation of aux vars is wrong')
-end
\ No newline at end of file
+end
diff --git a/tests/deterministic_simulations/ramst_block_mfs1.mod b/tests/deterministic_simulations/ramst_block_mfs1.mod
new file mode 100644
index 0000000000000000000000000000000000000000..7b9017cfa79257db6efecb457eb67ae939492d84
--- /dev/null
+++ b/tests/deterministic_simulations/ramst_block_mfs1.mod
@@ -0,0 +1,49 @@
+/* This model has a solve forward simple block that contains a recursive variable (a)
+ and a feedback one (b).
+ Regression test for bug fixed in preprocessor@740ea833f6b4a93c260b32e62f4302483af54f7a */
+
+var c k a b;
+varexo x e u;
+
+parameters alph gam delt bet aa rho tau;
+alph=0.5;
+gam=0.5;
+delt=0.02;
+bet=0.05;
+aa=0.5;
+rho   = 0.95;
+tau   = 0.025;
+
+
+model(block, mfs=1);
+c + k - aa*x*k(-1)^alph - (1-delt)*k(-1);
+c^(-gam) - (1+bet)^(-1)*(aa*alph*x(+1)*k^(alph-1) + 1 - delt)*c(+1)^(-gam);
+a = tau*b + e;
+b = tau*a+rho*b(-1) + u;
+end;
+
+initval;
+x = 1;
+k = ((delt+bet)/(1.0*aa*alph))^(1/(alph-1));
+c = aa*k^alph-delt*k;
+end;
+
+steady;
+
+check;
+
+shocks;
+  var x;
+  periods 1;
+  values 1.2;
+  var u;
+  periods 1;
+  values 1;
+end;
+
+model_info;
+
+perfect_foresight_setup(periods=200);
+perfect_foresight_solver;
+
+rplot a;
diff --git a/tests/deterministic_simulations/rbc_det_exo_lag_2b.mod b/tests/deterministic_simulations/rbc_det_exo_lag_2b.mod
index 8f44c36fbb7faa6ab10cc4b124e1f3deea645c2e..8965fc18f1ddafee9f9bc457c1482ad1c828f6dc 100644
--- a/tests/deterministic_simulations/rbc_det_exo_lag_2b.mod
+++ b/tests/deterministic_simulations/rbc_det_exo_lag_2b.mod
@@ -81,4 +81,4 @@ rplot Capital;
 
 O=load('rbc_det_exo_lag_2a_results');
 
-fataltest(oo_.endo_simul(:,2:end),O.oo_.endo_simul,1);
+fataltest(oo_.endo_simul(1:M_.orig_endo_nbr,:),O.oo_.endo_simul(1:O.M_.orig_endo_nbr,:),1);
diff --git a/tests/deterministic_simulations/rbc_det_exo_lag_2c.mod b/tests/deterministic_simulations/rbc_det_exo_lag_2c.mod
index 4d52ea0323f9c4c344cbf75162cef81954eb74b8..a1b5c2ae0dd8a2c6ffd1679f9780c4c0a333c372 100644
--- a/tests/deterministic_simulations/rbc_det_exo_lag_2c.mod
+++ b/tests/deterministic_simulations/rbc_det_exo_lag_2c.mod
@@ -81,4 +81,4 @@ rplot Capital;
 
 O=load('rbc_det_exo_lag_2a_results');
 
-fataltest(oo_.endo_simul(:,2:end),O.oo_.endo_simul,1);
+fataltest(oo_.endo_simul(1:M_.orig_endo_nbr,:),O.oo_.endo_simul(1:O.M_.orig_endo_nbr,:),1);
diff --git a/tests/deterministic_simulations/rbc_det_stack_solve_algo_7_exo_lag.mod b/tests/deterministic_simulations/rbc_det_stack_solve_algo_7_exo_lag.mod
index 8047da20b3d95b90e77f8951ce944ffdc9ab96aa..e449069044671b0677128cbcde38d533f2c56052 100644
--- a/tests/deterministic_simulations/rbc_det_stack_solve_algo_7_exo_lag.mod
+++ b/tests/deterministic_simulations/rbc_det_stack_solve_algo_7_exo_lag.mod
@@ -83,8 +83,8 @@ rplot Capital;
 
 D = load('rbc_det_results');
 
-if norm(D.oo_.endo_simul(:,D.M_.maximum_lag+1:end-D.M_.maximum_lead) - oo_.endo_simul(:,M_.maximum_lag+1:end-M_.maximum_lead)) > 1e-30;
-   disp(D.oo_.endo_simul(:,D.M_.maximum_lag+1:end-D.M_.maximum_lead) - oo_.endo_simul(:,M_.maximum_lag+1:end-M_.maximum_lead));
+if norm(D.oo_.endo_simul(1:D.M_.orig_endo_nbr,D.M_.maximum_lag+1:end-D.M_.maximum_lead) - oo_.endo_simul(1:M_.orig_endo_nbr,M_.maximum_lag+1:end-M_.maximum_lead)) > 1e-30;
+   disp(D.oo_.endo_simul(1:D.M_.orig_endo_nbr,D.M_.maximum_lag+1:end-D.M_.maximum_lead) - oo_.endo_simul(1:M_.orig_endo_nbr,M_.maximum_lag+1:end-M_.maximum_lead));
    error('rbc_det_stack_solve_algo_7 failed');
 end;                       
 
@@ -109,8 +109,8 @@ if isoctave && options_.solve_algo==0
 else
     tol_crit=1e-8;    
 end
-if norm(D.oo_.endo_simul(:,D.M_.maximum_lag+1:end-D.M_.maximum_lead) - oo_.endo_simul(:,M_.maximum_lag+1:end-M_.maximum_lead)) > tol_crit;
-    disp(D.oo_.endo_simul(:,D.M_.maximum_lag+1:end-D.M_.maximum_lead) - oo_.endo_simul(:,M_.maximum_lag+1:end-M_.maximum_lead));
+if norm(D.oo_.endo_simul(1:D.M_.orig_endo_nbr,D.M_.maximum_lag+1:end-D.M_.maximum_lead) - oo_.endo_simul(1:M_.orig_endo_nbr,M_.maximum_lag+1:end-M_.maximum_lead)) > tol_crit;
+    disp(D.oo_.endo_simul(1:D.M_.orig_endo_nbr,D.M_.maximum_lag+1:end-D.M_.maximum_lead) - oo_.endo_simul(1:M_.orig_endo_nbr,M_.maximum_lag+1:end-M_.maximum_lead));
     error(sprintf('rbc_det_stack_solve_algo_7 failed with solve_algo=%u',options_.solve_algo));
 end;
-@#endfor
\ No newline at end of file
+@#endfor
diff --git a/tests/deterministic_simulations/rbc_det_stack_solve_algo_7_exo_lead.mod b/tests/deterministic_simulations/rbc_det_stack_solve_algo_7_exo_lead.mod
index 6ee43a4560775dd1eb9eb5950d51e01a3a405868..9d649d90236d68457ce6c76016147187bff694d1 100644
--- a/tests/deterministic_simulations/rbc_det_stack_solve_algo_7_exo_lead.mod
+++ b/tests/deterministic_simulations/rbc_det_stack_solve_algo_7_exo_lead.mod
@@ -83,8 +83,8 @@ rplot Capital;
 
 D = load('rbc_det_results');
 
-if norm(D.oo_.endo_simul(:,D.M_.maximum_lag+1:end-D.M_.maximum_lead) - oo_.endo_simul(:,M_.maximum_lag+1:end-M_.maximum_lead)) > 1e-30;
-   disp(D.oo_.endo_simul(:,D.M_.maximum_lag+1:end-D.M_.maximum_lead) - oo_.endo_simul(:,M_.maximum_lag+1:end-M_.maximum_lead));
+if norm(D.oo_.endo_simul(1:D.M_.orig_endo_nbr,D.M_.maximum_lag+1:end-D.M_.maximum_lead) - oo_.endo_simul(1:M_.orig_endo_nbr,M_.maximum_lag+1:end-M_.maximum_lead)) > 1e-30;
+   disp(D.oo_.endo_simul(1:D.M_.orig_endo_nbr,D.M_.maximum_lag+1:end-D.M_.maximum_lead) - oo_.endo_simul(1:M_.orig_endo_nbr,M_.maximum_lag+1:end-M_.maximum_lead));
    error('rbc_det_stack_solve_algo_7 failed');
 end;                       
 
@@ -109,8 +109,8 @@ if isoctave && options_.solve_algo==0
 else
     tol_crit=1e-8;    
 end
-if norm(D.oo_.endo_simul(:,D.M_.maximum_lag+1:end-D.M_.maximum_lead) - oo_.endo_simul(:,M_.maximum_lag+1:end-M_.maximum_lead)) > tol_crit;
-    disp(D.oo_.endo_simul(:,D.M_.maximum_lag+1:end-D.M_.maximum_lead) - oo_.endo_simul(:,M_.maximum_lag+1:end-M_.maximum_lead));
+if norm(D.oo_.endo_simul(1:D.M_.orig_endo_nbr,D.M_.maximum_lag+1:end-D.M_.maximum_lead) - oo_.endo_simul(1:M_.orig_endo_nbr,M_.maximum_lag+1:end-M_.maximum_lead)) > tol_crit;
+    disp(D.oo_.endo_simul(1:D.M_.orig_endo_nbr,D.M_.maximum_lag+1:end-D.M_.maximum_lead) - oo_.endo_simul(1:M_.orig_endo_nbr,M_.maximum_lag+1:end-M_.maximum_lead));
     error(sprintf('rbc_det_stack_solve_algo_7 failed with solve_algo=%u',options_.solve_algo));
 end;
-@#endfor
\ No newline at end of file
+@#endfor
diff --git a/tests/discretionary_policy/Gali_2015_chapter_3.mod b/tests/discretionary_policy/Gali_2015_chapter_3.mod
new file mode 100644
index 0000000000000000000000000000000000000000..ac48a5eee9f744ebc8c1fa88a7c2777387e61de9
--- /dev/null
+++ b/tests/discretionary_policy/Gali_2015_chapter_3.mod
@@ -0,0 +1,163 @@
+/*
+ * This file implements the baseline New Keynesian model of Jordi Gal� (2015): Monetary Policy, Inflation,
+ * and the Business Cycle, Princeton University Press, Second Edition, Chapter 3
+ * 
+ * THIS MOD-FILE REQUIRES DYNARE 4.5 OR HIGHER
+ *
+ * Notes:
+ *  - all model variables are expressed in deviations from steady state, i.e. in contrast to
+ *      to the chapter, both the nominal interest rate and natural output are not in log-levels, but rather mean 0
+ *
+ * This implementation was written by Johannes Pfeifer. In case you spot mistakes,
+ * email me at jpfeifer@gmx.de
+ *
+ * Please note that the following copyright notice only applies to this Dynare 
+ * implementation of the model.
+ */
+
+/*
+ * Copyright (C) 2016-20 Johannes Pfeifer
+ * Copyright (C) 2020 Dynare Team
+ *
+ * This 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.
+ *
+ * It 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.
+ *
+ * For a copy of the GNU General Public License,
+ * see <http://www.gnu.org/licenses/>.
+ */
+
+
+var pi          ${\pi}$                 (long_name='inflation')
+    y_gap       ${\tilde y}$            (long_name='output gap')
+    y_nat       ${y^{nat}}$             (long_name='natural output')      //(in contrast to the textbook defined in deviation from steady state)
+    y           ${y}$                   (long_name='output')
+    yhat        ${\hat y}$              (long_name='output deviation from steady state')
+    r_nat       ${r^{nat}}$             (long_name='natural interest rate')
+    r_real      ${r^r}$                 (long_name='real interest rate')     
+    i           ${i}$                   (long_name='nominal interrst rate')
+    n           ${n}$                   (long_name='hours worked')
+    m_real      ${m-p}$                 (long_name='real money stock')
+    m_growth_ann ${\Delta m}$           (long_name='money growth annualized')
+    m_nominal   ${m}$                   (long_name='nominal money stock')
+    a           ${a}$                   (long_name='AR(1) technology shock process')
+    r_real_ann  ${r^{r,ann}}$           (long_name='annualized real interest rate')
+    i_ann       ${i^{ann}}$             (long_name='annualized nominal interest rate')
+    r_nat_ann   ${r^{nat,ann}}$         (long_name='annualized natural interest rate')
+    pi_ann      ${\pi^{ann}}$           (long_name='annualized inflation rate')
+    z           ${z}$                   (long_name='AR(1) preference shock process')
+    p           ${p}$                   (long_name='price level')
+    w           ${w}$                   (long_name='nominal wage')
+    c           ${c}$                   (long_name='consumption')
+    w_real      ${\frac{w}{p}}$         (long_name='real wage')
+    mu          ${\mu}$                 (long_name='markup')
+    mu_hat      ${\hat \mu}$            (long_name='markup gap')
+;     
+
+varexo  eps_a       ${\varepsilon_a}$       (long_name='technology shock')
+        eps_z       ${\varepsilon_z}$   (long_name='preference shock innovation')
+       ;
+
+parameters alppha       ${\alpha}$     (long_name='capital share')
+    betta               ${\beta}$       (long_name='discount factor')
+    rho_a               ${\rho_a}$      (long_name='autocorrelation technology shock')
+    rho_z               ${\rho_{z}}$    (long_name='autocorrelation monetary demand shock')
+    siggma              ${\sigma}$      (long_name='inverse EIS')
+    varphi              ${\varphi}$     (long_name='inverse Frisch elasticity')
+    phi_pi              ${\phi_{\pi}}$  (long_name='inflation feedback Taylor Rule')
+    phi_y               ${\phi_{y}}$    (long_name='output feedback Taylor Rule')
+    eta                 ${\eta}$        (long_name='semi-elasticity of money demand')
+    epsilon             ${\epsilon}$    (long_name='demand elasticity')
+    theta               ${\theta}$      (long_name='Calvo parameter')
+    ;
+%----------------------------------------------------------------
+% Parametrization, p. 67  and p. 113-115
+%----------------------------------------------------------------
+siggma = 1;
+varphi=5;
+phi_pi = 1.5;
+phi_y  = 0.125;
+theta=3/4;
+rho_z  = 0.5;
+rho_a  = 0.9;
+betta  = 0.99;
+eta  =3.77; %footnote 11, p. 115
+alppha=1/4;
+epsilon=9;
+
+%----------------------------------------------------------------
+% First Order Conditions
+%----------------------------------------------------------------
+
+model(linear); 
+//Composite parameters
+#Omega=(1-alppha)/(1-alppha+alppha*epsilon);        %defined on page 60
+#psi_n_ya=(1+varphi)/(siggma*(1-alppha)+varphi+alppha);   %defined on page 62
+#lambda=(1-theta)*(1-betta*theta)/theta*Omega;      %defined on page 61
+#kappa=lambda*(siggma+(varphi+alppha)/(1-alppha));     %defined on page 63
+[name='New Keynesian Phillips Curve eq. (22)']
+pi=betta*pi(+1)+kappa*y_gap;
+[name='Dynamic IS Curve eq. (23)']
+y_gap=-1/siggma*(i-pi(+1)-r_nat)+y_gap(+1);
+[name='Definition natural rate of interest eq. (24)']
+r_nat=-siggma*psi_n_ya*(1-rho_a)*a+(1-rho_z)*z;
+[name='Definition real interest rate']
+r_real=i-pi(+1);
+[name='Definition natural output, eq. (20)']
+y_nat=psi_n_ya*a;
+[name='Definition output gap']
+y_gap=y-y_nat;
+[name='TFP shock']
+a=rho_a*a(-1)+eps_a;
+[name='Production function (eq. 14)']
+y=a+(1-alppha)*n;
+[name='Preference shock, p. 54']
+z     = rho_z*z(-1) - eps_z;
+[name='Money growth (derived from eq. (4))']
+m_growth_ann=4*(y-y(-1)-eta*(i-i(-1))+pi);
+[name='Real money demand (eq. 4)']
+m_real=y-eta*i;
+[name='Annualized nominal interest rate']
+i_ann=4*i;
+[name='Annualized real interest rate']
+r_real_ann=4*r_real;
+[name='Annualized natural interest rate']
+r_nat_ann=4*r_nat;
+[name='Annualized inflation']
+pi_ann=4*pi;
+[name='Output deviation from steady state']
+yhat=y-steady_state(y);
+[name='Definition price level']
+pi=p-p(-1);
+[name='resource constraint, eq. (12)']
+y=c;
+[name='FOC labor, eq. (2)']
+w-p=siggma*c+varphi*n;
+[name='definition real wage']
+w_real=w-p;
+[name='definition nominal money stock']
+m_nominal=m_real+p;
+[name='average price markup, eq. (18)']
+mu=-(siggma+(varphi+alppha)/(1-alppha))*y+(1+varphi)/(1-alppha)*a;
+[name='average price markup, eq. (20)']
+mu_hat=-(siggma+(varphi+alppha)/(1-alppha))*y_gap;
+end;
+
+
+%----------------------------------------------------------------
+%  define shock variances
+%---------------------------------------------------------------
+shocks;
+var eps_a  = 0.5^2; //unit shock to preferences 
+end;
+
+planner_objective 0.5*((siggma+(varphi+alppha)/(1-alppha))*yhat^2+epsilon/0.0215*pi^2)/100;
+discretionary_policy(instruments=(i),irf=20,planner_discount=betta, periods=0) y_gap pi_ann y n w_real p yhat;
+
+
diff --git a/tests/discretionary_policy/Gali_2015_chapter_3_nonlinear.mod b/tests/discretionary_policy/Gali_2015_chapter_3_nonlinear.mod
new file mode 100644
index 0000000000000000000000000000000000000000..d9153977c64fb557fbf779a77786487c0525bb45
--- /dev/null
+++ b/tests/discretionary_policy/Gali_2015_chapter_3_nonlinear.mod
@@ -0,0 +1,229 @@
+/*
+ * This file implements the baseline New Keynesian model of Jordi Gal� (2015): Monetary Policy, Inflation,
+ * and the Business Cycle, Princeton University Press, Second Edition, Chapter 3
+ *
+ * Note that this mod-file implements the non-linear first order conditions and that the IRFs show the log-deviations
+ * from steady state.
+ *
+ * THIS MOD-FILE REQUIRES DYNARE 4.5 OR HIGHER
+ *
+ * Notes:
+ *  - in the LOM for the discount rate shock z the shock enters with a minus sign in this mod-file to generate the 
+ *      IRF to a -0.5% shock
+ *
+ * This implementation was written by Johannes Pfeifer. In case you spot mistakes,
+ * email me at jpfeifer@gmx.de
+ *
+ * Please note that the following copyright notice only applies to this Dynare 
+ * implementation of the model. 
+ */
+
+/*
+ * Copyright (C) 2016-20 Johannes Pfeifer
+ * Copyright (C) 2020 Dynare Team
+ *
+ * This 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.
+ *
+ * It 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.
+ *
+ * For a copy of the GNU General Public License,
+ * see <http://www.gnu.org/licenses/>.
+ */
+
+var C               ${C}$           (long_name='Consumption')
+    W_real          ${\frac{W}{P}}$ (long_name='Real Wage')
+    Pi              ${\Pi}$         (long_name='inflation')
+    A               ${A}$           (long_name='AR(1) technology process')
+    N               ${N}$           (long_name='Hours worked')
+    R               ${R^n}$         (long_name='Nominal Interest Rate') 
+    realinterest    ${R^{r}}$       (long_name='Real Interest Rate')
+    Y               ${Y}$           (long_name='Output') 
+    Q               ${Q}$           (long_name='Bond price')
+    Z               ${Z}$           (long_name='AR(1) preference shock process')
+    S               ${S}$           (long_name='Price dispersion')
+    Pi_star         ${\Pi^*}$       (long_name='Optimal reset price')
+    x_aux_1         ${x_1}$         (long_name='aux. var. 1 recursive price setting')
+    x_aux_2         ${x_2}$         (long_name='aux. var. 2 recursive price setting')
+    MC              ${mc}$          (long_name='real marginal costs')
+    M_real          ${M/P}$         (long_name='real money stock')
+    i_ann           ${i^{ann}}$     (long_name='annualized nominal interest rate')
+    pi_ann          ${\pi^{ann}}$   (long_name='annualized inflation rate')
+    r_real_ann      ${r^{r,ann}}$   (long_name='annualized real interest rate')
+    P               ${P}$           (long_name='price level')
+    log_m_nominal   ${log(M)}$      (long_name='log nominal money stock')
+    log_y           ${log(Y)}$      (long_name='log output')
+    log_W_real      ${log(W/P)}$    (long_name='log real wage')
+    log_N           ${log(N)}$      (long_name='log hours')
+    log_P           ${log(P)}$      (long_name='log price level')
+    log_A           ${log(A)}$      (long_name='log technology level')
+    log_Z           ${log(Z)}$      (long_name='log preference shock')
+    y_hat
+    pi
+    ;
+
+varexo eps_a        ${\varepsilon_a}$   (long_name='technology shock')
+       eps_z        ${\varepsilon_z}$   (long_name='preference shock')
+       ;   
+
+parameters alppha       ${\alpha}$      (long_name='capital share')
+    betta               ${\beta}$       (long_name='discount factor')
+    rho_a               ${\rho_a}$      (long_name='autocorrelation technology shock')
+    rho_z               ${\rho_{z}}$    (long_name='autocorrelation monetary demand shock')
+    siggma              ${\sigma}$      (long_name='inverse EIS')
+    varphi              ${\varphi}$     (long_name='inverse Frisch elasticity')
+    phi_pi              ${\phi_{\pi}}$  (long_name='inflation feedback Taylor Rule')
+    phi_y               ${\phi_{y}}$    (long_name='output feedback Taylor Rule')
+    eta                 ${\eta}$        (long_name='semi-elasticity of money demand')
+    epsilon             ${\epsilon}$    (long_name='demand elasticity')
+    theta               ${\theta}$      (long_name='Calvo parameter')
+    tau                 ${\tau}$      (long_name='labor subsidy')
+    ;
+    
+%----------------------------------------------------------------
+% Parametrization, p. 67  and p. 113-115
+%----------------------------------------------------------------
+siggma = 1;
+varphi=5;
+phi_pi = 1.5;
+phi_y  = 0.125;
+theta=3/4;
+rho_z  = 0.5;
+rho_a  = 0.9;
+betta  = 0.99;
+eta  =3.77; %footnote 11, p. 115
+alppha=1/4;
+epsilon=9;
+tau=0; //1/epsilon;
+
+%----------------------------------------------------------------
+% First Order Conditions
+%----------------------------------------------------------------
+
+model;
+    [name='FOC Wages, eq. (2)']
+    W_real=C^siggma*N^varphi;
+    [name='Euler equation eq. (3)']
+    Q=betta*(C(+1)/C)^(-siggma)*(Z(+1)/Z)/Pi(+1);
+    [name='Definition nominal interest rate), p. 22 top']
+    R=1/Q;
+    [name='Aggregate output, above eq. (14)']
+    Y=A*(N/S)^(1-alppha);
+    [name='Definition Real interest rate']
+    R=realinterest*Pi(+1);
+%     @#if money_growth_rule==0
+%         [name='Monetary Policy Rule, p. 26 bottom/eq. (22)']
+%         R=1/betta*Pi^phi_pi*(Y/steady_state(Y))^phi_y;
+%     @#endif
+    [name='Market Clearing, eq. (15)']
+    C=Y;
+    [name='Technology Shock, eq. (6)']
+    log(A)=rho_a*log(A(-1))+eps_a;
+    [name='Preference Shock, p.54']
+    log(Z)=rho_z*log(Z(-1))-eps_z;
+    [name='Definition marginal cost']
+    MC=W_real/((1-alppha)*Y/N*S);
+    [name='LOM prices, eq. (7)']
+    1=theta*Pi^(epsilon-1)+(1-theta)*(Pi_star)^(1-epsilon);
+    [name='LOM price dispersion']
+    S=(1-theta)*Pi_star^(-epsilon/(1-alppha))+theta*Pi^(epsilon/(1-alppha))*S(-1);
+    [name='FOC price setting']
+    Pi_star^(1+epsilon*(alppha/(1-alppha)))=x_aux_1/x_aux_2*(1-tau)*epsilon/(epsilon-1);
+    [name='Auxiliary price setting recursion 1']
+    x_aux_1=Z*C^(-siggma)*Y*MC+betta*theta*Pi(+1)^(epsilon+alppha*epsilon/(1-alppha))*x_aux_1(+1);
+    [name='Auxiliary price setting recursion 2']
+    x_aux_2=Z*C^(-siggma)*Y+betta*theta*Pi(+1)^(epsilon-1)*x_aux_2(+1);
+    [name='Definition log output']
+    log_y = log(Y);
+    [name='Definition log real wage']
+    log_W_real=log(W_real);
+    [name='Definition log hours']
+    log_N=log(N);
+    [name='Annualized inflation']
+    pi_ann=4*log(Pi);
+    [name='Annualized nominal interest rate']
+    i_ann=4*log(R);
+    [name='Annualized real interest rate']
+    r_real_ann=4*log(realinterest);
+    [name='Real money demand, eq. (4)']
+    M_real=Y/R^eta;
+    [name='definition nominal money stock']
+    log_m_nominal=log(M_real*P);
+    [name='Definition price level']
+    Pi=P/P(-1);
+    [name='Definition log price level']
+    log_P=log(P);
+    [name='Definition log TFP']
+    log_A=log(A);
+    [name='Definition log preference']
+    log_Z=log(Z);
+    [mcp='a']
+    y_hat=log(Y)-STEADY_STATE(log(Y));
+    
+    pi=log(Pi)-STEADY_STATE(log(Pi));
+end;
+
+%----------------------------------------------------------------
+%  Steady state values
+%---------------------------------------------------------------
+
+steady_state_model;
+A=1;
+Z=1;
+S=1;
+Pi_star=1;
+P=1;
+MC=(epsilon-1)/epsilon/(1-tau);
+R=1/betta;
+Pi=1;
+Q=1/R;
+realinterest=R;
+N=((1-alppha)*MC)^(1/((1-siggma)*alppha+varphi+siggma));
+C=A*N^(1-alppha);
+W_real=C^siggma*N^varphi;
+Y=C;
+money_growth=0;
+money_growth_ann=0;
+nu=0;
+x_aux_1=C^(-siggma)*Y*MC/(1-betta*theta*Pi^(epsilon/(1-alppha)));
+x_aux_2=C^(-siggma)*Y/(1-betta*theta*Pi^(epsilon-1));
+log_y = log(Y);
+log_W_real=log(W_real);
+log_N=log(N);
+pi_ann=4*log(Pi);
+i_ann=4*log(R);
+r_real_ann=4*log(realinterest);
+M_real=Y/R^eta;
+log_m_nominal=log(M_real*P);
+log_P=log(P);
+log_A=0;
+log_Z=0;
+end;
+
+%----------------------------------------------------------------
+%  define shock variances
+%---------------------------------------------------------------
+
+shocks;
+var eps_a  = 0.5^2; //unit shock to preferences 
+end;
+
+% steady;
+% check;
+% stoch_simul;
+planner_objective 0.5*((siggma+(varphi+alppha)/(1-alppha))*y_hat^2+epsilon/0.0215*pi^2)/100;
+discretionary_policy(order=1,instruments=(R),irf=20,planner_discount=betta, periods=0) y_hat pi_ann log_y log_N log_W_real log_P;
+
+temp=load('Gali_2015_chapter_3_results.mat');
+if abs(oo_.planner_objective_value-temp.oo_.planner_objective_value)>1e-6
+    warning('Planner objective does not match linear model')
+end
+if max(max(abs([temp.oo_.irfs.y_eps_a; temp.oo_.irfs.w_real_eps_a; temp.oo_.irfs.n_eps_a; temp.oo_.irfs.pi_ann_eps_a]-...
+        [oo_.irfs.log_y_eps_a; oo_.irfs.log_W_real_eps_a; oo_.irfs.log_N_eps_a; oo_.irfs.pi_ann_eps_a])))>1e-6
+    error('Policy is different')
+end
\ No newline at end of file
diff --git a/tests/ep/rbc_bytecode.mod b/tests/ep/rbc_bytecode.mod
new file mode 100644
index 0000000000000000000000000000000000000000..a45607db87af00a249958b035ee11b7a8ff480cd
--- /dev/null
+++ b/tests/ep/rbc_bytecode.mod
@@ -0,0 +1,77 @@
+// Test extended_path + bytecode (regression check for #1742)
+
+var Capital, Output, Labour, Consumption, Efficiency, efficiency, ExpectedTerm;
+
+varexo EfficiencyInnovation;
+
+parameters beta, theta, tau, alpha, psi, delta, rho, effstar, sigma;
+
+/*
+** Calibration
+*/
+
+
+beta    =  0.990;
+theta   =  0.357;
+tau     =  30.000;
+alpha   =  0.450;
+psi     =  -5.000;
+delta   =  0.020;
+rho     =  0.950;
+effstar =  1.000;
+sigma   =  0.010;
+
+model(bytecode);
+
+  // Eq. n°1:
+  efficiency = rho*efficiency(-1) + sigma*EfficiencyInnovation;
+
+  // Eq. n°2:
+  Efficiency = effstar*exp(efficiency-.5*sigma*sigma/(1-rho*rho));
+
+  // Eq. n°3:
+  Output = Efficiency*(alpha*(Capital(-1)^psi)+(1-alpha)*(Labour^psi))^(1/psi);
+
+  // Eq. n°4:
+  Consumption + Capital - Output - (1-delta)*Capital(-1);
+
+  // Eq. n°5:
+  ((1-theta)/theta)*(Consumption/(1-Labour)) - (1-alpha)*(Output/Labour)^(1-psi);
+
+  // Eq. n°6:
+  (((Consumption^theta)*((1-Labour)^(1-theta)))^(1-tau))/Consumption - ExpectedTerm(1);
+
+  // Eq. n°7:
+  ExpectedTerm = beta*((((Consumption^theta)*((1-Labour)^(1-theta)))^(1-tau))/Consumption)*(alpha*((Output/Capital(-1))^(1-psi))+1-delta);
+
+end;
+
+steady_state_model;
+efficiency = 0;
+Efficiency = effstar;
+// Compute steady state ratios.
+Output_per_unit_of_Capital=((1/beta-1+delta)/alpha)^(1/(1-psi));
+Consumption_per_unit_of_Capital=Output_per_unit_of_Capital-delta;
+Labour_per_unit_of_Capital=(((Output_per_unit_of_Capital/Efficiency)^psi-alpha)/(1-alpha))^(1/psi);
+Output_per_unit_of_Labour=Output_per_unit_of_Capital/Labour_per_unit_of_Capital;
+Consumption_per_unit_of_Labour=Consumption_per_unit_of_Capital/Labour_per_unit_of_Capital;
+
+// Compute steady state share of capital.
+ShareOfCapital=alpha/(alpha+(1-alpha)*Labour_per_unit_of_Capital^psi);
+
+/// Compute steady state of the endogenous variables.
+Labour=1/(1+Consumption_per_unit_of_Labour/((1-alpha)*theta/(1-theta)*Output_per_unit_of_Labour^(1-psi)));
+Consumption = Consumption_per_unit_of_Labour*Labour;
+Capital = Labour/Labour_per_unit_of_Capital;
+Output = Output_per_unit_of_Capital*Capital;
+ExpectedTerm = beta*((((Consumption^theta)*((1-Labour)^(1-theta)))^(1-tau))/Consumption)*(alpha*((Output/Capital)^(1-psi))+1-delta);
+end;
+
+
+shocks;
+var EfficiencyInnovation = 1;
+end;
+
+steady(nocheck);
+
+extended_path(periods=10, order=0);
diff --git a/tests/estimation/method_of_moments/AFVRR/AFVRR_M0.mod b/tests/estimation/method_of_moments/AFVRR/AFVRR_M0.mod
new file mode 100644
index 0000000000000000000000000000000000000000..8e51ac51368237c54d02210941407fdfd3a8db08
--- /dev/null
+++ b/tests/estimation/method_of_moments/AFVRR/AFVRR_M0.mod
@@ -0,0 +1,299 @@
+% DSGE model based on replication files of
+% Andreasen, Fernandez-Villaverde, Rubio-Ramirez (2018), The Pruned State-Space System for Non-Linear DSGE Models: Theory and Empirical Applications, Review of Economic Studies, 85, p. 1-49
+% Adapted for Dynare by Willi Mutschler (@wmutschl, willi@mutschler.eu), Jan 2021
+% =========================================================================
+% Copyright (C) 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 <http://www.gnu.org/licenses/>.
+% =========================================================================
+
+% This is the benchmark model with no feedback M_0
+% Original code RunGMM_standardModel_RRA.m by Martin M. Andreasen, Jan 2016
+
+@#include "AFVRR_common.inc"
+
+%--------------------------------------------------------------------------
+% Parameter calibration taken from RunGMM_standardModel_RRA.m
+%--------------------------------------------------------------------------
+% fixed parameters
+INHABIT   = 1;
+PHI1      = 4;
+PHI4      = 1;
+KAPAone   = 0;
+DELTA     = 0.025;
+THETA     = 0.36;
+ETA       = 6;
+CHI       = 0;
+CONSxhr40 = 0;
+BETTAxhr  = 0;
+BETTAxhr40= 0;
+RHOD      = 0;
+GAMA      = 0.9999;
+CONSxhr20 = 0;
+
+% estimated parameters
+BETTA    = 0.999544966118000;
+B        = 0.668859504661000;
+H        = 0.342483445196000;
+PHI2     = 0.997924964981000;
+RRA      = 662.7953149595370;
+KAPAtwo  = 5.516226495551000;
+ALFA     = 0.809462321180000;
+RHOR     = 0.643873352513000;
+BETTAPAI = 1.270087844103000;
+BETTAY   = 0.031812764291000;
+MYYPS    = 1.001189151180000;
+MYZ      = 1.005286347928000;
+RHOA     = 0.743239127127000;
+RHOG     = 0.793929380230000;
+PAI      = 1.012163659169000;
+GoY      = 0.206594858866000;
+STDA     = 0.016586292524000;
+STDG     = 0.041220613851000;
+STDD     = 0.013534473123000;
+
+% endogenous parameters set via steady state, no need to initialize
+%PHIzero  = ;
+%AA       = ;
+%PHI3     = ;
+%negVf    = ;
+
+model_diagnostics;
+% Model diagnostics show that some parameters are endogenously determined
+% via the steady state, so we run steady to calibrate all parameters
+steady;
+model_diagnostics;
+% Now all parameters are determined
+
+resid;
+check;
+
+%--------------------------------------------------------------------------
+% Shock distribution
+%--------------------------------------------------------------------------
+shocks;
+var eps_a = STDA^2;
+var eps_d = STDD^2;
+var eps_g = STDG^2;
+end;
+
+%--------------------------------------------------------------------------
+% Estimated Params block - these parameters will be estimated, we
+% initialize at calibrated values
+%--------------------------------------------------------------------------
+estimated_params;
+BETTA;
+B;
+H;
+PHI2;
+RRA;
+KAPAtwo;
+ALFA;
+RHOR;
+BETTAPAI;
+BETTAY;
+MYYPS;
+MYZ;
+RHOA;
+RHOG;
+PAI;
+GoY;
+stderr eps_a;
+stderr eps_g;
+stderr eps_d;
+end;
+
+estimated_params_init(use_calibration);
+end;
+
+%--------------------------------------------------------------------------
+% Compare whether toolbox yields equivalent moments at second order
+%--------------------------------------------------------------------------
+% Note that we compare results for orderApp=1|2 and not for orderApp=3, because
+% there is a small error in the replication files of the original article in the 
+% computation of the covariance matrix of the extended innovations vector.
+% The authors have been contacted, fixed it, and report that the results 
+% change only slightly at orderApp=3 to what they report in the paper. At
+% orderApp=2 all is correct and so the following part tests whether we get 
+% the same model moments at the calibrated parameters (we do not optimize).
+% We compare it to the replication file RunGMM_standardModel_RRA.m with the
+% following settings: orderApp=1|2, seOn=0, q_lag=10, weighting=1;
+% scaled=0; optimizer=0; estimator=1; momentSet=2;
+%
+% Output of the replication files for orderApp=1
+AndreasenEtAl.Q1 = 23893.072;
+AndreasenEtAl.moments1 =[ % note that we reshuffeled to be compatible with our matched moments block
+    {[ 1]}    {'Ex'  }    {'Gr_C   '}    {'     '  }    {'0.024388'   }    {'0.023764'   }
+    {[ 2]}    {'Ex'  }    {'Gr_I   '}    {'     '  }    {'0.031046'   }    {'0.028517'   }
+    {[ 3]}    {'Ex'  }    {'Infl  ' }    {'     '  }    {'0.03757'    }    {'0.048361'   }
+    {[ 4]}    {'Ex'  }    {'r1    ' }    {'     '  }    {'0.056048'   }    {'0.073945'   }
+    {[ 5]}    {'Ex'  }    {'r40   ' }    {'     '  }    {'0.069929'   }    {'0.073945'   }
+    {[ 6]}    {'Ex'  }    {'xhr40  '}    {'     '  }    {'0.017237'   }    {'0'          }
+    {[ 7]}    {'Ex'  }    {'GoY    '}    {'     '  }    {'-1.5745'    }    {'-1.577'     }
+    {[ 8]}    {'Ex'  }    {'hours  '}    {'     '  }    {'-0.043353'  }    {'-0.042861'  }
+    {[ 9]}    {'Exx' }    {'Gr_C   '}    {'Gr_C   '}    {'0.0013159'  }    {'0.0011816'  }
+    {[17]}    {'Exx' }    {'Gr_C   '}    {'Gr_I   '}    {'0.0021789'  }    {'0.0016052'  }
+    {[18]}    {'Exx' }    {'Gr_C   '}    {'Infl  ' }    {'0.00067495' }    {'0.00090947' }
+    {[19]}    {'Exx' }    {'Gr_C   '}    {'r1    ' }    {'0.0011655'  }    {'0.0016016'  }
+    {[20]}    {'Exx' }    {'Gr_C   '}    {'r40   ' }    {'0.0015906'  }    {'0.0017076'  }
+    {[21]}    {'Exx' }    {'Gr_C   '}    {'xhr40  '}    {'0.0020911'  }    {'0.0013997'  }
+    {[10]}    {'Exx' }    {'Gr_I   '}    {'Gr_I   '}    {'0.0089104'  }    {'0.0055317'  }
+    {[22]}    {'Exx' }    {'Gr_I   '}    {'Infl  ' }    {'0.00063139' }    {'0.00050106' }
+    {[23]}    {'Exx' }    {'Gr_I   '}    {'r1    ' }    {'0.0011031'  }    {'0.0018178'  }
+    {[24]}    {'Exx' }    {'Gr_I   '}    {'r40   ' }    {'0.0018445'  }    {'0.0020186'  }
+    {[25]}    {'Exx' }    {'Gr_I   '}    {'xhr40  '}    {'0.00095556' }    {'0.0064471'  }
+    {[11]}    {'Exx' }    {'Infl  ' }    {'Infl  ' }    {'0.0020268'  }    {'0.0030519'  }
+    {[26]}    {'Exx' }    {'Infl  ' }    {'r1    ' }    {'0.0025263'  }    {'0.0042181'  }
+    {[27]}    {'Exx' }    {'Infl  ' }    {'r40   ' }    {'0.0029126'  }    {'0.0039217'  }
+    {[28]}    {'Exx' }    {'Infl  ' }    {'xhr40  '}    {'-0.00077101'}    {'-0.0019975' }
+    {[12]}    {'Exx' }    {'r1    ' }    {'r1    ' }    {'0.0038708'  }    {'0.0061403'  }
+    {[29]}    {'Exx' }    {'r1    ' }    {'r40   ' }    {'0.0044773'  }    {'0.0058343'  }
+    {[30]}    {'Exx' }    {'r1    ' }    {'xhr40  '}    {'-0.00048202'}    {'-0.00089501'}
+    {[13]}    {'Exx' }    {'r40   ' }    {'r40   ' }    {'0.0054664'  }    {'0.0056883'  }
+    {[31]}    {'Exx' }    {'r40   ' }    {'xhr40  '}    {'0.00053864' }    {'-0.00041184'}
+    {[14]}    {'Exx' }    {'xhr40  '}    {'xhr40  '}    {'0.053097'   }    {'0.016255'   }
+    {[15]}    {'Exx' }    {'GoY    '}    {'GoY    '}    {'2.4863'     }    {'2.4919'     }
+    {[16]}    {'Exx' }    {'hours  '}    {'hours  '}    {'0.0018799'  }    {'0.0018384'  }
+    {[32]}    {'Exx1'}    {'Gr_C   '}    {'Gr_C   '}    {'0.00077917' }    {'0.00065543' }
+    {[33]}    {'Exx1'}    {'Gr_I   '}    {'Gr_I   '}    {'0.0050104'  }    {'0.0033626'  }
+    {[34]}    {'Exx1'}    {'Infl  ' }    {'Infl  ' }    {'0.0019503'  }    {'0.0029033'  }
+    {[35]}    {'Exx1'}    {'r1    ' }    {'r1    ' }    {'0.0038509'  }    {'0.006112'   }
+    {[36]}    {'Exx1'}    {'r40   ' }    {'r40   ' }    {'0.0054699'  }    {'0.005683'   }
+    {[37]}    {'Exx1'}    {'xhr40  '}    {'xhr40  '}    {'-0.00098295'}    {'3.3307e-16' }
+    {[38]}    {'Exx1'}    {'GoY    '}    {'GoY    '}    {'2.4868'     }    {'2.4912'     }
+    {[39]}    {'Exx1'}    {'hours  '}    {'hours  '}    {'0.0018799'  }    {'0.0018378'  }
+];
+
+% Output of the replication files for orderApp=2
+AndreasenEtAl.Q2 = 65.8269;
+AndreasenEtAl.moments2 =[ % note that we reshuffeled to be compatible with our matched moments block
+    {[ 1]}    {'Ex'  }    {'Gr_C   '}    {'     '  }    {'0.024388'   }    {'0.023764'  }
+    {[ 2]}    {'Ex'  }    {'Gr_I   '}    {'     '  }    {'0.031046'   }    {'0.028517'  }
+    {[ 3]}    {'Ex'  }    {'Infl  ' }    {'     '  }    {'0.03757'    }    {'0.034882'  }
+    {[ 4]}    {'Ex'  }    {'r1    ' }    {'     '  }    {'0.056048'   }    {'0.056542'  }
+    {[ 5]}    {'Ex'  }    {'r40   ' }    {'     '  }    {'0.069929'   }    {'0.070145'  }
+    {[ 6]}    {'Ex'  }    {'xhr40  '}    {'     '  }    {'0.017237'   }    {'0.020825'  }
+    {[ 7]}    {'Ex'  }    {'GoY    '}    {'     '  }    {'-1.5745'    }    {'-1.5748'   }
+    {[ 8]}    {'Ex'  }    {'hours  '}    {'     '  }    {'-0.043353'  }    {'-0.04335'  }
+    {[ 9]}    {'Exx' }    {'Gr_C   '}    {'Gr_C   '}    {'0.0013159'  }    {'0.001205'  }
+    {[17]}    {'Exx' }    {'Gr_C   '}    {'Gr_I   '}    {'0.0021789'  }    {'0.0016067' }
+    {[18]}    {'Exx' }    {'Gr_C   '}    {'Infl  ' }    {'0.00067495' }    {'0.00059406'}
+    {[19]}    {'Exx' }    {'Gr_C   '}    {'r1    ' }    {'0.0011655'  }    {'0.0011949' }
+    {[20]}    {'Exx' }    {'Gr_C   '}    {'r40   ' }    {'0.0015906'  }    {'0.0016104' }
+    {[21]}    {'Exx' }    {'Gr_C   '}    {'xhr40  '}    {'0.0020911'  }    {'0.0020245' }
+    {[10]}    {'Exx' }    {'Gr_I   '}    {'Gr_I   '}    {'0.0089104'  }    {'0.0060254' }
+    {[22]}    {'Exx' }    {'Gr_I   '}    {'Infl  ' }    {'0.00063139' }    {'8.3563e-05'}
+    {[23]}    {'Exx' }    {'Gr_I   '}    {'r1    ' }    {'0.0011031'  }    {'0.0013176' }
+    {[24]}    {'Exx' }    {'Gr_I   '}    {'r40   ' }    {'0.0018445'  }    {'0.0019042' }
+    {[25]}    {'Exx' }    {'Gr_I   '}    {'xhr40  '}    {'0.00095556' }    {'0.0064261' }
+    {[11]}    {'Exx' }    {'Infl  ' }    {'Infl  ' }    {'0.0020268'  }    {'0.0020735' }
+    {[26]}    {'Exx' }    {'Infl  ' }    {'r1    ' }    {'0.0025263'  }    {'0.0027621' }
+    {[27]}    {'Exx' }    {'Infl  ' }    {'r40   ' }    {'0.0029126'  }    {'0.0029257' }
+    {[28]}    {'Exx' }    {'Infl  ' }    {'xhr40  '}    {'-0.00077101'}    {'-0.0012165'}
+    {[12]}    {'Exx' }    {'r1    ' }    {'r1    ' }    {'0.0038708'  }    {'0.0040235' }
+    {[29]}    {'Exx' }    {'r1    ' }    {'r40   ' }    {'0.0044773'  }    {'0.0044702' }
+    {[30]}    {'Exx' }    {'r1    ' }    {'xhr40  '}    {'-0.00048202'}    {'0.00030542'}
+    {[13]}    {'Exx' }    {'r40   ' }    {'r40   ' }    {'0.0054664'  }    {'0.0052718' }
+    {[31]}    {'Exx' }    {'r40   ' }    {'xhr40  '}    {'0.00053864' }    {'0.0010045' }
+    {[14]}    {'Exx' }    {'xhr40  '}    {'xhr40  '}    {'0.053097'   }    {'0.018416'  }
+    {[15]}    {'Exx' }    {'GoY    '}    {'GoY    '}    {'2.4863'     }    {'2.4853'    }
+    {[16]}    {'Exx' }    {'hours  '}    {'hours  '}    {'0.0018799'  }    {'0.0018806' }
+    {[32]}    {'Exx1'}    {'Gr_C   '}    {'Gr_C   '}    {'0.00077917' }    {'0.00067309'}
+    {[33]}    {'Exx1'}    {'Gr_I   '}    {'Gr_I   '}    {'0.0050104'  }    {'0.0033293' }
+    {[34]}    {'Exx1'}    {'Infl  ' }    {'Infl  ' }    {'0.0019503'  }    {'0.0019223' }
+    {[35]}    {'Exx1'}    {'r1    ' }    {'r1    ' }    {'0.0038509'  }    {'0.0039949' }
+    {[36]}    {'Exx1'}    {'r40   ' }    {'r40   ' }    {'0.0054699'  }    {'0.0052659' }
+    {[37]}    {'Exx1'}    {'xhr40  '}    {'xhr40  '}    {'-0.00098295'}    {'0.0004337' }
+    {[38]}    {'Exx1'}    {'GoY    '}    {'GoY    '}    {'2.4868'     }    {'2.4846'    }
+    {[39]}    {'Exx1'}    {'hours  '}    {'hours  '}    {'0.0018799'  }    {'0.00188'   }
+];
+
+@#for orderApp in 1:2
+
+method_of_moments(
+          mom_method = GMM                    % method of moments method; possible values: GMM|SMM
+        , datafile   = 'AFVRR_data.mat'       % name of filename with data
+        , bartlett_kernel_lag = 10          % bandwith in optimal weighting matrix
+        , order = @{orderApp}                 % order of Taylor approximation in perturbation
+        , pruning                             % use pruned state space system at higher-order
+        % , verbose                           % display and store intermediate estimation results
+        , weighting_matrix = ['DIAGONAL']      % weighting matrix in moments distance objective function; possible values: OPTIMAL|IDENTITY_MATRIX|DIAGONAL|filename        
+        % , TeX                               % print TeX tables and graphics
+        % Optimization options that can be set by the user in the mod file, otherwise default values are provided        
+        %, huge_number=1D10                   % value for replacing the infinite bounds on parameters by finite numbers. Used by some optimizers for numerical reasons
+        , mode_compute = 0                    % specifies the optimizer for minimization of moments distance, note that by default there is a new optimizer        
+        , optim = ('TolFun', 1e-6
+                   ,'TolX', 1e-6
+                   ,'MaxIter', 3000
+                   ,'MaxFunEvals', 1D6
+                   ,'UseParallel' , 1
+                   %,'Jacobian' , 'on'
+                  )    % a list of NAME and VALUE pairs to set options for the optimization routines. Available options depend on mode_compute
+        %, silent_optimizer                  % run minimization of moments distance silently without displaying results or saving files in between
+        %, analytic_standard_errors
+        , se_tolx=1e-10
+);
+
+% Check results
+
+fprintf('****************************************************************\n')
+fprintf('Compare Results for perturbation order @{orderApp}\n')
+fprintf('****************************************************************\n')
+dev_Q            = AndreasenEtAl.Q@{orderApp} - oo_.mom.Q;
+dev_datamoments  = str2double(AndreasenEtAl.moments@{orderApp}(:,5)) - oo_.mom.data_moments;
+dev_modelmoments = str2double(AndreasenEtAl.moments@{orderApp}(:,6)) - oo_.mom.model_moments;
+
+table([AndreasenEtAl.Q@{orderApp} ; str2double(AndreasenEtAl.moments@{orderApp}(:,5)) ; str2double(AndreasenEtAl.moments@{orderApp}(:,6))],...
+      [oo_.mom.Q                  ; oo_.mom.data_moments                              ; oo_.mom.model_moments                            ],...
+      [dev_Q                      ; dev_datamoments                                   ; dev_modelmoments                                 ],...
+      'VariableNames', {'Andreasen et al', 'Dynare', 'dev'},...
+      'RowNames', ['Q'; strcat('Data_', M_.matched_moments(:,4)); strcat('Model_', M_.matched_moments(:,4))])
+
+if norm(dev_modelmoments)> 1e-4
+    error('Something wrong in the computation of moments at order @{orderApp}')
+end
+
+@#endfor
+
+%--------------------------------------------------------------------------
+% Replicate estimation at orderApp=3
+%--------------------------------------------------------------------------
+@#ifdef DoEstimation
+method_of_moments(
+          mom_method = GMM                    % method of moments method; possible values: GMM|SMM
+        , datafile   = 'AFVRR_data.mat'       % name of filename with data
+        , bartlett_kernel_lag = 10            % bandwith in optimal weighting matrix
+        , order = 3                           % order of Taylor approximation in perturbation
+        , pruning                             % use pruned state space system at higher-order
+        % , verbose                           % display and store intermediate estimation results
+        , weighting_matrix = ['DIAGONAL', 'OPTIMAL']      % weighting matrix in moments distance objective function; possible values: OPTIMAL|IDENTITY_MATRIX|DIAGONAL|filename        
+        % , TeX                               % print TeX tables and graphics
+        % Optimization options that can be set by the user in the mod file, otherwise default values are provided        
+        %, huge_number=1D10                   % value for replacing the infinite bounds on parameters by finite numbers. Used by some optimizers for numerical reasons
+        , mode_compute = 13                   % specifies the optimizer for minimization of moments distance, note that by default there is a new optimizer
+        , additional_optimizer_steps = [13]
+        , optim = ('TolFun', 1e-6
+                   ,'TolX', 1e-6
+                   ,'MaxIter', 3000
+                   ,'MaxFunEvals', 1D6
+                   ,'UseParallel' , 1
+                   %,'Jacobian' , 'on'
+                  )    % a list of NAME and VALUE pairs to set options for the optimization routines. Available options depend on mode_compute
+        %, silent_optimizer                  % run minimization of moments distance silently without displaying results or saving files in between
+        %, analytic_standard_errors
+        , se_tolx=1e-10
+);
+@#endif
\ No newline at end of file
diff --git a/tests/estimation/method_of_moments/AFVRR/AFVRR_MFB.mod b/tests/estimation/method_of_moments/AFVRR/AFVRR_MFB.mod
new file mode 100644
index 0000000000000000000000000000000000000000..450739ad3bd153855806d8bcbab513d554eb33b7
--- /dev/null
+++ b/tests/estimation/method_of_moments/AFVRR/AFVRR_MFB.mod
@@ -0,0 +1,300 @@
+% DSGE model based on replication files of
+% Andreasen, Fernandez-Villaverde, Rubio-Ramirez (2018), The Pruned State-Space System for Non-Linear DSGE Models: Theory and Empirical Applications, Review of Economic Studies, 85, p. 1-49
+% Adapted for Dynare by Willi Mutschler (@wmutschl, willi@mutschler.eu), Jan 2021
+% =========================================================================
+% Copyright (C) 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 <http://www.gnu.org/licenses/>.
+% =========================================================================
+
+% This is the model with Feedback M_FB
+% Original code RunGMM_Feedback_estim_RRA.m by Martin M. Andreasen, Jan 2016
+
+@#include "AFVRR_common.inc"
+
+%--------------------------------------------------------------------------
+% Parameter calibration taken from RunGMM_Feedback_estim_RRA.m
+%--------------------------------------------------------------------------
+% fixed parameters
+INHABIT   = 1;
+PHI1      = 4;
+PHI4      = 1;
+KAPAone   = 0;
+DELTA     = 0.025;
+THETA     = 0.36;
+ETA       = 6;
+CHI       = 0;
+BETTAxhr  = 0;
+BETTAxhr40= 0;
+RHOD      = 0;
+GAMA      = 0.9999;
+CONSxhr20 = 0;
+
+% estimated parameters
+BETTA     = 0.997007023687000;
+B         = 0.692501768577000;
+H         = 0.339214495653000;
+PHI2      = 0.688555040951000;
+RRA       = 24.346514272871001;
+KAPAtwo   = 10.018421876923000;
+ALFA      = 0.792507553312000;
+RHOR      = 0.849194030384000;
+BETTAPAI  = 2.060579322980000;
+BETTAY    = 0.220573712342000;
+MYYPS     = 1.001016690133000;
+MYZ       = 1.005356313981000;
+RHOA      = 0.784141391843000;
+RHOG      = 0.816924540497000;
+PAI       = 1.011924196487000;
+CONSxhr40 = 0.878774662208000;
+GoY       = 0.207110300602000;
+STDA      = 0.013024450606000;
+STDG      = 0.051049871928000;
+STDD      = 0.008877423780000;
+
+% endogenous parameters set via steady state, no need to initialize
+%PHIzero  = ;
+%AA       = ;
+%PHI3     = ;
+%negVf    = ;
+
+model_diagnostics;
+% Model diagnostics show that some parameters are endogenously determined
+% via the steady state, so we run steady to calibrate all parameters
+steady;
+model_diagnostics;
+% Now all parameters are determined
+
+resid;
+check;
+
+%--------------------------------------------------------------------------
+% Shock distribution
+%--------------------------------------------------------------------------
+shocks;
+var eps_a = STDA^2;
+var eps_d = STDD^2;
+var eps_g = STDG^2;
+end;
+
+%--------------------------------------------------------------------------
+% Estimated Params block - these parameters will be estimated, we
+% initialize at calibrated values
+%--------------------------------------------------------------------------
+estimated_params;
+BETTA;
+B;
+H;
+PHI2;
+RRA;
+KAPAtwo;
+ALFA;
+RHOR;
+BETTAPAI;
+BETTAY;
+MYYPS;
+MYZ;
+RHOA;
+RHOG;
+PAI;
+CONSxhr40;
+GoY;
+stderr eps_a;
+stderr eps_g;
+stderr eps_d;
+end;
+
+estimated_params_init(use_calibration);
+end;
+
+%--------------------------------------------------------------------------
+% Compare whether toolbox yields equivalent moments at second order
+%--------------------------------------------------------------------------
+% Note that we compare results for orderApp=1|2 and not for orderApp=3, because
+% there is a small error in the replication files of the original article in the 
+% computation of the covariance matrix of the extended innovations vector.
+% The authors have been contacted, fixed it, and report that the results 
+% change only slightly at orderApp=3 to what they report in the paper. At
+% orderApp=2 all is correct and so the following part tests whether we get 
+% the same model moments at the calibrated parameters (we do not optimize).
+% We compare it to the replication file RunGMM_Feedback_estim_RRA.m with the
+% following settings: orderApp=1|2, seOn=0, q_lag=10, weighting=1;
+% scaled=0; optimizer=0; estimator=1; momentSet=2;
+%
+% Output of the replication files for orderApp=1
+AndreasenEtAl.Q1 = 201778.9697;
+AndreasenEtAl.moments1 =[ % note that we reshuffeled to be compatible with our matched moments block
+    {[ 1]}    {'Ex'  }    {'Gr_C   '}    {'     '  }    {'0.024388'   }    {'0.023654'   }
+    {[ 2]}    {'Ex'  }    {'Gr_I   '}    {'     '  }    {'0.031046'   }    {'0.027719'   }
+    {[ 3]}    {'Ex'  }    {'Infl  ' }    {'     '  }    {'0.03757'    }    {'0.047415'   }
+    {[ 4]}    {'Ex'  }    {'r1    ' }    {'     '  }    {'0.056048'   }    {'0.083059'   }
+    {[ 5]}    {'Ex'  }    {'r40   ' }    {'     '  }    {'0.069929'   }    {'0.083059'   }
+    {[ 6]}    {'Ex'  }    {'xhr40  '}    {'     '  }    {'0.017237'   }    {'0'          }
+    {[ 7]}    {'Ex'  }    {'GoY    '}    {'     '  }    {'-1.5745'    }    {'-1.5745'    }
+    {[ 8]}    {'Ex'  }    {'hours  '}    {'     '  }    {'-0.043353'  }    {'-0.043245'  }
+    {[ 9]}    {'Exx' }    {'Gr_C   '}    {'Gr_C   '}    {'0.0013159'  }    {'0.0012253'  }
+    {[17]}    {'Exx' }    {'Gr_C   '}    {'Gr_I   '}    {'0.0021789'  }    {'0.0015117'  }
+    {[18]}    {'Exx' }    {'Gr_C   '}    {'Infl  ' }    {'0.00067495' }    {'0.00080078' }
+    {[19]}    {'Exx' }    {'Gr_C   '}    {'r1    ' }    {'0.0011655'  }    {'0.00182'    }
+    {[20]}    {'Exx' }    {'Gr_C   '}    {'r40   ' }    {'0.0015906'  }    {'0.001913'   }
+    {[21]}    {'Exx' }    {'Gr_C   '}    {'xhr40  '}    {'0.0020911'  }    {'0.0016326'  }
+    {[10]}    {'Exx' }    {'Gr_I   '}    {'Gr_I   '}    {'0.0089104'  }    {'0.0040112'  }
+    {[22]}    {'Exx' }    {'Gr_I   '}    {'Infl  ' }    {'0.00063139' }    {'0.00060604' }
+    {[23]}    {'Exx' }    {'Gr_I   '}    {'r1    ' }    {'0.0011031'  }    {'0.0021426'  }
+    {[24]}    {'Exx' }    {'Gr_I   '}    {'r40   ' }    {'0.0018445'  }    {'0.0022348'  }
+    {[25]}    {'Exx' }    {'Gr_I   '}    {'xhr40  '}    {'0.00095556' }    {'0.0039852'  }
+    {[11]}    {'Exx' }    {'Infl  ' }    {'Infl  ' }    {'0.0020268'  }    {'0.0030058'  }
+    {[26]}    {'Exx' }    {'Infl  ' }    {'r1    ' }    {'0.0025263'  }    {'0.0044951'  }
+    {[27]}    {'Exx' }    {'Infl  ' }    {'r40   ' }    {'0.0029126'  }    {'0.0042225'  }
+    {[28]}    {'Exx' }    {'Infl  ' }    {'xhr40  '}    {'-0.00077101'}    {'-0.0021222' }
+    {[12]}    {'Exx' }    {'r1    ' }    {'r1    ' }    {'0.0038708'  }    {'0.0074776'  }
+    {[29]}    {'Exx' }    {'r1    ' }    {'r40   ' }    {'0.0044773'  }    {'0.0071906'  }
+    {[30]}    {'Exx' }    {'r1    ' }    {'xhr40  '}    {'-0.00048202'}    {'-0.0006736' }
+    {[13]}    {'Exx' }    {'r40   ' }    {'r40   ' }    {'0.0054664'  }    {'0.0070599'  }
+    {[31]}    {'Exx' }    {'r40   ' }    {'xhr40  '}    {'0.00053864' }    {'-0.00036735'}
+    {[14]}    {'Exx' }    {'xhr40  '}    {'xhr40  '}    {'0.053097'   }    {'0.014516'   }
+    {[15]}    {'Exx' }    {'GoY    '}    {'GoY    '}    {'2.4863'     }    {'2.4866'     }
+    {[16]}    {'Exx' }    {'hours  '}    {'hours  '}    {'0.0018799'  }    {'0.0018713'  }
+    {[32]}    {'Exx1'}    {'Gr_C   '}    {'Gr_C   '}    {'0.00077917' }    {'0.00076856' }
+    {[33]}    {'Exx1'}    {'Gr_I   '}    {'Gr_I   '}    {'0.0050104'  }    {'0.002163'   }
+    {[34]}    {'Exx1'}    {'Infl  ' }    {'Infl  ' }    {'0.0019503'  }    {'0.0028078'  }
+    {[35]}    {'Exx1'}    {'r1    ' }    {'r1    ' }    {'0.0038509'  }    {'0.0074583'  }
+    {[36]}    {'Exx1'}    {'r40   ' }    {'r40   ' }    {'0.0054699'  }    {'0.0070551'  }
+    {[37]}    {'Exx1'}    {'xhr40  '}    {'xhr40  '}    {'-0.00098295'}    {'7.2164e-16' }
+    {[38]}    {'Exx1'}    {'GoY    '}    {'GoY    '}    {'2.4868'     }    {'2.4856'     }
+    {[39]}    {'Exx1'}    {'hours  '}    {'hours  '}    {'0.0018799'  }    {'0.0018708'  }
+];
+
+% Output of the replication files for orderApp=2
+AndreasenEtAl.Q2 = 59.3323;
+AndreasenEtAl.moments2 =[ % note that we reshuffeled to be compatible with our matched moments block
+    {[ 1]}    {'Ex'  }    {'Gr_C   '}    {'     '  }    {'0.024388'   }    {'0.023654'  }
+    {[ 2]}    {'Ex'  }    {'Gr_I   '}    {'     '  }    {'0.031046'   }    {'0.027719'  }
+    {[ 3]}    {'Ex'  }    {'Infl  ' }    {'     '  }    {'0.03757'    }    {'0.034565'  }
+    {[ 4]}    {'Ex'  }    {'r1    ' }    {'     '  }    {'0.056048'   }    {'0.056419'  }
+    {[ 5]}    {'Ex'  }    {'r40   ' }    {'     '  }    {'0.069929'   }    {'0.07087'   }
+    {[ 6]}    {'Ex'  }    {'xhr40  '}    {'     '  }    {'0.017237'   }    {'0.01517'   }
+    {[ 7]}    {'Ex'  }    {'GoY    '}    {'     '  }    {'-1.5745'    }    {'-1.5743'   }
+    {[ 8]}    {'Ex'  }    {'hours  '}    {'     '  }    {'-0.043353'  }    {'-0.043352' }
+    {[ 9]}    {'Exx' }    {'Gr_C   '}    {'Gr_C   '}    {'0.0013159'  }    {'0.0012464' }
+    {[17]}    {'Exx' }    {'Gr_C   '}    {'Gr_I   '}    {'0.0021789'  }    {'0.0015247' }
+    {[18]}    {'Exx' }    {'Gr_C   '}    {'Infl  ' }    {'0.00067495' }    {'0.0004867' }
+    {[19]}    {'Exx' }    {'Gr_C   '}    {'r1    ' }    {'0.0011655'  }    {'0.0011867' }
+    {[20]}    {'Exx' }    {'Gr_C   '}    {'r40   ' }    {'0.0015906'  }    {'0.0016146' }
+    {[21]}    {'Exx' }    {'Gr_C   '}    {'xhr40  '}    {'0.0020911'  }    {'0.0021395' }
+    {[10]}    {'Exx' }    {'Gr_I   '}    {'Gr_I   '}    {'0.0089104'  }    {'0.0043272' }
+    {[22]}    {'Exx' }    {'Gr_I   '}    {'Infl  ' }    {'0.00063139' }    {'0.00021752'}
+    {[23]}    {'Exx' }    {'Gr_I   '}    {'r1    ' }    {'0.0011031'  }    {'0.0013919' }
+    {[24]}    {'Exx' }    {'Gr_I   '}    {'r40   ' }    {'0.0018445'  }    {'0.0018899' }
+    {[25]}    {'Exx' }    {'Gr_I   '}    {'xhr40  '}    {'0.00095556' }    {'0.0037854' }
+    {[11]}    {'Exx' }    {'Infl  ' }    {'Infl  ' }    {'0.0020268'  }    {'0.0021043' }
+    {[26]}    {'Exx' }    {'Infl  ' }    {'r1    ' }    {'0.0025263'  }    {'0.0026571' }
+    {[27]}    {'Exx' }    {'Infl  ' }    {'r40   ' }    {'0.0029126'  }    {'0.0028566' }
+    {[28]}    {'Exx' }    {'Infl  ' }    {'xhr40  '}    {'-0.00077101'}    {'-0.0016279'}
+    {[12]}    {'Exx' }    {'r1    ' }    {'r1    ' }    {'0.0038708'  }    {'0.0039136' }
+    {[29]}    {'Exx' }    {'r1    ' }    {'r40   ' }    {'0.0044773'  }    {'0.0044118' }
+    {[30]}    {'Exx' }    {'r1    ' }    {'xhr40  '}    {'-0.00048202'}    {'0.00016791'}
+    {[13]}    {'Exx' }    {'r40   ' }    {'r40   ' }    {'0.0054664'  }    {'0.0052851' }
+    {[31]}    {'Exx' }    {'r40   ' }    {'xhr40  '}    {'0.00053864' }    {'0.00062143'}
+    {[14]}    {'Exx' }    {'xhr40  '}    {'xhr40  '}    {'0.053097'   }    {'0.018126'  }
+    {[15]}    {'Exx' }    {'GoY    '}    {'GoY    '}    {'2.4863'     }    {'2.4863'    }
+    {[16]}    {'Exx' }    {'hours  '}    {'hours  '}    {'0.0018799'  }    {'0.0018806' }
+    {[32]}    {'Exx1'}    {'Gr_C   '}    {'Gr_C   '}    {'0.00077917' }    {'0.00078586'}
+    {[33]}    {'Exx1'}    {'Gr_I   '}    {'Gr_I   '}    {'0.0050104'  }    {'0.0021519' }
+    {[34]}    {'Exx1'}    {'Infl  ' }    {'Infl  ' }    {'0.0019503'  }    {'0.0019046' }
+    {[35]}    {'Exx1'}    {'r1    ' }    {'r1    ' }    {'0.0038509'  }    {'0.0038939' }
+    {[36]}    {'Exx1'}    {'r40   ' }    {'r40   ' }    {'0.0054699'  }    {'0.0052792' }
+    {[37]}    {'Exx1'}    {'xhr40  '}    {'xhr40  '}    {'-0.00098295'}    {'0.00023012'}
+    {[38]}    {'Exx1'}    {'GoY    '}    {'GoY    '}    {'2.4868'     }    {'2.4852'    }
+    {[39]}    {'Exx1'}    {'hours  '}    {'hours  '}    {'0.0018799'  }    {'0.0018801' }
+];
+
+@#for orderApp in 1:2
+
+method_of_moments(
+          mom_method = GMM                    % method of moments method; possible values: GMM|SMM
+        , datafile   = 'AFVRR_data.mat'       % name of filename with data
+        , bartlett_kernel_lag = 10          % bandwith in optimal weighting matrix
+        , order = @{orderApp}                 % order of Taylor approximation in perturbation
+        , pruning                             % use pruned state space system at higher-order
+        % , verbose                           % display and store intermediate estimation results
+        , weighting_matrix = ['DIAGONAL']      % weighting matrix in moments distance objective function; possible values: OPTIMAL|IDENTITY_MATRIX|DIAGONAL|filename        
+        % , TeX                               % print TeX tables and graphics
+        % Optimization options that can be set by the user in the mod file, otherwise default values are provided        
+        %, huge_number=1D10                   % value for replacing the infinite bounds on parameters by finite numbers. Used by some optimizers for numerical reasons
+        , mode_compute = 0                    % specifies the optimizer for minimization of moments distance, note that by default there is a new optimizer        
+        , optim = ('TolFun', 1e-6
+                   ,'TolX', 1e-6
+                   ,'MaxIter', 3000
+                   ,'MaxFunEvals', 1D6
+                   ,'UseParallel' , 1
+                   %,'Jacobian' , 'on'
+                  )    % a list of NAME and VALUE pairs to set options for the optimization routines. Available options depend on mode_compute
+        %, silent_optimizer                  % run minimization of moments distance silently without displaying results or saving files in between
+        %, analytic_standard_errors
+        , se_tolx=1e-10
+);
+
+% Check results
+
+fprintf('****************************************************************\n')
+fprintf('Compare Results for perturbation order @{orderApp}\n')
+fprintf('****************************************************************\n')
+dev_Q            = AndreasenEtAl.Q@{orderApp} - oo_.mom.Q;
+dev_datamoments  = str2double(AndreasenEtAl.moments@{orderApp}(:,5)) - oo_.mom.data_moments;
+dev_modelmoments = str2double(AndreasenEtAl.moments@{orderApp}(:,6)) - oo_.mom.model_moments;
+
+table([AndreasenEtAl.Q@{orderApp} ; str2double(AndreasenEtAl.moments@{orderApp}(:,5)) ; str2double(AndreasenEtAl.moments@{orderApp}(:,6))],...
+      [oo_.mom.Q                  ; oo_.mom.data_moments                              ; oo_.mom.model_moments                            ],...
+      [dev_Q                      ; dev_datamoments                                   ; dev_modelmoments                                 ],...
+      'VariableNames', {'Andreasen et al', 'Dynare', 'dev'},...
+      'RowNames', ['Q'; strcat('Data_', M_.matched_moments(:,4)); strcat('Model_', M_.matched_moments(:,4))])
+
+if norm(dev_modelmoments)> 1e-4
+    warning('Something wrong in the computation of moments at order @{orderApp}')
+end
+
+@#endfor
+
+%--------------------------------------------------------------------------
+% Replicate estimation at orderApp=3
+%--------------------------------------------------------------------------
+@#ifdef DoEstimation
+method_of_moments(
+          mom_method = GMM                    % method of moments method; possible values: GMM|SMM
+        , datafile   = 'AFVRR_data.mat'       % name of filename with data
+        , bartlett_kernel_lag = 10            % bandwith in optimal weighting matrix
+        , order = 3                           % order of Taylor approximation in perturbation
+        , pruning                             % use pruned state space system at higher-order
+        % , verbose                           % display and store intermediate estimation results
+        , weighting_matrix = ['DIAGONAL', 'Optimal']      % weighting matrix in moments distance objective function; possible values: OPTIMAL|IDENTITY_MATRIX|DIAGONAL|filename        
+        % , TeX                               % print TeX tables and graphics
+        % Optimization options that can be set by the user in the mod file, otherwise default values are provided        
+        %, huge_number=1D10                   % value for replacing the infinite bounds on parameters by finite numbers. Used by some optimizers for numerical reasons
+        , mode_compute = 13                   % specifies the optimizer for minimization of moments distance, note that by default there is a new optimizer
+        , additional_optimizer_steps = [13]
+        , optim = ('TolFun', 1e-6
+                   ,'TolX', 1e-6
+                   ,'MaxIter', 3000
+                   ,'MaxFunEvals', 1D6
+                   ,'UseParallel' , 1
+                   %,'Jacobian' , 'on'
+                  )    % a list of NAME and VALUE pairs to set options for the optimization routines. Available options depend on mode_compute
+        %, silent_optimizer                  % run minimization of moments distance silently without displaying results or saving files in between
+        %, analytic_standard_errors
+        , se_tolx=1e-10
+);
+@#endif
\ No newline at end of file
diff --git a/tests/estimation/method_of_moments/AFVRR/AFVRR_MFB_RRA.mod b/tests/estimation/method_of_moments/AFVRR/AFVRR_MFB_RRA.mod
new file mode 100644
index 0000000000000000000000000000000000000000..9c069d3a3dff9dfb87ce7e40f2678f27ce1364aa
--- /dev/null
+++ b/tests/estimation/method_of_moments/AFVRR/AFVRR_MFB_RRA.mod
@@ -0,0 +1,299 @@
+% DSGE model based on replication files of
+% Andreasen, Fernandez-Villaverde, Rubio-Ramirez (2018), The Pruned State-Space System for Non-Linear DSGE Models: Theory and Empirical Applications, Review of Economic Studies, 85, p. 1-49
+% Adapted for Dynare by Willi Mutschler (@wmutschl, willi@mutschler.eu), Jan 2021
+% =========================================================================
+% Copyright (C) 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 <http://www.gnu.org/licenses/>.
+% =========================================================================
+
+% This is the model with feedback and calibrated RRA
+% Original code RunGMM_Feedback_estim_RRA_5.m by Martin M. Andreasen, Jan 2016
+
+@#include "AFVRR_common.inc"
+
+%--------------------------------------------------------------------------
+% Parameter calibration taken from RunGMM_Feedback_estim_RRA_5.m
+%--------------------------------------------------------------------------
+% fixed parameters
+INHABIT   = 1;
+PHI1      = 4;
+PHI4      = 1;
+KAPAone   = 0;
+DELTA     = 0.025;
+THETA     = 0.36;
+ETA       = 6;
+CHI       = 0;
+BETTAxhr  = 0;
+BETTAxhr40= 0;
+RHOD      = 0;
+GAMA      = 0.9999;
+CONSxhr20 = 0;
+RRA       = 5;
+
+% estimated parameters
+BETTA     = 0.996850651147000;
+B         = 0.684201133923000;
+H         = 0.338754441432000;
+PHI2      = 0.738293581320000;
+KAPAtwo   = 11.664785970704999;
+ALFA      = 0.831836572237000;
+RHOR      = 0.772754520116000;
+BETTAPAI  = 3.020381242896000;
+BETTAY    = 0.288367683973000;
+MYYPS     = 1.000911709188000;
+MYZ       = 1.005433723022000;
+RHOA      = 0.749465413198000;
+RHOG      = 0.847225569814000;
+PAI       = 1.010428794858000;
+CONSxhr40 = 0.992863217133000;
+GoY       = 0.207099399789000;
+STDA      = 0.015621059978000;
+STDG      = 0.047539390956000;
+STDD      = 0.008623441943000;
+
+% endogenous parameters set via steady state, no need to initialize
+%PHIzero  = ;
+%AA       = ;
+%PHI3     = ;
+%negVf    = ;
+
+model_diagnostics;
+% Model diagnostics show that some parameters are endogenously determined
+% via the steady state, so we run steady to calibrate all parameters
+steady;
+model_diagnostics;
+% Now all parameters are determined
+
+resid;
+check;
+
+%--------------------------------------------------------------------------
+% Shock distribution
+%--------------------------------------------------------------------------
+shocks;
+var eps_a = STDA^2;
+var eps_d = STDD^2;
+var eps_g = STDG^2;
+end;
+
+%--------------------------------------------------------------------------
+% Estimated Params block - these parameters will be estimated, we
+% initialize at calibrated values
+%--------------------------------------------------------------------------
+estimated_params;
+BETTA;
+B;
+H;
+PHI2;
+KAPAtwo;
+ALFA;
+RHOR;
+BETTAPAI;
+BETTAY;
+MYYPS;
+MYZ;
+RHOA;
+RHOG;
+PAI;
+CONSxhr40;
+GoY;
+stderr eps_a;
+stderr eps_g;
+stderr eps_d;
+end;
+
+estimated_params_init(use_calibration);
+end;
+
+%--------------------------------------------------------------------------
+% Compare whether toolbox yields equivalent moments at second order
+%--------------------------------------------------------------------------
+% Note that we compare results for orderApp=1|2 and not for orderApp=3, because
+% there is a small error in the replication files of the original article in the 
+% computation of the covariance matrix of the extended innovations vector.
+% The authors have been contacted, fixed it, and report that the results 
+% change only slightly at orderApp=3 to what they report in the paper. At
+% orderApp=2 all is correct and so the following part tests whether we get 
+% the same model moments at the calibrated parameters (we do not optimize).
+% We compare it to the replication file RunGMM_Feedback_estim_RRA.m with the
+% following settings: orderApp=1|2, seOn=1, q_lag=10, weighting=1+1;
+% scaled=0; optimizer=0; estimator=1; momentSet=2;
+%
+% Output of the replication files for orderApp=1
+AndreasenEtAl.Q1 = 60275.3715;
+AndreasenEtAl.moments1 =[ % note that we reshuffeled to be compatible with our matched moments block
+    {[ 1]}    {'Ex'  }    {'Gr_C   '}    {'     '  }    {'0.024388'   }    {'0.023726'   }
+    {[ 2]}    {'Ex'  }    {'Gr_I   '}    {'     '  }    {'0.031046'   }    {'0.027372'   }
+    {[ 3]}    {'Ex'  }    {'Infl  ' }    {'     '  }    {'0.03757'    }    {'0.041499'   }
+    {[ 4]}    {'Ex'  }    {'r1    ' }    {'     '  }    {'0.056048'   }    {'0.077843'   }
+    {[ 5]}    {'Ex'  }    {'r40   ' }    {'     '  }    {'0.069929'   }    {'0.077843'   }
+    {[ 6]}    {'Ex'  }    {'xhr40  '}    {'     '  }    {'0.017237'   }    {'0'          }
+    {[ 7]}    {'Ex'  }    {'GoY    '}    {'     '  }    {'-1.5745'    }    {'-1.5746'    }
+    {[ 8]}    {'Ex'  }    {'hours  '}    {'     '  }    {'-0.043353'  }    {'-0.043299'  }
+    {[ 9]}    {'Exx' }    {'Gr_C   '}    {'Gr_C   '}    {'0.0013159'  }    {'0.0012763'  }
+    {[17]}    {'Exx' }    {'Gr_C   '}    {'Gr_I   '}    {'0.0021789'  }    {'0.0017759'  }
+    {[18]}    {'Exx' }    {'Gr_C   '}    {'Infl  ' }    {'0.00067495' }    {'0.00077354' }
+    {[19]}    {'Exx' }    {'Gr_C   '}    {'r1    ' }    {'0.0011655'  }    {'0.0016538'  }
+    {[20]}    {'Exx' }    {'Gr_C   '}    {'r40   ' }    {'0.0015906'  }    {'0.0017949'  }
+    {[21]}    {'Exx' }    {'Gr_C   '}    {'xhr40  '}    {'0.0020911'  }    {'0.0017847'  }
+    {[10]}    {'Exx' }    {'Gr_I   '}    {'Gr_I   '}    {'0.0089104'  }    {'0.0053424'  }
+    {[22]}    {'Exx' }    {'Gr_I   '}    {'Infl  ' }    {'0.00063139' }    {'0.00064897' }
+    {[23]}    {'Exx' }    {'Gr_I   '}    {'r1    ' }    {'0.0011031'  }    {'0.0019533'  }
+    {[24]}    {'Exx' }    {'Gr_I   '}    {'r40   ' }    {'0.0018445'  }    {'0.0020602'  }
+    {[25]}    {'Exx' }    {'Gr_I   '}    {'xhr40  '}    {'0.00095556' }    {'0.0064856'  }
+    {[11]}    {'Exx' }    {'Infl  ' }    {'Infl  ' }    {'0.0020268'  }    {'0.0020922'  }
+    {[26]}    {'Exx' }    {'Infl  ' }    {'r1    ' }    {'0.0025263'  }    {'0.0036375'  }
+    {[27]}    {'Exx' }    {'Infl  ' }    {'r40   ' }    {'0.0029126'  }    {'0.0034139'  }
+    {[28]}    {'Exx' }    {'Infl  ' }    {'xhr40  '}    {'-0.00077101'}    {'-0.0011665' }
+    {[12]}    {'Exx' }    {'r1    ' }    {'r1    ' }    {'0.0038708'  }    {'0.0066074'  }
+    {[29]}    {'Exx' }    {'r1    ' }    {'r40   ' }    {'0.0044773'  }    {'0.0062959'  }
+    {[30]}    {'Exx' }    {'r1    ' }    {'xhr40  '}    {'-0.00048202'}    {'-0.00075499'}
+    {[13]}    {'Exx' }    {'r40   ' }    {'r40   ' }    {'0.0054664'  }    {'0.0061801'  }
+    {[31]}    {'Exx' }    {'r40   ' }    {'xhr40  '}    {'0.00053864' }    {'-0.00030456'}
+    {[14]}    {'Exx' }    {'xhr40  '}    {'xhr40  '}    {'0.053097'   }    {'0.012048'   }
+    {[15]}    {'Exx' }    {'GoY    '}    {'GoY    '}    {'2.4863'     }    {'2.4872'     }
+    {[16]}    {'Exx' }    {'hours  '}    {'hours  '}    {'0.0018799'  }    {'0.0018759'  }
+    {[32]}    {'Exx1'}    {'Gr_C   '}    {'Gr_C   '}    {'0.00077917' }    {'0.00080528' }
+    {[33]}    {'Exx1'}    {'Gr_I   '}    {'Gr_I   '}    {'0.0050104'  }    {'0.0017036'  }
+    {[34]}    {'Exx1'}    {'Infl  ' }    {'Infl  ' }    {'0.0019503'  }    {'0.0020185'  }
+    {[35]}    {'Exx1'}    {'r1    ' }    {'r1    ' }    {'0.0038509'  }    {'0.0065788'  }
+    {[36]}    {'Exx1'}    {'r40   ' }    {'r40   ' }    {'0.0054699'  }    {'0.0061762'  }
+    {[37]}    {'Exx1'}    {'xhr40  '}    {'xhr40  '}    {'-0.00098295'}    {'-4.5519e-15'}
+    {[38]}    {'Exx1'}    {'GoY    '}    {'GoY    '}    {'2.4868'     }    {'2.4863'     }
+    {[39]}    {'Exx1'}    {'hours  '}    {'hours  '}    {'0.0018799'  }    {'0.0018755'  }
+];
+
+% Output of the replication files for orderApp=2
+AndreasenEtAl.Q2 = 140.8954;
+AndreasenEtAl.moments2 =[ % note that we reshuffeled to be compatible with our matched moments block
+    {[ 1]}    {'Ex'  }    {'Gr_C   '}    {'     '  }    {'0.024388'   }    {'0.023726'   }
+    {[ 2]}    {'Ex'  }    {'Gr_I   '}    {'     '  }    {'0.031046'   }    {'0.027372'   }
+    {[ 3]}    {'Ex'  }    {'Infl  ' }    {'     '  }    {'0.03757'    }    {'0.034618'   }
+    {[ 4]}    {'Ex'  }    {'r1    ' }    {'     '  }    {'0.056048'   }    {'0.056437'   }
+    {[ 5]}    {'Ex'  }    {'r40   ' }    {'     '  }    {'0.069929'   }    {'0.07051'    }
+    {[ 6]}    {'Ex'  }    {'xhr40  '}    {'     '  }    {'0.017237'   }    {'0.014242'   }
+    {[ 7]}    {'Ex'  }    {'GoY    '}    {'     '  }    {'-1.5745'    }    {'-1.574'     }
+    {[ 8]}    {'Ex'  }    {'hours  '}    {'     '  }    {'-0.043353'  }    {'-0.043351'  }
+    {[ 9]}    {'Exx' }    {'Gr_C   '}    {'Gr_C   '}    {'0.0013159'  }    {'0.0012917'  }
+    {[17]}    {'Exx' }    {'Gr_C   '}    {'Gr_I   '}    {'0.0021789'  }    {'0.0017862'  }
+    {[18]}    {'Exx' }    {'Gr_C   '}    {'Infl  ' }    {'0.00067495' }    {'0.00061078' }
+    {[19]}    {'Exx' }    {'Gr_C   '}    {'r1    ' }    {'0.0011655'  }    {'0.0011494'  }
+    {[20]}    {'Exx' }    {'Gr_C   '}    {'r40   ' }    {'0.0015906'  }    {'0.0016149'  }
+    {[21]}    {'Exx' }    {'Gr_C   '}    {'xhr40  '}    {'0.0020911'  }    {'0.002203'   }
+    {[10]}    {'Exx' }    {'Gr_I   '}    {'Gr_I   '}    {'0.0089104'  }    {'0.0054317'  }
+    {[22]}    {'Exx' }    {'Gr_I   '}    {'Infl  ' }    {'0.00063139' }    {'0.00045278' }
+    {[23]}    {'Exx' }    {'Gr_I   '}    {'r1    ' }    {'0.0011031'  }    {'0.0013672'  }
+    {[24]}    {'Exx' }    {'Gr_I   '}    {'r40   ' }    {'0.0018445'  }    {'0.0018557'  }
+    {[25]}    {'Exx' }    {'Gr_I   '}    {'xhr40  '}    {'0.00095556' }    {'0.0067742'  }
+    {[11]}    {'Exx' }    {'Infl  ' }    {'Infl  ' }    {'0.0020268'  }    {'0.0016583'  }
+    {[26]}    {'Exx' }    {'Infl  ' }    {'r1    ' }    {'0.0025263'  }    {'0.0024521'  }
+    {[27]}    {'Exx' }    {'Infl  ' }    {'r40   ' }    {'0.0029126'  }    {'0.002705'   }
+    {[28]}    {'Exx' }    {'Infl  ' }    {'xhr40  '}    {'-0.00077101'}    {'-0.00065007'}
+    {[12]}    {'Exx' }    {'r1    ' }    {'r1    ' }    {'0.0038708'  }    {'0.0038274'  }
+    {[29]}    {'Exx' }    {'r1    ' }    {'r40   ' }    {'0.0044773'  }    {'0.004297'   }
+    {[30]}    {'Exx' }    {'r1    ' }    {'xhr40  '}    {'-0.00048202'}    {'6.3243e-05' }
+    {[13]}    {'Exx' }    {'r40   ' }    {'r40   ' }    {'0.0054664'  }    {'0.0051686'  }
+    {[31]}    {'Exx' }    {'r40   ' }    {'xhr40  '}    {'0.00053864' }    {'0.00066645' }
+    {[14]}    {'Exx' }    {'xhr40  '}    {'xhr40  '}    {'0.053097'   }    {'0.013543'   }
+    {[15]}    {'Exx' }    {'GoY    '}    {'GoY    '}    {'2.4863'     }    {'2.4858'     }
+    {[16]}    {'Exx' }    {'hours  '}    {'hours  '}    {'0.0018799'  }    {'0.0018804'  }
+    {[32]}    {'Exx1'}    {'Gr_C   '}    {'Gr_C   '}    {'0.00077917' }    {'0.00081772' }
+    {[33]}    {'Exx1'}    {'Gr_I   '}    {'Gr_I   '}    {'0.0050104'  }    {'0.0017106'  }
+    {[34]}    {'Exx1'}    {'Infl  ' }    {'Infl  ' }    {'0.0019503'  }    {'0.0015835'  }
+    {[35]}    {'Exx1'}    {'r1    ' }    {'r1    ' }    {'0.0038509'  }    {'0.0037985'  }
+    {[36]}    {'Exx1'}    {'r40   ' }    {'r40   ' }    {'0.0054699'  }    {'0.0051642'  }
+    {[37]}    {'Exx1'}    {'xhr40  '}    {'xhr40  '}    {'-0.00098295'}    {'0.00020285' }
+    {[38]}    {'Exx1'}    {'GoY    '}    {'GoY    '}    {'2.4868'     }    {'2.4848'     }
+    {[39]}    {'Exx1'}    {'hours  '}    {'hours  '}    {'0.0018799'  }    {'0.0018799'  }
+];
+
+@#for orderApp in 1:2
+
+method_of_moments(
+          mom_method = GMM                    % method of moments method; possible values: GMM|SMM
+        , datafile   = 'AFVRR_data.mat'       % name of filename with data
+        , bartlett_kernel_lag = 10          % bandwith in optimal weighting matrix
+        , order = @{orderApp}                 % order of Taylor approximation in perturbation
+        , pruning                             % use pruned state space system at higher-order
+        % , verbose                           % display and store intermediate estimation results
+        , weighting_matrix = ['DIAGONAL']      % weighting matrix in moments distance objective function; possible values: OPTIMAL|IDENTITY_MATRIX|DIAGONAL|filename        
+        % , TeX                               % print TeX tables and graphics
+        % Optimization options that can be set by the user in the mod file, otherwise default values are provided        
+        %, huge_number=1D10                   % value for replacing the infinite bounds on parameters by finite numbers. Used by some optimizers for numerical reasons
+        , mode_compute = 0                    % specifies the optimizer for minimization of moments distance, note that by default there is a new optimizer        
+        , optim = ('TolFun', 1e-6
+                   ,'TolX', 1e-6
+                   ,'MaxIter', 3000
+                   ,'MaxFunEvals', 1D6
+                   ,'UseParallel' , 1
+                   %,'Jacobian' , 'on'
+                  )    % a list of NAME and VALUE pairs to set options for the optimization routines. Available options depend on mode_compute
+        %, silent_optimizer                  % run minimization of moments distance silently without displaying results or saving files in between
+        %, analytic_standard_errors
+        , se_tolx=1e-10
+);
+
+% Check results
+
+fprintf('****************************************************************\n')
+fprintf('Compare Results for perturbation order @{orderApp}\n')
+fprintf('****************************************************************\n')
+dev_Q            = AndreasenEtAl.Q@{orderApp} - oo_.mom.Q;
+dev_datamoments  = str2double(AndreasenEtAl.moments@{orderApp}(:,5)) - oo_.mom.data_moments;
+dev_modelmoments = str2double(AndreasenEtAl.moments@{orderApp}(:,6)) - oo_.mom.model_moments;
+
+table([AndreasenEtAl.Q@{orderApp} ; str2double(AndreasenEtAl.moments@{orderApp}(:,5)) ; str2double(AndreasenEtAl.moments@{orderApp}(:,6))],...
+      [oo_.mom.Q                  ; oo_.mom.data_moments                              ; oo_.mom.model_moments                            ],...
+      [dev_Q                      ; dev_datamoments                                   ; dev_modelmoments                                 ],...
+      'VariableNames', {'Andreasen et al', 'Dynare', 'dev'},...
+      'RowNames', ['Q'; strcat('Data_', M_.matched_moments(:,4)); strcat('Model_', M_.matched_moments(:,4))])
+
+if norm(dev_modelmoments)> 1e-4
+    warning('Something wrong in the computation of moments at order @{orderApp}')
+end
+
+@#endfor
+
+%--------------------------------------------------------------------------
+% Replicate estimation at orderApp=3
+%--------------------------------------------------------------------------
+@#ifdef DoEstimation
+method_of_moments(
+          mom_method = GMM                    % method of moments method; possible values: GMM|SMM
+        , datafile   = 'AFVRR_data.mat'       % name of filename with data
+        , bartlett_kernel_lag = 10            % bandwith in optimal weighting matrix
+        , order = 3                           % order of Taylor approximation in perturbation
+        , pruning                             % use pruned state space system at higher-order
+        % , verbose                           % display and store intermediate estimation results
+        , weighting_matrix = ['DIAGONAL', 'Optimal']      % weighting matrix in moments distance objective function; possible values: OPTIMAL|IDENTITY_MATRIX|DIAGONAL|filename        
+        % , TeX                               % print TeX tables and graphics
+        % Optimization options that can be set by the user in the mod file, otherwise default values are provided        
+        %, huge_number=1D10                   % value for replacing the infinite bounds on parameters by finite numbers. Used by some optimizers for numerical reasons
+        , mode_compute = 13                   % specifies the optimizer for minimization of moments distance, note that by default there is a new optimizer
+        , additional_optimizer_steps = [13]
+        , optim = ('TolFun', 1e-6
+                   ,'TolX', 1e-6
+                   ,'MaxIter', 3000
+                   ,'MaxFunEvals', 1D6
+                   ,'UseParallel' , 1
+                   %,'Jacobian' , 'on'
+                  )    % a list of NAME and VALUE pairs to set options for the optimization routines. Available options depend on mode_compute
+        %, silent_optimizer                  % run minimization of moments distance silently without displaying results or saving files in between
+        %, analytic_standard_errors
+        , se_tolx=1e-10
+);
+@#endif
\ No newline at end of file
diff --git a/tests/estimation/method_of_moments/AFVRR/AFVRR_common.inc b/tests/estimation/method_of_moments/AFVRR/AFVRR_common.inc
new file mode 100644
index 0000000000000000000000000000000000000000..76aea9e0b0104df02664e55bc65fedb338af2376
--- /dev/null
+++ b/tests/estimation/method_of_moments/AFVRR/AFVRR_common.inc
@@ -0,0 +1,540 @@
+% DSGE model based on replication files of
+% Andreasen, Fernandez-Villaverde, Rubio-Ramirez (2018), The Pruned State-Space System for Non-Linear DSGE Models: Theory and Empirical Applications, Review of Economic Studies, 85, p. 1-49
+% Original code by Martin M. Andreasen, Jan 2016
+% Adapted for Dynare by Willi Mutschler (@wmutschl, willi@mutschler.eu), Jan 2021
+% =========================================================================
+% Copyright (C) 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 <http://www.gnu.org/licenses/>.
+% =========================================================================
+
+%--------------------------------------------------------------------------
+% Variable declaration
+%--------------------------------------------------------------------------
+var
+ln_k
+ln_s
+ln_a
+ln_g
+ln_d
+
+ln_c
+ln_r
+ln_pai
+ln_h
+ln_q
+ln_evf
+ln_iv
+ln_x2
+ln_la
+ln_goy
+ln_Esdf
+
+xhr20
+xhr40
+Exhr
+
+@#for i in 1:40
+ln_p@{i}
+@#endfor
+
+Obs_Gr_C
+Obs_Gr_I
+Obs_Infl
+Obs_r1
+Obs_r40
+Obs_xhr40
+Obs_GoY
+Obs_hours
+;
+
+predetermined_variables ln_k ln_s;
+
+varobs Obs_Gr_C Obs_Gr_I Obs_Infl Obs_r1 Obs_r40 Obs_xhr40 Obs_GoY Obs_hours;
+
+%--------------------------------------------------------------------------
+% Exogenous shocks
+%--------------------------------------------------------------------------
+varexo 
+eps_a
+eps_d
+eps_g
+;
+
+%--------------------------------------------------------------------------
+% Parameter declaration
+%--------------------------------------------------------------------------
+parameters 
+BETTA
+B
+INHABIT
+H
+PHI1
+PHI2
+RRA
+PHI4
+KAPAone
+KAPAtwo
+DELTA
+THETA
+ETA
+ALFA
+CHI
+RHOR
+BETTAPAI
+BETTAY
+MYYPS
+MYZ
+RHOA
+%STDA
+RHOG
+%STDG
+RHOD
+%STDD
+CONSxhr40
+BETTAxhr
+BETTAxhr40
+CONSxhr20
+PAI
+GAMA
+GoY
+
+%auxiliary
+PHIzero
+AA
+PHI3
+negVf
+;
+
+
+%--------------------------------------------------------------------------
+% Model equations
+%--------------------------------------------------------------------------
+% Based on DSGE_model_NegVf_yieldCurve.m and DSGE_model_PosVf_yieldCurve.m
+% Note that we include an auxiliary parameter negVf to distinguish whether
+% the steady state value function is positive (negVf=0) or negative (negVf=1).
+% This parameter is endogenously determined in the steady_state_model block.
+
+model;
+%--------------------------------------------------------------------------
+% Auxiliary expressions
+%--------------------------------------------------------------------------
+% do exp transform such that variables are logged variables
+@#for var in [ "k", "s", "c", "r", "a", "g", "d", "pai", "h", "q", "evf", "iv", "x2", "la", "goy", "Esdf" ]
+#@{var}_ba1  = exp(ln_@{var}(-1));
+#@{var}_cu   = exp(ln_@{var});
+#@{var}_cup  = exp(ln_@{var}(+1));
+@#endfor
+@#for i in 1:40
+#p@{i}_cu   = exp(ln_p@{i});
+#p@{i}_cup  = exp(ln_p@{i}(+1));
+@#endfor
+% these variables are not transformed
+#xhr20_cu  = xhr20;
+#xhr20_cup = xhr20(+1);
+#xhr40_cu  = xhr40;
+#xhr40_cup = xhr40(+1);
+#Exhr_cu   = Exhr;
+#Exhr_cup  = Exhr(+1);
+
+% auxiliary steady state variables
+#K  = exp(steady_state(ln_k));
+#IV = exp(steady_state(ln_iv));
+#C  = exp(steady_state(ln_c));
+#Y  = (C + IV)/(1-GoY);
+#R  = exp(steady_state(ln_r));
+#G  = Y-C-IV;
+
+#removeMeanXhr = 1;
+
+% The atemporal relations if possible
+% No stochastic trend in investment specific shocks
+#myyps_cu  = MYYPS;
+#myyps_cup = MYYPS;
+
+% No stochastic trend in non-stationary technology shocks
+#myz_cu    = MYZ;
+#myz_cup   = MYZ;
+
+% Defining myzstar
+#MYZSTAR    = MYYPS^(THETA/(1-THETA))*MYZ;
+#myzstar_cu = myyps_cu ^(THETA/(1-THETA))*myz_cu;
+#myzstar_cup= myyps_cup^(THETA/(1-THETA))*myz_cup;
+
+% The expression for the value function (only valid for deterministic trends!)
+% Note that we make use of auxiliary parameter negVf to switch signs
+#mvf_cup   = -negVf*(d_cup/(1-PHI2)*((c_cup-B*c_cu*MYZSTAR^-1)^(1-PHI2)-1) + d_cup*PHIzero/(1-PHI1)*(1-h_cup)^(1-PHI1) - negVf* BETTA*MYZSTAR^((1-PHI4)*(1-PHI2))*AA*evf_cup^(1/(1-PHI3)));
+
+% The growth rate in lambda
+#myla_cup  = (la_cup/la_cu)*(AA*evf_cu^(1/(1-PHI3))/mvf_cup)^PHI3*myzstar_cup^(-PHI2*(1-PHI4)-PHI4);
+
+% The relation between the optimal price for the firms and the pris and inflation 
+%ptil_cu   = ((1-ALFA*(pai_ba1^CHI/pai_cu )^(1-ETA))/(1-ALFA))^(1/(1-ETA));
+%ptil_cup  = ((1-ALFA*(pai_cu ^CHI/pai_cup)^(1-ETA))/(1-ALFA))^(1/(1-ETA));
+#ptil_cu   = ((1-ALFA*(1/pai_cu )^(1-ETA))/(1-ALFA))^(1/(1-ETA));
+#ptil_cup  = ((1-ALFA*(1/pai_cup)^(1-ETA))/(1-ALFA))^(1/(1-ETA));
+        
+% From the households' FOC for labor
+#w_cu      = d_cu*PHIzero*(1-h_cu )^(-PHI1)/la_cu;
+#w_cup     = d_cu*PHIzero*(1-h_cup)^(-PHI1)/la_cup;
+% Shouldn't w_cup include d_cup? Let's stick to the original (wrong) code in the replication files as results don't change dramatically... [@wmutschl]
+
+% The firms' FOC for labor 
+#mc_cu     = w_cu /((1-THETA)*a_cu *myyps_cu ^(-THETA/(1-THETA))*myz_cu ^-THETA *k_cu ^THETA*h_cu ^(-THETA));
+#mc_cup    = w_cup/((1-THETA)*a_cup*myyps_cup^(-THETA/(1-THETA))*myz_cup^-THETA *k_cup^THETA*h_cup^(-THETA));
+
+% The firms' FOC for capital 
+#rk_cu     = mc_cu *THETA* a_cu *myyps_cu *myz_cu ^(1-THETA)*k_cu ^(THETA-1)*h_cu ^(1-THETA);
+#rk_cup    = mc_cup*THETA* a_cup*myyps_cup*myz_cup^(1-THETA)*k_cup^(THETA-1)*h_cup^(1-THETA);
+
+% The income identity
+#y_cu = c_cu + iv_cu + g_cu;
+
+%--------------------------------------------------------------------------
+% Actual model equations
+%--------------------------------------------------------------------------
+
+[name='Expected value of the value function']
+0 = -evf_cu + (mvf_cup/AA)^(1-PHI3);
+
+[name='Households FOC for capital']
+0 = -q_cu+BETTA*myla_cup/myyps_cup*(rk_cup+q_cup*(1-DELTA) -q_cup*KAPAtwo/2*(iv_cup/k_cup*myyps_cup*myzstar_cup - IV/K*MYYPS*MYZSTAR)^2 +q_cup*KAPAtwo*(iv_cup/k_cup*myyps_cup*myzstar_cup - IV/K*MYYPS*MYZSTAR)*iv_cup/k_cup*myyps_cup*myzstar_cup);
+
+[name='Households FOC for investments']
+0 = -1+q_cu*(1-KAPAone/2*(iv_cu/IV-1)^2-iv_cu/IV*KAPAone*(iv_cu/IV-1)-KAPAtwo*(iv_cu/k_cu*myyps_cu*myzstar_cu - IV/K*MYYPS*MYZSTAR));
+
+[name='Euler equation for consumption']
+0 = -1+BETTA*r_cu*exp(CONSxhr40*xhr40_cu + CONSxhr20*xhr20_cu)*myla_cup/pai_cup;
+
+[name='Households FOC for consumption']
+0 = -la_cu  + d_cu*(c_cu -B*c_ba1*myzstar_cu^-1)^(-PHI2) -INHABIT*B*BETTA*d_cup*(AA*evf_cu^(1/(1-PHI3))/mvf_cup)^PHI3*(c_cup -B*c_cu*myzstar_cup^-1)^(-PHI2)*myzstar_cup^(-PHI2*(1-PHI4)-PHI4);
+
+[name='Nonlinear pricing, relation for x1 = (ETA-1)/ETA*x2']
+0= -(ETA-1)/ETA*x2_cu+y_cu*mc_cu*ptil_cu^(-ETA-1) +ALFA*BETTA*myla_cup*(ptil_cu/ptil_cup)^(-ETA-1)*(1/pai_cup)^(-ETA)*(ETA-1)/ETA*x2_cup*myzstar_cup;
+  
+[name='Nonlinear pricing, relation for x2']
+0=-x2_cu+y_cu*ptil_cu^-ETA +ALFA*BETTA*myla_cup*(ptil_cu/ptil_cup)^(-ETA)*(1/pai_cup)^(1-ETA)*x2_cup*myzstar_cup;
+
+[name='Nonlinear pricing, relation for s']
+0= -s_cup+(1-ALFA)*ptil_cu^(-ETA)+ALFA*(pai_cu/1)^ETA*s_cu;
+  
+[name='Interest rate rule']
+0 = -log(r_cu/R)+RHOR*log(r_ba1/R)+(1-RHOR)*(BETTAPAI*log(pai_cu/PAI)+BETTAY*log(y_cu/Y) + BETTAxhr*(BETTAxhr40*xhr40_cu - removeMeanXhr*Exhr_cu));
+
+[name='Production function']
+0 = -y_cu*s_cup + a_cu *(k_cu *myyps_cu ^(-1/(1-THETA))*myz_cu ^-1)^THETA*h_cu ^(1-THETA);
+
+[name='Relation for physical capital stock']
+0= -k_cup + (1-DELTA)*k_cu*(myyps_cu*myzstar_cu)^-1 + iv_cu - iv_cu*KAPAone/2*(iv_cu/IV-1)^2 - k_cu*(myyps_cu*myzstar_cu)^-1*KAPAtwo/2*(iv_cu/k_cu*myyps_cu*myzstar_cu - IV/K*MYYPS*MYZSTAR)^2;
+
+[name='Goverment spending over output']
+0=-goy_cu + g_cu/y_cu;
+
+[name='The yield curve: p1']
+0= -p1_cu + 1/r_cu;
+
+@#for i in 2:40
+[name='The yield curve: p@{i}']
+0= -p@{i}_cu + BETTA*myla_cup/pai_cup*p@{i-1}_cup;
+@#endfor
+
+[name='Stochastic discount factor']
+0= -Esdf_cu+ BETTA*myla_cup/pai_cup;
+
+[name='Expected 5 year excess holding period return']
+0= -xhr20_cu+ log(p19_cup) - log(p20_cu) - log(r_cu);
+
+[name='Expected 10 year excess holding period return']
+0= -xhr40_cu+ log(p39_cup) - log(p40_cu) - log(r_cu);
+
+[name='Mean of expected excess holding period return in Taylor rule']
+0= -Exhr_cu + (1-GAMA)*(BETTAxhr40*xhr40_cu) + GAMA*Exhr_cup;
+
+[name='Exogenous process for productivity']
+0 = -log(a_cu)+RHOA*log(a_ba1) + eps_a;
+
+[name='Exogenous process for government spending']
+0 = -log(g_cu/G)+RHOG*log(g_ba1/G) + eps_g;
+
+[name='Exogenous process for discount factor shifter']
+0 = -log(d_cu)+RHOD*log(d_ba1) + eps_d;
+
+[name='Observable annualized consumption growth']
+Obs_Gr_C  = 4*( ln_c -ln_c(-1) + log(MYZSTAR));
+
+[name='Observable annualized investment growth']
+Obs_Gr_I  = 4*( ln_iv - ln_iv(-1) + log(MYZSTAR)+log(MYYPS));
+
+[name='Observable annualized inflation']
+Obs_Infl  = 4*( ln_pai);
+
+[name='Observable annualized one-quarter nominal yield']
+Obs_r1    = 4*( ln_r);
+
+[name='Observable annualized 10-year nominal yield']
+Obs_r40   = 4*( -1/40*ln_p40);
+
+[name='Observable annualized 10-year ex post excess holding period return']
+Obs_xhr40 = 4*( ln_p39 - ln_p40(-1) - ln_r(-1) );
+
+[name='Observable annualized log ratio of government spending to GDP']
+Obs_GoY   = 4*( 1/4*ln_goy);
+
+[name='Observable annualized log of hours']
+Obs_hours = 4*( 1/100*ln_h);
+end;
+
+
+%--------------------------------------------------------------------------
+% Steady State Computations
+%--------------------------------------------------------------------------
+% Based on DSGE_model_yieldCurve_ss.m, getPHI3.m, ObjectGMM.m
+% Note that we include an auxiliary parameter negVf to distinguish whether
+% the steady state value function is positive (negVf=0) or negative (negVf=1).
+% This parameter is endogenously determined in the steady_state_model block.
+
+
+steady_state_model;
+
+% The growth rate in the firms' fixed costs
+MYZSTARBAR       = MYYPS^(THETA/(1-THETA))*MYZ;
+
+% The growth rate for lampda
+MYLABAR          = MYZSTARBAR^(-PHI2*(1-PHI4)-PHI4);
+
+% The relative optimal price for firms
+PTILBAR 		  = ((1-ALFA*PAI^((CHI-1)*(1-ETA)))/(1-ALFA))^(1/(1-ETA)); 
+
+% The state variable s for distortions between output and produktion
+SBAR             = ((1-ALFA)*PTILBAR^(-ETA))/(1-ALFA*PAI^((1-CHI)*ETA));
+
+% The 1-period interest rate
+RBAR 			  = PAI/(BETTA*MYLABAR);
+
+% The market price of capital
+QBAR             = 1;
+
+% The real price of renting capital
+RKBAR            = QBAR*(MYYPS/(BETTA*MYLABAR)-(1-DELTA));
+
+% The marginal costs in the firms
+MCBAR            = (1-ALFA*BETTA*MYLABAR*PAI^((1-CHI)*ETA)*MYZSTARBAR)*(ETA-1)/ETA*PTILBAR/(1-ALFA*BETTA*MYLABAR*PAI^((CHI-1)*(1-ETA))*MYZSTARBAR);
+            
+% The capital stock 
+KBAR             = H*(RKBAR/(MCBAR*THETA*MYYPS*MYZ^(1-THETA)))^(1/(THETA-1));
+
+% The wage level 
+WBAR             = MCBAR*(1-THETA)*MYYPS^(-THETA/(1-THETA))*MYZ^-THETA*(KBAR/H)^THETA;
+
+% The level of investment
+IVBAR            = KBAR - (1-DELTA)*KBAR*MYYPS^(-1/(1-THETA))*MYZ^-1; 
+
+% The consumption level
+CBAR              = ((1-GoY)*(KBAR*MYYPS^(-1/(1-THETA))*MYZ^-1)^THETA*H^(1-THETA))/SBAR-IVBAR;
+
+% The output level 
+YBAR             = (CBAR + IVBAR)/(1-GoY); 
+
+% The value of lambda
+LABAR            = (CBAR-B*CBAR*MYZSTARBAR^-1)^-PHI2 - INHABIT*B*BETTA*(CBAR-B*CBAR*MYZSTARBAR^-1)^-PHI2*MYZSTARBAR^(-PHI2*(1-PHI4)-PHI4);
+
+% The value of PHIzero
+PHIzero       = LABAR*WBAR*(1-H)^PHI1;
+
+% The level of the value function 
+VFBAR            = 1/(1-BETTA*MYZSTARBAR^((1-PHI4)*(1-PHI2)))*(1/(1-PHI2)*((CBAR-B*CBAR*MYZSTARBAR^-1)^(1-PHI2)-1)+PHIzero/(1-PHI1)*(1-H)^(1-PHI1));
+UBAR             = 1/(1-PHI2)*((CBAR-B*CBAR*MYZSTARBAR^-1)^(1-PHI2)-1)+PHIzero/(1-PHI1)*(1-H)^(1-PHI1);
+[AA, EVFBAR, PHI3, negVf, info]= AFVRR_steady_helper(VFBAR,RBAR,IVBAR,CBAR,KBAR,LABAR,QBAR,YBAR,  BETTA,B,PAI,H,PHIzero,PHI1,PHI2,THETA,MYYPS,MYZ,INHABIT,RRA,CONSxhr40);
+% The value of X2
+X2BAR            = YBAR*PTILBAR^(-ETA)/(1-BETTA*ALFA*MYLABAR*PAI^((CHI-1)*(1-ETA))*MYZSTARBAR);
+
+% Government spending
+GBAR             = GoY*YBAR;
+%**************************************************************************        
+
+% map into model variables
+ln_k = log(KBAR);
+ln_s = log(SBAR);
+ln_c_ba1 = log(CBAR);
+ln_r_ba1 = log(RBAR);
+ln_a = log(1);
+ln_g = log(GBAR);
+ln_d = log(1);
+
+ln_c = log(CBAR);
+ln_r = log(RBAR);
+ln_pai = log(PAI);
+ln_h = log(H);
+ln_q = log(QBAR);
+ln_evf = log(EVFBAR);
+ln_iv = log(IVBAR);
+ln_x2 = log(X2BAR);
+ln_la = log(LABAR);
+ln_goy = log(GoY);
+ln_Esdf = log(1/RBAR);
+xhr20 = 0;
+xhr40 = 0;
+Exhr = 0;
+% The yield curve
+ln_p1 = log((1/RBAR)^1);
+ln_p2 = log((1/RBAR)^2);
+ln_p3 = log((1/RBAR)^3);
+ln_p4 = log((1/RBAR)^4);
+ln_p5 = log((1/RBAR)^5);
+ln_p6 = log((1/RBAR)^6);
+ln_p7 = log((1/RBAR)^7);
+ln_p8 = log((1/RBAR)^8);
+ln_p9 = log((1/RBAR)^9);
+ln_p10 = log((1/RBAR)^10);
+ln_p11 = log((1/RBAR)^11);
+ln_p12 = log((1/RBAR)^12);
+ln_p13 = log((1/RBAR)^13);
+ln_p14 = log((1/RBAR)^14);
+ln_p15 = log((1/RBAR)^15);
+ln_p16 = log((1/RBAR)^16);
+ln_p17 = log((1/RBAR)^17);
+ln_p18 = log((1/RBAR)^18);
+ln_p19 = log((1/RBAR)^19);
+ln_p20 = log((1/RBAR)^20);
+ln_p21 = log((1/RBAR)^21);
+ln_p22 = log((1/RBAR)^22);
+ln_p23 = log((1/RBAR)^23);
+ln_p24 = log((1/RBAR)^24);
+ln_p25 = log((1/RBAR)^25);
+ln_p26 = log((1/RBAR)^26);
+ln_p27 = log((1/RBAR)^27);
+ln_p28 = log((1/RBAR)^28);
+ln_p29 = log((1/RBAR)^29);
+ln_p30 = log((1/RBAR)^30);
+ln_p31 = log((1/RBAR)^31);
+ln_p32 = log((1/RBAR)^32);
+ln_p33 = log((1/RBAR)^33);
+ln_p34 = log((1/RBAR)^34);
+ln_p35 = log((1/RBAR)^35);
+ln_p36 = log((1/RBAR)^36);
+ln_p37 = log((1/RBAR)^37);
+ln_p38 = log((1/RBAR)^38);
+ln_p39 = log((1/RBAR)^39);
+ln_p40 = log((1/RBAR)^40);
+
+Obs_Gr_C  = 4*( log(MYZSTARBAR) );
+Obs_Gr_I  = 4*( log(MYZSTARBAR)+log(MYYPS) );
+Obs_Infl  = 4*( ln_pai );
+Obs_r1    = 4*( ln_r );
+Obs_r40   = 4*( -1/40*ln_p40 );
+Obs_xhr40 = 4*( xhr40 );
+Obs_GoY   = 4*( 1/4*ln_goy );
+Obs_hours = 4*( 1/100*ln_h );
+end;
+
+%--------------------------------------------------------------------------
+% Declare moments to use in estimation
+%--------------------------------------------------------------------------
+% These are the moments used in the paper; corresponds to momentSet=2 in the replication files
+
+matched_moments;
+%mean
+Obs_Gr_C;
+Obs_Gr_I;
+Obs_Infl;
+Obs_r1;
+Obs_r40;
+Obs_xhr40;
+Obs_GoY;
+Obs_hours;
+
+% all variances
+Obs_Gr_C*Obs_Gr_C;
+Obs_Gr_I*Obs_Gr_I;
+Obs_Infl*Obs_Infl;
+Obs_r1*Obs_r1;
+Obs_r40*Obs_r40;
+Obs_xhr40*Obs_xhr40;
+Obs_GoY*Obs_GoY;
+Obs_hours*Obs_hours;
+
+% covariance excluding GoY and hours
+Obs_Gr_C*Obs_Gr_I;
+Obs_Gr_C*Obs_Infl;
+Obs_Gr_C*Obs_r1;
+Obs_Gr_C*Obs_r40;
+Obs_Gr_C*Obs_xhr40;
+%Obs_Gr_C*Obs_GoY;
+%Obs_Gr_C*Obs_hours;
+
+Obs_Gr_I*Obs_Infl;
+Obs_Gr_I*Obs_r1;
+Obs_Gr_I*Obs_r40;
+Obs_Gr_I*Obs_xhr40;
+%Obs_Gr_I*Obs_GoY;
+%Obs_Gr_I*Obs_hours;
+
+Obs_Infl*Obs_r1;
+Obs_Infl*Obs_r40;
+Obs_Infl*Obs_xhr40;
+%Obs_Infl*Obs_GoY;
+%Obs_Infl*Obs_hours;
+
+Obs_r1*Obs_r40;
+Obs_r1*Obs_xhr40;
+%Obs_r1*Obs_GoY;
+%Obs_r1*Obs_hours;
+
+Obs_r40*Obs_xhr40;
+%Obs_r40*Obs_GoY;
+%Obs_r40*Obs_hours;
+
+%Obs_xhr40*Obs_GoY;
+%Obs_xhr40*Obs_hours;
+
+%Obs_GoY*Obs_hours;
+
+%first autocovariance
+Obs_Gr_C*Obs_Gr_C(-1);
+Obs_Gr_I*Obs_Gr_I(-1);
+Obs_Infl*Obs_Infl(-1);
+Obs_r1*Obs_r1(-1);
+Obs_r40*Obs_r40(-1);
+Obs_xhr40*Obs_xhr40(-1);
+Obs_GoY*Obs_GoY(-1);
+Obs_hours*Obs_hours(-1);
+end;
+
+%--------------------------------------------------------------------------
+% Create Data
+%--------------------------------------------------------------------------
+@#ifdef CreateData
+verbatim;
+% From 1961Q3 to 2007Q4
+DataUS = xlsread('Data_PruningPaper_v5.xlsx','Data_used','E3:M188');
+%                                         ANNUALIZED (except for hours and GoY)
+%           1   2      3     4     5        6      7    8     9        
+% Lables: Date Gr_C   Gr_I  GoY   hours   Infl_C   r1   r40  xhr40   
+%label_data = {'Gr_C   ', 'Gr_I   ','Infl  ', 'r1    ', 'r40   ', 'xhr40  ','GoY    ', 'hours  '};
+%DataUS     = [DataUS(:,2:3) DataUS(:,6:8)  DataUS(:,9) log(DataUS(:,4)) 4*log(DataUS(:,5))/100];
+Obs_Gr_C  = DataUS(:,2);
+Obs_Gr_I  = DataUS(:,3);
+Obs_Infl  = DataUS(:,6);
+Obs_r1    = DataUS(:,7);
+Obs_r40   = DataUS(:,8);
+Obs_xhr40 = DataUS(:,9);
+Obs_GoY   = log(DataUS(:,4));
+Obs_hours = 4*log(DataUS(:,5))/100;
+
+save('AFVRR_data.mat','Obs_Gr_C','Obs_Gr_I','Obs_Infl','Obs_r1','Obs_r40','Obs_xhr40','Obs_GoY','Obs_hours');
+pause(1);
+end;
+@#endif
\ No newline at end of file
diff --git a/tests/estimation/method_of_moments/AFVRR/AFVRR_data.mat b/tests/estimation/method_of_moments/AFVRR/AFVRR_data.mat
new file mode 100644
index 0000000000000000000000000000000000000000..f606b2109e2bf61024b860d13000842c27f3d290
Binary files /dev/null and b/tests/estimation/method_of_moments/AFVRR/AFVRR_data.mat differ
diff --git a/tests/estimation/method_of_moments/AFVRR/AFVRR_steady_helper.m b/tests/estimation/method_of_moments/AFVRR/AFVRR_steady_helper.m
new file mode 100644
index 0000000000000000000000000000000000000000..b8289d48488efd077fcd83461454b319a6f93fc0
--- /dev/null
+++ b/tests/estimation/method_of_moments/AFVRR/AFVRR_steady_helper.m
@@ -0,0 +1,80 @@
+% DSGE model based on replication files of
+% Andreasen, Fernandez-Villaverde, Rubio-Ramirez (2018), The Pruned State-Space System for Non-Linear DSGE Models: Theory and Empirical Applications, Review of Economic Studies, 85, p. 1-49
+% Adapted for Dynare by Willi Mutschler (@wmutschl, willi@mutschler.eu), Jan 2021
+% =========================================================================
+% Copyright (C) 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 <http://www.gnu.org/licenses/>.
+% =========================================================================
+
+% This is a helper function to compute steady state values and endogenous parameters
+% Based on DSGE_model_yieldCurve_ss.m, getPHI3.m, ObjectGMM.m
+
+function [AA, EVFBAR, PHI3, negVf, info]= AFVRR_steady_helper(VFBAR,RBAR,IVBAR,CBAR,KBAR,LABAR,QBAR,YBAR,  BETTA,B,PAI,H,PHIzero,PHI1,PHI2,THETA,MYYPS,MYZ,INHABIT,RRA,CONSxhr40)         
+% We get nice values of EVF by setting AA app. equal to VF. 
+% The value of the expected value function raised to the power 1-PHI3
+% Also we check bounds on other variables
+% % Adding PHI3 to params. Note that PHI3 only affects the value function in
+% % steady state, hence the value we assign to PHI3 is irrelevant
+%     PHI3 = -100;
+
+info=0;
+AA = NaN;
+EVFBAR = NaN;
+PHI3 = NaN;
+negVf = NaN;
+
+MYZSTAR = MYYPS^(THETA/(1-THETA))*MYZ;
+% The wage level
+WBAR      = PHIzero*(1-H)^(-PHI1)/LABAR;
+RRAc   = RRA;
+if INHABIT == 1
+    PHI3 = (RRAc - PHI2/((1-B*MYZSTAR^-1)/(1-BETTA*B)+PHI2/PHI1*WBAR*(1-H)/CBAR))/((1-PHI2)/((1-B*MYZSTAR^-1)/(1-BETTA*B)-(CBAR-B*CBAR*MYZSTAR^-1)^PHI2/((1-BETTA*B)*CBAR)+WBAR*(1-H)/CBAR*(1-PHI2)/(1-PHI1)));
+else    
+    PHI3 = (RRAc - PHI2/(1-B*MYZSTAR^-1+PHI2/PHI1*WBAR*(1-H)/CBAR))/((1-PHI2)/(1-B*MYZSTAR^-1-(CBAR-B*CBAR*MYZSTAR^-1)^PHI2/((1-BETTA*B)*CBAR)+WBAR*(1-H)/CBAR*(1-PHI2)/(1-PHI1)));
+end
+if abs(PHI3) > 30000
+    disp('abs of PHI3 exceeds 30000')
+    info=1;
+    return
+end
+
+if CONSxhr40 > 1
+   info=1;
+   return
+end
+
+
+if VFBAR < 0   
+    AA        = -VFBAR; 
+    EVFBAR    = (-VFBAR/AA)^(1-PHI3);
+    negVf      = 1;    
+else
+    AA        = VFBAR;
+    EVFBAR    = (VFBAR/AA)^(1-PHI3);
+    negVf      = -1;
+    disp('Positive Value Function');
+end
+
+
+if RBAR < 1 || IVBAR < 0 || CBAR < 0 || KBAR < 0 || PAI < 1 || H < 0 || H > 1 || QBAR < 0 || YBAR < 0
+   info = 1;
+end
+
+end
+
+
+
diff --git a/tests/estimation/method_of_moments/AnScho_MoM.mod b/tests/estimation/method_of_moments/AnScho/AnScho_MoM.mod
similarity index 72%
rename from tests/estimation/method_of_moments/AnScho_MoM.mod
rename to tests/estimation/method_of_moments/AnScho/AnScho_MoM.mod
index 2f9c2c24d83991ff411a3d189ac146de41fa9a0b..3d0e718c9e1285de51c194f88a95a28cb3e5dea6 100644
--- a/tests/estimation/method_of_moments/AnScho_MoM.mod
+++ b/tests/estimation/method_of_moments/AnScho/AnScho_MoM.mod
@@ -1,8 +1,8 @@
-% DSGE model used in replication files of 
+% DSGE model used in replication files of
 % An, Sungbae and Schorfheide, Frank, (2007), Bayesian Analysis of DSGE Models, Econometric Reviews, 26, issue 2-4, p. 113-172.
 % Adapted by Willi Mutschler (@wmutschl, willi@mutschler.eu)
 % =========================================================================
-% Copyright (C) 2020 Dynare Team
+% Copyright (C) 2020-2021 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -25,7 +25,7 @@
 @#define estimParams = 1
 
 % Note that we set the numerical optimization tolerance levels very large to speed up the testsuite
-@#define optimizer = 4
+@#define optimizer = 13
 
 var c p R g y z INFL INT YGR;
 varexo e_r e_g e_z;
@@ -203,28 +203,33 @@ end
 
 @#for mommethod in ["GMM", "SMM"]
     method_of_moments(
-        % Necessery options
-          mom_method = @{mommethod}                  % method of moments method; possible values: GMM|SMM
-        , datafile   = 'AnScho_MoM_data_@{orderApp}.mat'         % name of filename with data
+    % Necessery options
+          mom_method = @{mommethod}           % method of moments method; possible values: GMM|SMM
+        , datafile   = 'AnScho_MoM_data_@{orderApp}.mat' % name of filename with data
 
-        % Options for both GMM and SMM
+    % Options for both GMM and SMM
         % , bartlett_kernel_lag = 20          % bandwith in optimal weighting matrix
         , order = @{orderApp}                 % order of Taylor approximation in perturbation
-        % , penalized_estimator               % use penalized optimization
+        % , penalized_estimator               % include deviation from prior mean as additional moment restriction and use prior precision as weight
         , pruning                             % use pruned state space system at higher-order
         % , verbose                           % display and store intermediate estimation results
-        , weighting_matrix = ['optimal']      % weighting matrix in moments distance objective function; possible values: OPTIMAL|IDENTITY_MATRIX|DIAGONAL|filename
-        , additional_optimizer_steps = [4]    % vector of numbers for the iterations in the 2-step feasible method of moments
-        % , prefilter=0                       % demean each data series by its empirical mean and use centered moments
-        % 
-        % Options for SMM
+        , weighting_matrix = ['optimal']      % weighting matrix in moments distance objective function; possible values: OPTIMAL|IDENTITY_MATRIX|DIAGONAL|filename. Size of cell determines stages in iterated estimation, e.g. two state with ['DIAGONAL','OPTIMAL']
+        %, weighting_matrix_scaling_factor=1  % scaling of weighting matrix in objective function
+        , se_tolx=1e-6                        % step size for numerical computation of standard errors
+
+    % Options for SMM
+        % , burnin=500                        % number of periods dropped at beginning of simulation
         % , bounded_shock_support             % trim shocks in simulation to +- 2 stdev
-        % , drop = 500                        % number of periods dropped at beginning of simulation
         % , seed = 24051986                   % seed used in simulations
         % , simulation_multiple = 5           % multiple of the data length used for simulation
-        % 
-        % General options
-        %, dirname = 'MM'                    % directory in which to store estimation output
+
+    % Options for GMM
+        @#if mommethod == "GMM"
+        , analytic_standard_errors            % compute standard errors using analytical derivatives
+        @#endif
+
+    % General options
+        % , dirname = 'MM'                    % directory in which to store estimation output
         % , graph_format = EPS                % specify the file format(s) for graphs saved to disk
         % , nodisplay                         % do not display the graphs, but still save them to disk
         % , nograph                           % do not create graphs (which implies that they are not saved to the disk nor displayed)
@@ -232,41 +237,50 @@ end
         % , plot_priors = 1                   % control plotting of priors
         % , prior_trunc = 1e-10               % probability of extreme values of the prior density that is ignored when computing bounds for the parameters
         % , TeX                               % print TeX tables and graphics
-        % 
-        % Data and model options
-        %, first_obs = 501                     % number of first observation
-        % , logdata                           % if loglinear is set, this option is necessary if the user provides data already in logs, otherwise the log transformation will be applied twice (this may result in complex data)
-        % , loglinear                         % computes a log-linear approximation of the model instead of a linear approximation
-        , nobs = 250                        % number of observations
-        % , xls_sheet = willi                 % name of sheet with data in Excel
+
+    % Data and model options
+        % , first_obs = 501                   % number of first observation
+        % , logdata                           % if data is already in logs
+        , nobs = 250                          % number of observations
+        % , prefilter=0                       % demean each data series by its empirical mean and use centered moments
+
+        % , xls_sheet = data                  % name/number of sheet with data in Excel
         % , xls_range = B2:D200               % range of data in Excel sheet
-        % 
-        % Optimization options that can be set by the user in the mod file, otherwise default values are provided
-        % , analytic_derivation               % uses analytic derivatives to compute standard errors for GMM
-        %, huge_number=1D10                   % value for replacing the infinite bounds on parameters by finite numbers. Used by some optimizers for numerical reasons
-        , mode_compute = @{optimizer}         % specifies the optimizer for minimization of moments distance, note that by default there is a new optimizer
-        %, optim = ('TolFun', 1e-5
-        %           ,'TolX', 1e-6
-        %          )    % a list of NAME and VALUE pairs to set options for the optimization routines. Available options depend on mode_compute
-        %, silent_optimizer                  % run minimization of moments distance silently without displaying results or saving files in between
-        % , tolf = 1e-5                       % convergence criterion on function value for numerical differentiation
-        % , tolx = 1e-6                       % convergence criterion on funciton input for numerical differentiation
-        % 
-        % % Numerical algorithms options
+
+    % Optimization options that can be set by the user in the mod file, otherwise default values are provided
+        % , huge_number=1e7                   % value for replacing the infinite bounds on parameters by finite numbers. Used by some optimizers for numerical reasons
+        , mode_compute = @{optimizer}         % specifies the optimizer for minimization of moments distance
+        , additional_optimizer_steps = [1]    % vector of additional mode-finders run after mode_compute
+        % optim: a list of NAME and VALUE pairs to set options for the optimization routines. Available options depend on mode_compute, some exemplary common options:
+        , optim = ('TolFun'      , 1e-6       % termination tolerance on the function value, a positive scalar
+                  ,'TolX'        , 1e-6       % termination tolerance on x, a positive scalar
+                  ,'MaxIter'     , 3000       % maximum number of iterations allowed, a positive integer
+                  ,'MaxFunEvals' , 1D6        % maximum number of function evaluations allowed, a positive integer
+        %           ,'UseParallel' , 1        % when true (and supported by optimizer) solver estimates gradients in parallel (using Matlab/Octave's parallel toolbox)
+        %           ,'Jacobian'    , 'off'    % when 'off' gradient-based solvers approximate Jacobian using finite differences; for GMM we can also pass the analytical Jacobian to gradient-based solvers by setting this 'on'
+                  )                         
+        , silent_optimizer                    % run minimization of moments distance silently without displaying results or saving files in between
+
+    % Numerical algorithms options
         % , aim_solver                             % Use AIM algorithm to compute perturbation approximation
+        % , k_order_solver                         % use k_order_solver in higher order perturbation approximations
         % , dr=default                             % method used to compute the decision rule; possible values are DEFAULT, CYCLE_REDUCTION, LOGARITHMIC_REDUCTION
         % , dr_cycle_reduction_tol = 1e-7          % convergence criterion used in the cycle reduction algorithm
+        % , dr_logarithmic_reduction_tol = 1e-12   % convergence criterion used in the logarithmic reduction algorithm
         % , dr_logarithmic_reduction_maxiter = 100 % maximum number of iterations used in the logarithmic reduction algorithm
-        % , dr_logarithmic_reduction_tol = 1e-12   % convergence criterion used in the cycle reduction algorithm
-        % , k_order_solver                         % use k_order_solver in higher order perturbation approximations
         % , lyapunov = DEFAULT                     % algorithm used to solve lyapunov equations; possible values are DEFAULT, FIXED_POINT, DOUBLING, SQUARE_ROOT_SOLVER
         % , lyapunov_complex_threshold = 1e-15     % complex block threshold for the upper triangular matrix in symmetric Lyapunov equation solver
         % , lyapunov_fixed_point_tol = 1e-10       % convergence criterion used in the fixed point Lyapunov solver
         % , lyapunov_doubling_tol = 1e-16          % convergence criterion used in the doubling algorithm
         % , sylvester = default                    % algorithm to solve Sylvester equation; possible values are DEFAULT, FIXED_POINT
         % , sylvester_fixed_point_tol = 1e-12      % convergence criterion used in the fixed point Sylvester solver
-        % , qz_criterium = 0.999999                % value used to split stable from unstable eigenvalues in reordering the Generalized Schur decomposition used for solving first order problems [IS THIS CORRET @wmutschl]
+        % , qz_criterium = 0.999999                % value used to split stable from unstable eigenvalues in reordering the Generalized Schur decomposition used for solving first order problems
         % , qz_zero_threshold = 1e-6               % value used to test if a generalized eigenvalue is 0/0 in the generalized Schur decomposition
+        % , schur_vec_tol=1e-11                    % tolerance level used to find nonstationary variables in Schur decomposition of the transition matrix
+        % , mode_check                             % plot the target function for values around the computed minimum for each estimated parameter in turn
+        % , mode_check_neighbourhood_size = 5      % width of the window (expressed in percentage deviation) around the computed minimum to be displayed on the diagnostic plots
+        % , mode_check_symmetric_plots=1           % ensure that the check plots are symmetric around the minimum
+        % , mode_check_number_of_points = 20       % number of points around the minimum where the target function is evaluated (for each parameter)
     );
 @#endfor
 
diff --git a/tests/estimation/method_of_moments/RBC_Andreasen_Data_2.mat b/tests/estimation/method_of_moments/RBC/RBC_Andreasen_Data_2.mat
similarity index 100%
rename from tests/estimation/method_of_moments/RBC_Andreasen_Data_2.mat
rename to tests/estimation/method_of_moments/RBC/RBC_Andreasen_Data_2.mat
diff --git a/tests/estimation/method_of_moments/RBC/RBC_MoM_Andreasen.mod b/tests/estimation/method_of_moments/RBC/RBC_MoM_Andreasen.mod
new file mode 100644
index 0000000000000000000000000000000000000000..b9191a1f7dd7af6070570855915edfc2f65b8b0b
--- /dev/null
+++ b/tests/estimation/method_of_moments/RBC/RBC_MoM_Andreasen.mod
@@ -0,0 +1,230 @@
+% Tests SMM and GMM routines
+%
+% Copyright (C) 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 <http://www.gnu.org/licenses/>.
+% =========================================================================
+
+% Define testscenario
+@#define orderApp = 2
+@#define estimParams = 1
+
+% Note that we will set the numerical optimization tolerance levels very large to speed up the testsuite
+@#define optimizer = 13
+
+
+@#include "RBC_MoM_common.inc"
+
+shocks;
+var u_a; stderr 0.0072;        
+end;
+
+varobs c iv n;
+
+
+@#if estimParams == 0
+estimated_params;
+    DELTA,         0.025;
+    BETTA,         0.984;
+    B,             0.5;
+    ETAc,          2;
+    ALFA,          0.667;
+    RHOA,          0.979;
+    stderr u_a,    0.0072;
+end;
+@#endif
+
+@#if estimParams == 1
+estimated_params;
+    DELTA,         ,        0,           1;
+    BETTA,         ,        0,           1;
+    B,             ,        0,           1;
+    ETAc,          ,        0,           10;
+    ALFA,          ,        0,           1;
+    RHOA,          ,        0,           1;
+    stderr u_a,    ,        0,           1;
+end;
+@#endif
+
+@#if estimParams == 2
+estimated_params;
+    DELTA,         0.025,         0,           1,  normal_pdf, 0.02, 0.5;
+    BETTA,         0.98,         0,           1,  beta_pdf, 0.90, 0.25;
+    B,             0.45,         0,           1,  normal_pdf, 0.40, 0.5;
+    %ETAl,          1,            0,           10, normal_pdf, 0.25, 0.0.1;
+    ETAc,          1.8,         0,           10, normal_pdf, 1.80, 0.5;
+    ALFA,          0.65,         0,           1,  normal_pdf, 0.60, 0.5;
+    RHOA,          0.95,         0,           1,  normal_pdf, 0.90, 0.5;
+    stderr u_a,    0.01,         0,           1,  normal_pdf, 0.01, 0.5;
+    %THETA,         3.48,          0,           10, normal_pdf, 0.25, 0.0.1;
+end;
+@#endif
+
+% Simulate data
+%stoch_simul(order=@{orderApp},pruning,nodisplay,nomoments,periods=500);
+%save('RBC_MoM_data_@{orderApp}.mat', options_.varobs{:} );
+%pause(1);
+
+
+estimated_params_init(use_calibration);
+end;
+
+
+%--------------------------------------------------------------------------
+% Method of Moments Estimation
+%--------------------------------------------------------------------------
+matched_moments;
+c;
+n;
+iv;
+c*c;
+c*iv;
+iv*n;
+iv*iv;
+n*c;
+n*n;
+c*c(-1);
+n*n(-1);
+iv*iv(-1);
+
+c*c(-3);
+n*n(-3);
+iv*iv(-3);
+
+c*c(-5);
+n*n(-5);
+iv*iv(-5);
+end;
+
+% get indices in declaration order
+ic  = strmatch('c',  M_.endo_names,'exact');
+iiv = strmatch('iv', M_.endo_names,'exact');
+in  = strmatch('n',  M_.endo_names,'exact');
+% first entry: number of variable in declaration order
+% second entry: lag
+% third entry: power
+
+matched_moments_ = {
+    [ic     ]  [0   ],  [1  ];
+    [in     ]  [0   ],  [1  ];    
+    [iiv    ]  [0   ],  [1  ];
+    
+    [ic  ic ]  [0  0],  [1 1];
+    [ic  iiv]  [0  0],  [1 1];
+    %[ic  in ]  [0  0],  [1 1];
+    %[iiv ic ]  [0  0],  [1 1];
+    [in iiv]  [0  0],  [1 1];
+    [iiv iiv]  [0  0],  [1 1];    
+    [ic  in]  [0  0],  [1 1];
+    %[in  iiv]  [0  0],  [1 1];
+    [in  in ]  [0  0],  [1 1];
+    
+    [ic  ic ]  [0 -1],  [1 1];
+    [in  in ]  [0 -1],  [1 1];
+    [iiv iiv]  [0 -1],  [1 1];
+
+    [ic  ic ]  [0 -3],  [1 1];
+    [in  in ]  [0 -3],  [1 1];
+    [iiv iiv]  [0 -3],  [1 1];
+
+    [ic  ic ]  [0 -5],  [1 1];
+    [in  in ]  [0 -5],  [1 1];
+    [iiv iiv]  [0 -5],  [1 1];
+
+};
+
+if ~isequal(M_.matched_moments,matched_moments_)
+    error('Translation to matched_moments-block failed')
+end
+
+
+method_of_moments(
+    % Necessery options
+          mom_method = GMM                   % method of moments method; possible values: GMM|SMM
+        , datafile   = 'RBC_Andreasen_Data_2.mat' % name of filename with data
+
+    % Options for both GMM and SMM
+        % , bartlett_kernel_lag = 20          % bandwith in optimal weighting matrix
+        , order = @{orderApp}                 % order of Taylor approximation in perturbation
+        % , penalized_estimator               % include deviation from prior mean as additional moment restriction and use prior precision as weight
+        % , pruning                           % use pruned state space system at higher-order
+        % , verbose                           % display and store intermediate estimation results
+        , weighting_matrix = ['DIAGONAL','OPTIMAL'] % weighting matrix in moments distance objective function; possible values: OPTIMAL|IDENTITY_MATRIX|DIAGONAL|filename. Size of cell determines stages in iterated estimation, e.g. two state with ['DIAGONAL','OPTIMAL']
+        % , weighting_matrix_scaling_factor=1 % scaling of weighting matrix in objective function
+        , se_tolx=1e-6                        % step size for numerical computation of standard errors
+
+    % Options for SMM
+        % , burnin=500                        % number of periods dropped at beginning of simulation
+        % , bounded_shock_support             % trim shocks in simulation to +- 2 stdev
+        % , seed = 24051986                   % seed used in simulations
+        % , simulation_multiple = 5           % multiple of the data length used for simulation
+
+    % Options for GMM        
+        % , analytic_standard_errors          % compute standard errors using analytical derivatives
+
+    % General options
+        % , dirname = 'MM'                    % directory in which to store estimation output
+        % , graph_format = EPS                % specify the file format(s) for graphs saved to disk
+        % , nodisplay                         % do not display the graphs, but still save them to disk
+        % , nograph                           % do not create graphs (which implies that they are not saved to the disk nor displayed)
+        % , noprint                           % do not print stuff to console
+        % , plot_priors = 1                   % control plotting of priors
+        % , prior_trunc = 1e-10               % probability of extreme values of the prior density that is ignored when computing bounds for the parameters
+        , TeX                                 % print TeX tables and graphics
+
+    % Data and model options
+        % , first_obs = 501                   % number of first observation
+        % , logdata                           % if data is already in logs
+        % , nobs = 250                        % number of observations
+        % , prefilter=0                       % demean each data series by its empirical mean and use centered moments
+        % , xls_sheet = data                  % name/number of sheet with data in Excel
+        % , xls_range = B2:D200               % range of data in Excel sheet
+
+    % Optimization options that can be set by the user in the mod file, otherwise default values are provided
+        % , huge_number=1e7                   % value for replacing the infinite bounds on parameters by finite numbers. Used by some optimizers for numerical reasons
+        , mode_compute = 3                    % specifies the optimizer for minimization of moments distance
+        , additional_optimizer_steps = [13]   % vector of additional mode-finders run after mode_compute
+        % optim: a list of NAME and VALUE pairs to set options for the optimization routines. Available options depend on mode_compute, some exemplary common options:
+        , optim = ('TolFun'      , 1D-6       % termination tolerance on the function value, a positive scalar
+                  ,'TolX'        , 1e-6       % termination tolerance on x, a positive scalar
+        %           ,'MaxIter'     , 3000     % maximum number of iterations allowed, a positive integer
+        %           ,'MaxFunEvals' , 1D6      % maximum number of function evaluations allowed, a positive integer
+        %           ,'UseParallel' , 1        % when true (and supported by optimizer) solver estimates gradients in parallel (using Matlab/Octave's parallel toolbox)
+        %           ,'Jacobian'    , 'off'    % when 'off' gradient-based solvers approximate Jacobian using finite differences; for GMM we can also pass the analytical Jacobian to gradient-based solvers by setting this 'on'
+                  )                         
+        % , silent_optimizer                  % run minimization of moments distance silently without displaying results or saving files in between
+
+    % Numerical algorithms options
+        % , aim_solver                             % Use AIM algorithm to compute perturbation approximation
+        % , k_order_solver                         % use k_order_solver in higher order perturbation approximations
+        % , dr=default                             % method used to compute the decision rule; possible values are DEFAULT, CYCLE_REDUCTION, LOGARITHMIC_REDUCTION
+        % , dr_cycle_reduction_tol = 1e-7          % convergence criterion used in the cycle reduction algorithm
+        % , dr_logarithmic_reduction_tol = 1e-12   % convergence criterion used in the logarithmic reduction algorithm
+        % , dr_logarithmic_reduction_maxiter = 100 % maximum number of iterations used in the logarithmic reduction algorithm
+        % , lyapunov = DEFAULT                     % algorithm used to solve lyapunov equations; possible values are DEFAULT, FIXED_POINT, DOUBLING, SQUARE_ROOT_SOLVER
+        % , lyapunov_complex_threshold = 1e-15     % complex block threshold for the upper triangular matrix in symmetric Lyapunov equation solver
+        % , lyapunov_fixed_point_tol = 1e-10       % convergence criterion used in the fixed point Lyapunov solver
+        % , lyapunov_doubling_tol = 1e-16          % convergence criterion used in the doubling algorithm
+        % , sylvester = default                    % algorithm to solve Sylvester equation; possible values are DEFAULT, FIXED_POINT
+        % , sylvester_fixed_point_tol = 1e-12      % convergence criterion used in the fixed point Sylvester solver
+        % , qz_criterium = 0.999999                % value used to split stable from unstable eigenvalues in reordering the Generalized Schur decomposition used for solving first order problems
+        % , qz_zero_threshold = 1e-6               % value used to test if a generalized eigenvalue is 0/0 in the generalized Schur decomposition
+        % , schur_vec_tol=1e-11                    % tolerance level used to find nonstationary variables in Schur decomposition of the transition matrix
+        , mode_check                               % plot the target function for values around the computed minimum for each estimated parameter in turn
+        % , mode_check_neighbourhood_size = 5      % width of the window (expressed in percentage deviation) around the computed minimum to be displayed on the diagnostic plots
+        % , mode_check_symmetric_plots=1           % ensure that the check plots are symmetric around the minimum
+        % , mode_check_number_of_points = 20       % number of points around the minimum where the target function is evaluated (for each parameter)
+    );
\ No newline at end of file
diff --git a/tests/estimation/method_of_moments/RBC_MoM_SMM_ME.mod b/tests/estimation/method_of_moments/RBC/RBC_MoM_SMM_ME.mod
similarity index 65%
rename from tests/estimation/method_of_moments/RBC_MoM_SMM_ME.mod
rename to tests/estimation/method_of_moments/RBC/RBC_MoM_SMM_ME.mod
index 9648626709d0413dec27ceec9d09232a6b2da556..b407cd28a515c8027d586ed46f9d00fd522ff2e9 100644
--- a/tests/estimation/method_of_moments/RBC_MoM_SMM_ME.mod
+++ b/tests/estimation/method_of_moments/RBC/RBC_MoM_SMM_ME.mod
@@ -1,3 +1,5 @@
+% =========================================================================
+% Copyright (C) 2020-2021 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -137,30 +139,31 @@ end
 
 @#for mommethod in ["SMM"]
     method_of_moments(
-        % Necessery options
-          mom_method = @{mommethod}                  % method of moments method; possible values: GMM|SMM
-        , datafile   = 'RBC_MoM_data_@{orderApp}.mat'         % name of filename with data
+    % Necessery options
+          mom_method = @{mommethod}           % method of moments method; possible values: GMM|SMM
+        , datafile   = 'RBC_MoM_data_@{orderApp}.mat' % name of filename with data
 
-        % Options for both GMM and SMM
+    % Options for both GMM and SMM
         % , bartlett_kernel_lag = 20          % bandwith in optimal weighting matrix
         , order = @{orderApp}                 % order of Taylor approximation in perturbation
-        % , penalized_estimator               % use penalized optimization
+        % , penalized_estimator               % include deviation from prior mean as additional moment restriction and use prior precision as weight
         , pruning                             % use pruned state space system at higher-order
         % , verbose                           % display and store intermediate estimation results
-        , weighting_matrix = ['identity_matrix']      % weighting matrix in moments distance objective function; possible values: OPTIMAL|IDENTITY_MATRIX|DIAGONAL|filename
-        , weighting_matrix_scaling_factor = 10
-        , burnin=250
-        %, additional_optimizer_steps = [4]    % vector of additional mode-finders run after mode_compute
-        % , prefilter=0                       % demean each data series by its empirical mean and use centered moments
-        % 
-        % Options for SMM
+        , weighting_matrix = ['identity_matrix'] % weighting matrix in moments distance objective function; possible values: OPTIMAL|IDENTITY_MATRIX|DIAGONAL|filename. Size of cell determines stages in iterated estimation, e.g. two state with ['DIAGONAL','OPTIMAL']
+        , weighting_matrix_scaling_factor=10  % scaling of weighting matrix in objective function
+        % , se_tolx=1e-6                      % step size for numerical computation of standard errors
+
+    % Options for SMM
+        , burnin=250                          % number of periods dropped at beginning of simulation
         % , bounded_shock_support             % trim shocks in simulation to +- 2 stdev
-        % , drop = 500                        % number of periods dropped at beginning of simulation
         % , seed = 24051986                   % seed used in simulations
         % , simulation_multiple = 5           % multiple of the data length used for simulation
-        % 
-        % General options
-        %, dirname = 'MM'                    % directory in which to store estimation output
+
+    % Options for GMM
+        % , analytic_standard_errors          % compute standard errors using analytical derivatives
+
+    % General options
+        % , dirname = 'MM'                    % directory in which to store estimation output
         % , graph_format = EPS                % specify the file format(s) for graphs saved to disk
         % , nodisplay                         % do not display the graphs, but still save them to disk
         % , nograph                           % do not create graphs (which implies that they are not saved to the disk nor displayed)
@@ -168,41 +171,49 @@ end
         % , plot_priors = 1                   % control plotting of priors
         % , prior_trunc = 1e-10               % probability of extreme values of the prior density that is ignored when computing bounds for the parameters
         % , TeX                               % print TeX tables and graphics
-        % 
-        % Data and model options
-        %, first_obs = 501                     % number of first observation
-        % , logdata                           % if loglinear is set, this option is necessary if the user provides data already in logs, otherwise the log transformation will be applied twice (this may result in complex data)
-        % , loglinear                         % computes a log-linear approximation of the model instead of a linear approximation
-        %, nobs = 500                        % number of observations
-        % , xls_sheet = willi                 % name of sheet with data in Excel
+
+    % Data and model options
+        % , first_obs = 501                   % number of first observation
+        % , logdata                           % if data is already in logs
+        % , nobs = 250                        % number of observations
+        % , prefilter=0                       % demean each data series by its empirical mean and use centered moments
+        % , xls_sheet = data                  % name/number of sheet with data in Excel
         % , xls_range = B2:D200               % range of data in Excel sheet
-        % 
-        % Optimization options that can be set by the user in the mod file, otherwise default values are provided
-        % , analytic_derivation               % uses analytic derivatives to compute standard errors for GMM
-        %, huge_number=1D10                   % value for replacing the infinite bounds on parameters by finite numbers. Used by some optimizers for numerical reasons
-        , mode_compute = @{optimizer}         % specifies the optimizer for minimization of moments distance, note that by default there is a new optimizer
-        %, optim = ('TolFun', 1e-3
-        %           ,'TolX', 1e-5
-        %          )    % a list of NAME and VALUE pairs to set options for the optimization routines. Available options depend on mode_compute
-        %, silent_optimizer                  % run minimization of moments distance silently without displaying results or saving files in between
-        % , tolf = 1e-5                       % convergence criterion on function value for numerical differentiation
-        % , tolx = 1e-6                       % convergence criterion on funciton input for numerical differentiation
-        % 
-        % % Numerical algorithms options
+
+    % Optimization options that can be set by the user in the mod file, otherwise default values are provided
+        % , huge_number=1e7                   % value for replacing the infinite bounds on parameters by finite numbers. Used by some optimizers for numerical reasons
+        , mode_compute = @{optimizer}         % specifies the optimizer for minimization of moments distance
+        %, additional_optimizer_steps = [1 2 3 4]    % vector of additional mode-finders run after mode_compute
+        % optim: a list of NAME and VALUE pairs to set options for the optimization routines. Available options depend on mode_compute, some exemplary common options:
+        % , optim = ('TolFun'      , 1e-6     % termination tolerance on the function value, a positive scalar
+        %           ,'TolX'        , 1e-6     % termination tolerance on x, a positive scalar
+        %           ,'MaxIter'     , 3000     % maximum number of iterations allowed, a positive integer
+        %           ,'MaxFunEvals' , 1D6      % maximum number of function evaluations allowed, a positive integer
+        %           ,'UseParallel' , 1        % when true (and supported by optimizer) solver estimates gradients in parallel (using Matlab/Octave's parallel toolbox)
+        %           ,'Jacobian'    , 'off'    % when 'off' gradient-based solvers approximate Jacobian using finite differences; for GMM we can also pass the analytical Jacobian to gradient-based solvers by setting this 'on'
+        %           )                         
+        % , silent_optimizer                  % run minimization of moments distance silently without displaying results or saving files in between
+
+    % Numerical algorithms options
         % , aim_solver                             % Use AIM algorithm to compute perturbation approximation
+        % , k_order_solver                         % use k_order_solver in higher order perturbation approximations
         % , dr=default                             % method used to compute the decision rule; possible values are DEFAULT, CYCLE_REDUCTION, LOGARITHMIC_REDUCTION
         % , dr_cycle_reduction_tol = 1e-7          % convergence criterion used in the cycle reduction algorithm
+        % , dr_logarithmic_reduction_tol = 1e-12   % convergence criterion used in the logarithmic reduction algorithm
         % , dr_logarithmic_reduction_maxiter = 100 % maximum number of iterations used in the logarithmic reduction algorithm
-        % , dr_logarithmic_reduction_tol = 1e-12   % convergence criterion used in the cycle reduction algorithm
-        % , k_order_solver                         % use k_order_solver in higher order perturbation approximations
         % , lyapunov = DEFAULT                     % algorithm used to solve lyapunov equations; possible values are DEFAULT, FIXED_POINT, DOUBLING, SQUARE_ROOT_SOLVER
         % , lyapunov_complex_threshold = 1e-15     % complex block threshold for the upper triangular matrix in symmetric Lyapunov equation solver
         % , lyapunov_fixed_point_tol = 1e-10       % convergence criterion used in the fixed point Lyapunov solver
         % , lyapunov_doubling_tol = 1e-16          % convergence criterion used in the doubling algorithm
         % , sylvester = default                    % algorithm to solve Sylvester equation; possible values are DEFAULT, FIXED_POINT
         % , sylvester_fixed_point_tol = 1e-12      % convergence criterion used in the fixed point Sylvester solver
-        % , qz_criterium = 0.999999                % value used to split stable from unstable eigenvalues in reordering the Generalized Schur decomposition used for solving first order problems [IS THIS CORRET @wmutschl]
+        % , qz_criterium = 0.999999                % value used to split stable from unstable eigenvalues in reordering the Generalized Schur decomposition used for solving first order problems
         % , qz_zero_threshold = 1e-6               % value used to test if a generalized eigenvalue is 0/0 in the generalized Schur decomposition
+        % , schur_vec_tol=1e-11                    % tolerance level used to find nonstationary variables in Schur decomposition of the transition matrix
+        % , mode_check                             % plot the target function for values around the computed minimum for each estimated parameter in turn
+        % , mode_check_neighbourhood_size = 5      % width of the window (expressed in percentage deviation) around the computed minimum to be displayed on the diagnostic plots
+        % , mode_check_symmetric_plots=1           % ensure that the check plots are symmetric around the minimum
+        % , mode_check_number_of_points = 20       % number of points around the minimum where the target function is evaluated (for each parameter)
     );
 @#endfor
 
diff --git a/tests/estimation/method_of_moments/RBC_MoM_common.inc b/tests/estimation/method_of_moments/RBC/RBC_MoM_common.inc
similarity index 71%
rename from tests/estimation/method_of_moments/RBC_MoM_common.inc
rename to tests/estimation/method_of_moments/RBC/RBC_MoM_common.inc
index d480e35c06253961f95edf3d597a61ef44bd14c8..330dd2fcf0d026c9f9bc1653d699d18b32885b16 100644
--- a/tests/estimation/method_of_moments/RBC_MoM_common.inc
+++ b/tests/estimation/method_of_moments/RBC/RBC_MoM_common.inc
@@ -2,7 +2,23 @@
 % Andreasen, Fernández-Villaverde, Rubio-Ramírez (2018): "The Pruned State-Space System for Non-Linear DSGE Models: Theory and Empirical Applications", Review of Economic Studies, 85(1):1-49.
 % Adapted by Willi Mutschler (@wmutschl, willi@mutschler.eu)
 % =========================================================================
-% Copyright (C) 2020 Dynare Team
+% Copyright (C) 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 <http://www.gnu.org/licenses/>.
+% =========================================================================
 
 var k   $K$
     c   $C$
diff --git a/tests/estimation/method_of_moments/RBC/RBC_MoM_optimizer.mod b/tests/estimation/method_of_moments/RBC/RBC_MoM_optimizer.mod
new file mode 100644
index 0000000000000000000000000000000000000000..08b1ed882fabf4ec1bea83047d394e736400ca63
--- /dev/null
+++ b/tests/estimation/method_of_moments/RBC/RBC_MoM_optimizer.mod
@@ -0,0 +1,146 @@
+% Test optimizers
+%
+% Copyright (C) 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 <http://www.gnu.org/licenses/>.
+% =========================================================================
+% TO DO
+% [ ] fix optimizers 11 and 12; 
+% note that 12 and 102 require GADS_Toolbox which is not available on servers, but need to be tested locally
+
+% Define testscenario
+@#define orderApp = 2
+
+% Note that we will set the numerical optimization tolerance levels very large to speed up the testsuite
+
+@#include "RBC_MoM_common.inc"
+
+shocks;
+var u_a; stderr 0.0072;        
+end;
+
+varobs c iv n;
+
+%--------------------------------------------------------------------------
+% Method of Moments Estimation
+%--------------------------------------------------------------------------
+matched_moments;
+c;
+n;
+iv;
+c*c;
+c*iv;
+iv*n;
+iv*iv;
+n*c;
+n*n;
+c*c(-1);
+n*n(-1);
+iv*iv(-1);
+end;
+
+% reduce options to speed up testsuite
+options_.newrat.maxiter = 10;
+options_.newrat.tolerance.f = 1e-2;
+options_.newrat.tolerance.f_analytic = 1e-2;
+
+options_.mh_jscale = 0.6;
+options_.gmhmaxlik.iterations=1;
+options_.gmhmaxlik.number=2000;
+options_.gmhmaxlik.nclimb=2000;
+options_.gmhmaxlik.nscale=2000;
+options_.gmhmaxlik.target=0.5;
+
+options_.solveopt.MaxIter=300;
+options_.solveopt.LBGradientStep=1e-3;
+options_.solveopt.TolFun = 1e-3;
+options_.solveopt.TolX = 1e-3;
+options_.solveopt.TolXConstraint=1e-3;
+
+
+@#for estimParams in [0, 1, 2]
+  clear estim_params_;
+  @#if estimParams == 0
+    estimated_params;
+        %DELTA,         0.025;
+        %BETTA,         0.984;
+        %B,             0.5;
+        %ETAc,          2;
+        ALFA,          0.667;
+        RHOA,          0.979;
+        stderr u_a,    0.0072;
+    end;
+  @#define OPTIMIZERS = [1, 2, 3, 4, 5, 7, 8, 9, 10, 13, 101]
+  @#endif
+
+  @#if estimParams == 1
+    estimated_params;
+        %DELTA,         ,        0,           1;
+        %BETTA,         ,        0,           1;
+        %B,             ,        0,           1;
+        %ETAc,          ,        0,           10;
+        ALFA,          ,        0,           1;
+        RHOA,          ,        0,           1;
+        stderr u_a,    ,        0,           1;
+    end;
+  @#define OPTIMIZERS = [1, 2, 3, 4, 7, 8, 9, 10, 13, 101]
+  @#endif
+
+  @#if estimParams == 2
+    estimated_params;
+        %DELTA,         0.025,         0,           1,  normal_pdf, 0.02, 0.5;
+        %BETTA,         0.98,         0,           1,  beta_pdf, 0.90, 0.25;
+        %B,             0.45,         0,           1,  normal_pdf, 0.40, 0.5;
+        %ETAl,          1,            0,           10, normal_pdf, 0.25, 0.0.1;
+        %ETAc,          1.8,         0,           10, normal_pdf, 1.80, 0.5;
+        ALFA,          0.65,         0,           1,  normal_pdf, 0.60, 0.5;
+        RHOA,          0.95,         0,           1,  normal_pdf, 0.90, 0.5;
+        stderr u_a,    0.01,         0,           1,  normal_pdf, 0.01, 0.5;
+        %THETA,         3.48,          0,           10, normal_pdf, 0.25, 0.0.1;
+    end;
+  @#define OPTIMIZERS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 101]
+  @#endif
+
+    estimated_params_init(use_calibration);
+    end;
+
+    @#for optimizer in OPTIMIZERS
+    method_of_moments(
+          mom_method = GMM         % method of moments method; possible values: GMM|SMM
+        , datafile   = 'RBC_Andreasen_Data_2.mat' % name of filename with data
+        , order = @{orderApp}                 % order of Taylor approximation in perturbation
+        , weighting_matrix = ['OPTIMAL']      % weighting matrix in moments distance objective function; possible values: OPTIMAL|IDENTITY_MATRIX|DIAGONAL|filename. Size of cell determines stages in iterated estimation, e.g. two state with ['DIAGONAL','OPTIMAL']
+        , nograph                           % do not create graphs (which implies that they are not saved to the disk nor displayed)
+        , mode_compute = @{optimizer}        % specifies the optimizer for minimization of moments distance
+        @#if optimizer == 102
+        , optim = ('TolFun'      , 1D-3       % termination tolerance on the function value, a positive scalar
+                  ,'MaxIter'     , 300        % maximum number of iterations allowed, a positive integer
+                  ,'MaxFunEvals' , 1D3        % maximum number of function evaluations allowed, a positive integer
+                  )
+        @#else
+        , optim = ('TolFun'      , 1D-3       % termination tolerance on the function value, a positive scalar
+                  ,'TolX'        , 1e-3       % termination tolerance on x, a positive scalar
+                  ,'MaxIter'     , 300        % maximum number of iterations allowed, a positive integer
+                  ,'MaxFunEvals' , 1D3        % maximum number of function evaluations allowed, a positive integer
+                  )
+        @#endif
+        %, silent_optimizer                  % run minimization of moments distance silently without displaying results or saving files in between
+    );
+    @#endfor
+@#endfor
+
+
+
diff --git a/tests/estimation/method_of_moments/RBC_MoM_prefilter.mod b/tests/estimation/method_of_moments/RBC/RBC_MoM_prefilter.mod
similarity index 61%
rename from tests/estimation/method_of_moments/RBC_MoM_prefilter.mod
rename to tests/estimation/method_of_moments/RBC/RBC_MoM_prefilter.mod
index 7fb29f8abfb19ef53e9e6dbc90343b9843705308..326badcd585f01fc16ca0040655cf21aaa85b2c2 100644
--- a/tests/estimation/method_of_moments/RBC_MoM_prefilter.mod
+++ b/tests/estimation/method_of_moments/RBC/RBC_MoM_prefilter.mod
@@ -1,6 +1,6 @@
 % Tests SMM and GMM routines with prefilter, explicit initialization, and estimated_params_init(use_calibration);
 %
-% Copyright (C) 2020 Dynare Team
+% Copyright (C) 2020-2021 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -110,31 +110,31 @@ save('test_matrix.mat','weighting_matrix')
 
 @#for mommethod in ["GMM", "SMM"]
     method_of_moments(
-        % Necessery options
-          mom_method = @{mommethod}                  % method of moments method; possible values: GMM|SMM
-        , datafile   = 'RBC_MoM_data_@{orderApp}.mat'         % name of filename with data
+    % Necessery options
+          mom_method = @{mommethod}           % method of moments method; possible values: GMM|SMM
+        , datafile   = 'RBC_MoM_data_@{orderApp}.mat' % name of filename with data
 
-        % Options for both GMM and SMM
+    % Options for both GMM and SMM
         % , bartlett_kernel_lag = 20          % bandwith in optimal weighting matrix
         , order = @{orderApp}                 % order of Taylor approximation in perturbation
-        % , penalized_estimator               % use penalized optimization
+        % , penalized_estimator               % include deviation from prior mean as additional moment restriction and use prior precision as weight
         , pruning                             % use pruned state space system at higher-order
         % , verbose                           % display and store intermediate estimation results
-%         , weighting_matrix = 'test_matrix.mat' % weighting matrix in moments distance objective function; possible values: OPTIMAL|IDENTITY_MATRIX|DIAGONAL|filename
-        , weighting_matrix =['test_matrix.mat','optimal']
-        %, weighting_matrix = optimal            % weighting matrix in moments distance objective function; possible values: OPTIMAL|IDENTITY_MATRIX|DIAGONAL|filename
-        %, additional_optimizer_steps = [4]    % vector of additional mode-finders run after mode_compute
-        , prefilter=1                       % demean each data series by its empirical mean and use centered moments
-        , se_tolx=1e-5
-        % 
-        % Options for SMM
+        , weighting_matrix = ['test_matrix.mat','optimal'] % weighting matrix in moments distance objective function; possible values: OPTIMAL|IDENTITY_MATRIX|DIAGONAL|filename. Size of cell determines stages in iterated estimation, e.g. two state with ['DIAGONAL','OPTIMAL']
+        %, weighting_matrix_scaling_factor=1  % scaling of weighting matrix in objective function
+        , se_tolx=1e-5                        % step size for numerical computation of standard errors
+
+    % Options for SMM
+        , burnin=500                          % number of periods dropped at beginning of simulation
         % , bounded_shock_support             % trim shocks in simulation to +- 2 stdev
-        , burnin = 500                      % number of periods dropped at beginning of simulation
         % , seed = 24051986                   % seed used in simulations
         % , simulation_multiple = 5           % multiple of the data length used for simulation
-        % 
-        % General options
-        %, dirname = 'MM'                    % directory in which to store estimation output
+
+    % Options for GMM        
+        % , analytic_standard_errors            % compute standard errors using analytical derivatives        
+
+    % General options
+        % , dirname = 'MM'                    % directory in which to store estimation output
         % , graph_format = EPS                % specify the file format(s) for graphs saved to disk
         % , nodisplay                         % do not display the graphs, but still save them to disk
         % , nograph                           % do not create graphs (which implies that they are not saved to the disk nor displayed)
@@ -142,38 +142,49 @@ save('test_matrix.mat','weighting_matrix')
         % , plot_priors = 1                   % control plotting of priors
         % , prior_trunc = 1e-10               % probability of extreme values of the prior density that is ignored when computing bounds for the parameters
         % , TeX                               % print TeX tables and graphics
-        % 
-        % Data and model options
-        %, first_obs = 501                     % number of first observation
-        % , logdata                           % if loglinear is set, this option is necessary if the user provides data already in logs, otherwise the log transformation will be applied twice (this may result in complex data)
-        % , loglinear                         % computes a log-linear approximation of the model instead of a linear approximation
-        %, nobs = 500                        % number of observations
-        % , xls_sheet = willi                 % name of sheet with data in Excel
+
+    % Data and model options
+        % , first_obs = 501                   % number of first observation
+        % , logdata                           % if data is already in logs
+        , nobs = 250                          % number of observations
+        , prefilter=1                         % demean each data series by its empirical mean and use centered moments
+
+        % , xls_sheet = data                  % name/number of sheet with data in Excel
         % , xls_range = B2:D200               % range of data in Excel sheet
-        % 
-        % Optimization options that can be set by the user in the mod file, otherwise default values are provided
-        % , analytic_derivation               % uses analytic derivatives to compute standard errors for GMM
-        %, huge_number=1D10                   % value for replacing the infinite bounds on parameters by finite numbers. Used by some optimizers for numerical reasons
-        , mode_compute = @{optimizer}         % specifies the optimizer for minimization of moments distance, note that by default there is a new optimizer
-        %, optim = ('TolFun', 1e-3
-        %           ,'TolX', 1e-5
-        %          )    % a list of NAME and VALUE pairs to set options for the optimization routines. Available options depend on mode_compute
-        %, silent_optimizer                  % run minimization of moments distance silently without displaying results or saving files in between
-        % 
-        % % Numerical algorithms options
+
+    % Optimization options that can be set by the user in the mod file, otherwise default values are provided
+        % , huge_number=1e7                   % value for replacing the infinite bounds on parameters by finite numbers. Used by some optimizers for numerical reasons
+        , mode_compute = @{optimizer}         % specifies the optimizer for minimization of moments distance
+        %, additional_optimizer_steps = [7]  % vector of additional mode-finders run after mode_compute
+        % optim: a list of NAME and VALUE pairs to set options for the optimization routines. Available options depend on mode_compute, some exemplary common options:
+        % , optim = ('TolFun'      , 1e-6     % termination tolerance on the function value, a positive scalar
+        %           ,'TolX'        , 1e-6     % termination tolerance on x, a positive scalar
+        %           ,'MaxIter'     , 3000     % maximum number of iterations allowed, a positive integer
+        %           ,'MaxFunEvals' , 1D6      % maximum number of function evaluations allowed, a positive integer
+        %           ,'UseParallel' , 1        % when true (and supported by optimizer) solver estimates gradients in parallel (using Matlab/Octave's parallel toolbox)
+        %           ,'Jacobian'    , 'off'    % when 'off' gradient-based solvers approximate Jacobian using finite differences; for GMM we can also pass the analytical Jacobian to gradient-based solvers by setting this 'on'
+        %           )                         
+        % , silent_optimizer                  % run minimization of moments distance silently without displaying results or saving files in between
+
+    % Numerical algorithms options
         % , aim_solver                             % Use AIM algorithm to compute perturbation approximation
+        % , k_order_solver                         % use k_order_solver in higher order perturbation approximations
         % , dr=default                             % method used to compute the decision rule; possible values are DEFAULT, CYCLE_REDUCTION, LOGARITHMIC_REDUCTION
         % , dr_cycle_reduction_tol = 1e-7          % convergence criterion used in the cycle reduction algorithm
+        % , dr_logarithmic_reduction_tol = 1e-12   % convergence criterion used in the logarithmic reduction algorithm
         % , dr_logarithmic_reduction_maxiter = 100 % maximum number of iterations used in the logarithmic reduction algorithm
-        % , dr_logarithmic_reduction_tol = 1e-12   % convergence criterion used in the cycle reduction algorithm
-        % , k_order_solver                         % use k_order_solver in higher order perturbation approximations
         % , lyapunov = DEFAULT                     % algorithm used to solve lyapunov equations; possible values are DEFAULT, FIXED_POINT, DOUBLING, SQUARE_ROOT_SOLVER
         % , lyapunov_complex_threshold = 1e-15     % complex block threshold for the upper triangular matrix in symmetric Lyapunov equation solver
         % , lyapunov_fixed_point_tol = 1e-10       % convergence criterion used in the fixed point Lyapunov solver
         % , lyapunov_doubling_tol = 1e-16          % convergence criterion used in the doubling algorithm
         % , sylvester = default                    % algorithm to solve Sylvester equation; possible values are DEFAULT, FIXED_POINT
         % , sylvester_fixed_point_tol = 1e-12      % convergence criterion used in the fixed point Sylvester solver
-        % , qz_criterium = 0.999999                % value used to split stable from unstable eigenvalues in reordering the Generalized Schur decomposition used for solving first order problems [IS THIS CORRET @wmutschl]
+        % , qz_criterium = 0.999999                % value used to split stable from unstable eigenvalues in reordering the Generalized Schur decomposition used for solving first order problems
         % , qz_zero_threshold = 1e-6               % value used to test if a generalized eigenvalue is 0/0 in the generalized Schur decomposition
+        % , schur_vec_tol=1e-11                    % tolerance level used to find nonstationary variables in Schur decomposition of the transition matrix
+        % , mode_check                             % plot the target function for values around the computed minimum for each estimated parameter in turn
+        % , mode_check_neighbourhood_size = 5      % width of the window (expressed in percentage deviation) around the computed minimum to be displayed on the diagnostic plots
+        % , mode_check_symmetric_plots=1           % ensure that the check plots are symmetric around the minimum
+        % , mode_check_number_of_points = 20       % number of points around the minimum where the target function is evaluated (for each parameter)
     );
 @#endfor
\ No newline at end of file
diff --git a/tests/estimation/method_of_moments/RBC/RBC_MoM_steady_helper.m b/tests/estimation/method_of_moments/RBC/RBC_MoM_steady_helper.m
new file mode 100644
index 0000000000000000000000000000000000000000..9c43619d7682489f8f278ac04df1f5b4766aa62b
--- /dev/null
+++ b/tests/estimation/method_of_moments/RBC/RBC_MoM_steady_helper.m
@@ -0,0 +1,40 @@
+% =========================================================================
+% Copyright (C) 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 <http://www.gnu.org/licenses/>.
+% =========================================================================
+function [N, info]= RBC_MoM_steady_helper(THETA,ETAl,ETAc,BETTA,B,C_O_N,W)
+info=0;
+if ~isreal(C_O_N)
+    info=1;
+    N=NaN;
+    return;
+end
+if ETAc == 1 && ETAl == 1
+    N = (1-BETTA*B)*(C_O_N*(1-B))^-1*W/THETA/(1+(1-BETTA*B)*(C_O_N*(1-B))^-1*W/THETA);
+else
+    % No closed-form solution use a fixed-point algorithm
+    N0 = 1/3;
+    try
+        [N, ~, exitflag] = fsolve(@(N) THETA*(1-N)^(-ETAl)*N^ETAc - (1-BETTA*B)*(C_O_N*(1-B))^(-ETAc)*W, N0,optimset('Display','off','TolX',1e-12,'TolFun',1e-12));        
+        if exitflag<1
+            info=1;
+        end
+    catch
+        N=NaN;
+        info=1;
+    end
+end
\ No newline at end of file
diff --git a/tests/estimation/method_of_moments/RBC_MoM_Andreasen.mod b/tests/estimation/method_of_moments/RBC_MoM_Andreasen.mod
deleted file mode 100644
index ae69840050f5f33165cbf36d2a13c04f84feda1e..0000000000000000000000000000000000000000
--- a/tests/estimation/method_of_moments/RBC_MoM_Andreasen.mod
+++ /dev/null
@@ -1,227 +0,0 @@
-% Tests SMM and GMM routines
-%
-% Copyright (C) 2020 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 <http://www.gnu.org/licenses/>.
-% =========================================================================
-
-% Define testscenario
-@#define orderApp = 2
-@#define estimParams = 1
-
-% Note that we will set the numerical optimization tolerance levels very large to speed up the testsuite
-@#define optimizer = 13
-
-
-@#include "RBC_MoM_common.inc"
-
-shocks;
-var u_a; stderr 0.0072;        
-end;
-
-varobs c iv n;
-
-
-@#if estimParams == 0
-estimated_params;
-    DELTA,         0.025;
-    BETTA,         0.984;
-    B,             0.5;
-    ETAc,          2;
-    ALFA,          0.667;
-    RHOA,          0.979;
-    stderr u_a,    0.0072;
-end;
-@#endif
-
-@#if estimParams == 1
-estimated_params;
-    DELTA,         ,        0,           1;
-    BETTA,         ,        0,           1;
-    B,             ,        0,           1;
-    ETAc,          ,        0,           10;
-    ALFA,          ,        0,           1;
-    RHOA,          ,        0,           1;
-    stderr u_a,    ,        0,           1;
-end;
-@#endif
-
-@#if estimParams == 2
-estimated_params;
-    DELTA,         0.025,         0,           1,  normal_pdf, 0.02, 0.5;
-    BETTA,         0.98,         0,           1,  beta_pdf, 0.90, 0.25;
-    B,             0.45,         0,           1,  normal_pdf, 0.40, 0.5;
-    %ETAl,          1,            0,           10, normal_pdf, 0.25, 0.0.1;
-    ETAc,          1.8,         0,           10, normal_pdf, 1.80, 0.5;
-    ALFA,          0.65,         0,           1,  normal_pdf, 0.60, 0.5;
-    RHOA,          0.95,         0,           1,  normal_pdf, 0.90, 0.5;
-    stderr u_a,    0.01,         0,           1,  normal_pdf, 0.01, 0.5;
-    %THETA,         3.48,          0,           10, normal_pdf, 0.25, 0.0.1;
-end;
-@#endif
-
-% Simulate data
-%stoch_simul(order=@{orderApp},pruning,nodisplay,nomoments,periods=500);
-%save('RBC_MoM_data_@{orderApp}.mat', options_.varobs{:} );
-%pause(1);
-
-
-estimated_params_init(use_calibration);
-end;
-
-
-%--------------------------------------------------------------------------
-% Method of Moments Estimation
-%--------------------------------------------------------------------------
-matched_moments;
-c;
-n;
-iv;
-c*c;
-c*iv;
-iv*n;
-iv*iv;
-n*c;
-n*n;
-c*c(-1);
-n*n(-1);
-iv*iv(-1);
-
-c*c(-3);
-n*n(-3);
-iv*iv(-3);
-
-c*c(-5);
-n*n(-5);
-iv*iv(-5);
-end;
-
-% get indices in declaration order
-ic  = strmatch('c',  M_.endo_names,'exact');
-iiv = strmatch('iv', M_.endo_names,'exact');
-in  = strmatch('n',  M_.endo_names,'exact');
-% first entry: number of variable in declaration order
-% second entry: lag
-% third entry: power
-
-matched_moments_ = {
-    [ic     ]  [0   ],  [1  ];
-    [in     ]  [0   ],  [1  ];    
-    [iiv    ]  [0   ],  [1  ];
-    
-    [ic  ic ]  [0  0],  [1 1];
-    [ic  iiv]  [0  0],  [1 1];
-    %[ic  in ]  [0  0],  [1 1];
-    %[iiv ic ]  [0  0],  [1 1];
-    [in iiv]  [0  0],  [1 1];
-    [iiv iiv]  [0  0],  [1 1];    
-    [ic  in]  [0  0],  [1 1];
-    %[in  iiv]  [0  0],  [1 1];
-    [in  in ]  [0  0],  [1 1];
-    
-    [ic  ic ]  [0 -1],  [1 1];
-    [in  in ]  [0 -1],  [1 1];
-    [iiv iiv]  [0 -1],  [1 1];
-
-    [ic  ic ]  [0 -3],  [1 1];
-    [in  in ]  [0 -3],  [1 1];
-    [iiv iiv]  [0 -3],  [1 1];
-
-    [ic  ic ]  [0 -5],  [1 1];
-    [in  in ]  [0 -5],  [1 1];
-    [iiv iiv]  [0 -5],  [1 1];
-
-};
-
-if ~isequal(M_.matched_moments,matched_moments_)
-    error('Translation to matched_moments-block failed')
-end
-
-
-    method_of_moments(
-        % Necessery options
-          mom_method = GMM                  % method of moments method; possible values: GMM|SMM
-        , datafile   = 'RBC_Andreasen_Data_2.mat'         % name of filename with data
-
-        % Options for both GMM and SMM
-        %, bartlett_kernel_lag = 20          % bandwith in optimal weighting matrix
-        , order = @{orderApp}                % order of Taylor approximation in perturbation
-        %, penalized_estimator               % use penalized optimization
-        %, pruning                             % use pruned state space system at higher-order
-        %, verbose                           % display and store intermediate estimation results
-        , weighting_matrix = ['DIAGONAL','OPTIMAL']      % weighting matrix in moments distance objective function; possible values: OPTIMAL|IDENTITY_MATRIX|DIAGONAL|filename
-        %, weighting_matrix_scaling_factor=1
-        , additional_optimizer_steps = [13]    % vector of additional mode-finders run after mode_compute
-        %, prefilter=0                       % demean each data series by its empirical mean and use centered moments
-        % 
-        % Options for SMM
-        %, bounded_shock_support             % trim shocks in simulation to +- 2 stdev
-        %, drop = 500                        % number of periods dropped at beginning of simulation
-        %, seed = 24051986                   % seed used in simulations
-        %, simulation_multiple = 5           % multiple of the data length used for simulation
-        %, burnin = 200
-        % 
-        % General options
-        %, dirname = 'MM'                    % directory in which to store estimation output
-        %, graph_format = EPS                % specify the file format(s) for graphs saved to disk
-        %, nodisplay                         % do not display the graphs, but still save them to disk
-        %, nograph                           % do not create graphs (which implies that they are not saved to the disk nor displayed)
-        %, noprint                           % do not print stuff to console
-        %, plot_priors = 1                   % control plotting of priors
-        %, prior_trunc = 1e-10               % probability of extreme values of the prior density that is ignored when computing bounds for the parameters
-        , TeX                               % print TeX tables and graphics
-        % 
-        % Data and model options
-        %, first_obs = 501                     % number of first observation
-        %, logdata                           % if loglinear is set, this option is necessary if the user provides data already in logs, otherwise the log transformation will be applied twice (this may result in complex data)
-        %, loglinear                         % computes a log-linear approximation of the model instead of a linear approximation
-        %, nobs = 50                        % number of observations
-        % , xls_sheet = willi                 % name of sheet with data in Excel
-        % , xls_range = B2:D200               % range of data in Excel sheet
-        % 
-        % Optimization options that can be set by the user in the mod file, otherwise default values are provided
-        %, analytic_derivation               % uses analytic derivatives to compute standard errors for GMM
-        %, huge_number=1D10                   % value for replacing the infinite bounds on parameters by finite numbers. Used by some optimizers for numerical reasons
-        , mode_compute = 13         % specifies the optimizer for minimization of moments distance, note that by default there is a new optimizer
-        , optim = ('TolFun', 1D-6
-                   ,'TolX', 1D-6
-                  )    % a list of NAME and VALUE pairs to set options for the optimization routines. Available options depend on mode_compute
-        %, silent_optimizer                  % run minimization of moments distance silently without displaying results or saving files in between
-        , se_tolx = 1e-6                       % convergence criterion on funciton input for numerical differentiation
-        % 
-        % % Numerical algorithms options
-        %, aim_solver                             % Use AIM algorithm to compute perturbation approximation
-        %, dr=DEFAULT                             % method used to compute the decision rule; possible values are DEFAULT, CYCLE_REDUCTION, LOGARITHMIC_REDUCTION
-        %, dr_cycle_reduction_tol = 1e-7          % convergence criterion used in the cycle reduction algorithm
-        %, dr_logarithmic_reduction_maxiter = 100 % maximum number of iterations used in the logarithmic reduction algorithm
-        %, dr_logarithmic_reduction_tol = 1e-12   % convergence criterion used in the cycle reduction algorithm
-        %, k_order_solver                         % use k_order_solver in higher order perturbation approximations
-        %, lyapunov = DEFAULT                     % algorithm used to solve lyapunov equations; possible values are DEFAULT, FIXED_POINT, DOUBLING, SQUARE_ROOT_SOLVER
-        %, lyapunov_complex_threshold = 1e-15     % complex block threshold for the upper triangular matrix in symmetric Lyapunov equation solver
-        %, lyapunov_fixed_point_tol = 1e-10       % convergence criterion used in the fixed point Lyapunov solver
-        %, lyapunov_doubling_tol = 1e-16          % convergence criterion used in the doubling algorithm
-        %, sylvester = default                    % algorithm to solve Sylvester equation; possible values are DEFAULT, FIXED_POINT
-        %, sylvester_fixed_point_tol = 1e-12      % convergence criterion used in the fixed point Sylvester solver
-        %, qz_criterium = 0.999999                % value used to split stable from unstable eigenvalues in reordering the Generalized Schur decomposition used for solving first order problems [IS THIS CORRET @wmutschl]
-        %, qz_zero_threshold = 1e-6               % value used to test if a generalized eigenvalue is 0/0 in the generalized Schur decomposition
-        , mode_check
-        %, mode_check_neighbourhood_size=0.5
-        %, mode_check_symmetric_plots=0
-        %, mode_check_number_of_points=25
-    );
-
-
-
diff --git a/tests/estimation/method_of_moments/RBC_MoM_steady_helper.m b/tests/estimation/method_of_moments/RBC_MoM_steady_helper.m
deleted file mode 100644
index b495e27a1a1d5de281d17514c7be527a79c897eb..0000000000000000000000000000000000000000
--- a/tests/estimation/method_of_moments/RBC_MoM_steady_helper.m
+++ /dev/null
@@ -1,22 +0,0 @@
-function [N, info]= RBC_MoM_steady_helper(THETA,ETAl,ETAc,BETTA,B,C_O_N,W)
-info=0;
-if ~isreal(C_O_N)
-    info=1;
-    N=NaN;
-    return;
-end
-if ETAc == 1 && ETAl == 1
-    N = (1-BETTA*B)*(C_O_N*(1-B))^-1*W/THETA/(1+(1-BETTA*B)*(C_O_N*(1-B))^-1*W/THETA);
-else
-    % No closed-form solution use a fixed-point algorithm
-    N0 = 1/3;
-    try
-        [N, ~, exitflag] = fsolve(@(N) THETA*(1-N)^(-ETAl)*N^ETAc - (1-BETTA*B)*(C_O_N*(1-B))^(-ETAc)*W, N0,optimset('Display','off','TolX',1e-12,'TolFun',1e-12));        
-        if exitflag<1
-            info=1;
-        end
-    catch
-        N=NaN;
-        info=1;
-    end
-end
\ No newline at end of file
diff --git a/tests/estimation/method_of_moments/RBC_MoM_steadystate.m b/tests/estimation/method_of_moments/RBC_MoM_steadystate.m
deleted file mode 100644
index ba4ef9240b522ac5bbf83fc41380a50f3f1805f8..0000000000000000000000000000000000000000
--- a/tests/estimation/method_of_moments/RBC_MoM_steadystate.m
+++ /dev/null
@@ -1,74 +0,0 @@
-% By Willi Mutschler, September 26, 2016. Email: willi@mutschler.eu
-function [ys,params,check] = RBCmodel_steadystate(ys,exo,M_,options_)
-%% Step 0: initialize indicator and set options for numerical solver
-check = 0;
-options = optimset('Display','off','TolX',1e-12,'TolFun',1e-12);
-params = M_.params;
-
-%% Step 1: read out parameters to access them with their name
-for ii = 1:M_.param_nbr
-  eval([ M_.param_names{ii} ' = M_.params(' int2str(ii) ');']);
-end
-
-%% Step 2: Check parameter restrictions
-if ETAc*ETAl<1 % parameter violates restriction (here it is artifical)
-    check=1; %set failure indicator
-    return;  %return without updating steady states
-end
-
-%% Step 3: Enter model equations here
-A = 1;
-RK = 1/BETTA - (1-DELTA);
-K_O_N = (RK/(A*(1-ALFA)))^(-1/ALFA);
-if K_O_N <= 0
-    check = 1; % set failure indicator
-    return;    % return without updating steady states
-end
-W = A*ALFA*(K_O_N)^(1-ALFA);
-IV_O_N = DELTA*K_O_N;
-Y_O_N = A*K_O_N^(1-ALFA);
-C_O_N = Y_O_N - IV_O_N;
-if C_O_N <= 0
-    check = 1; % set failure indicator
-    return;    % return without updating steady states
-end
-
-% The labor level
-if ETAc == 1 && ETAl == 1
-    N = (1-BETTA*B)*(C_O_N*(1-B))^-1*W/THETA/(1+(1-BETTA*B)*(C_O_N*(1-B))^-1*W/THETA);
-else
-    % No closed-form solution use a fixed-point algorithm
-    N0 = 1/3;
-    [N,~,exitflag] = fsolve(@(N) THETA*(1-N)^(-ETAl)*N^ETAc - (1-BETTA*B)*(C_O_N*(1-B))^(-ETAc)*W, N0,options);
-    if exitflag <= 0
-        check = 1; % set failure indicator
-        return     % return without updating steady states
-    end
-end
-
-C=C_O_N*N;
-Y=Y_O_N*N;
-IV=IV_O_N*N;
-K=K_O_N*N;
-LA = (C-B*C)^(-ETAc)-BETTA*B*(C-B*C)^(-ETAc);
-
-k=log(K);
-c=log(C);
-a=log(A);
-iv=log(IV);
-y=log(Y);
-la=log(LA);
-n=log(N);
-rk=log(RK);
-w=log(W);
-%% Step 4: Update parameters and variables
-params=NaN(M_.param_nbr,1);
-for iter = 1:M_.param_nbr %update parameters set in the file
-  eval([ 'params(' num2str(iter) ') = ' M_.param_names{iter} ';' ])
-end
-
-for ii = 1:M_.orig_endo_nbr %auxiliary variables are set automatically
-  eval(['ys(' int2str(ii) ') = ' M_.endo_names{ii} ';']);
-end
-
-end
diff --git a/tests/histval_initval_file/ramst_data.mod b/tests/histval_initval_file/ramst_data.mod
index c65b9fc816cb27a8444cec66fadbdb8f128d6568..97fa2ef277e75407607df287f2d978912cf494ea 100644
--- a/tests/histval_initval_file/ramst_data.mod
+++ b/tests/histval_initval_file/ramst_data.mod
@@ -36,8 +36,8 @@ perfect_foresight_solver;
 
 fh = fopen('ramst_data.m', 'w');
 fprintf(fh, 'INIT__ = ''1Y'';\n');
-fprintf(fh, 'NAMES__ = {''c'', ''k'', ''x''};\n');
-fprintf(fh, 'TEX__ = {''c'', ''k'', ''x''};\n');
+fprintf(fh, 'NAMES__ = {''c''; ''k''; ''x''};\n');
+fprintf(fh, 'TEX__ = {''c''; ''k''; ''x''};\n');
 fprintf(fh, 'c = [');
 fprintf(fh, '%f ', oo_.endo_simul(1,:));
 fprintf(fh, '];\n');
@@ -50,8 +50,8 @@ fprintf(fh, '];\n');
 fclose(fh);
 
 INIT__ = '1Y';
-NAMES__ = {'c', 'k', 'x'};
-TEX__  = {'c', 'k', 'x'};
+NAMES__ = {'c'; 'k'; 'x'};
+TEX__  = {'c'; 'k'; 'x'};
 eval('c = oo_.endo_simul(1,:);');
 eval('k = oo_.endo_simul(2,:);');
 eval('x = oo_.exo_simul'';');
@@ -61,7 +61,7 @@ save('ramst_data.mat', 'INIT__', 'NAMES__', ...
 fh = fopen('ramst_data.csv', 'w');
 fprintf(fh, 'c,k,x\n');
 for i = 1:size(oo_.endo_simul, 2);
-  fprintf(fh, '%f, ', oo_.endo_simul(:, i));
+  fprintf(fh, '%f, ', oo_.endo_simul(1:M_.orig_endo_nbr, i));
   fprintf(fh, '%f\n', oo_.exo_simul(i));
 end;
 fclose(fh);
diff --git a/tests/histval_initval_file/sim_exo_lead_lag_initvalf.mod b/tests/histval_initval_file/sim_exo_lead_lag_initvalf.mod
index 044a1ee2630abbb040755dd5a2f21fda5526032c..43e129e3e4c34944c46f8437fbb623f45f23fb26 100644
--- a/tests/histval_initval_file/sim_exo_lead_lag_initvalf.mod
+++ b/tests/histval_initval_file/sim_exo_lead_lag_initvalf.mod
@@ -25,10 +25,10 @@ end;
 
 initval_file(series = ds);
 if oo_.initval_series.dates(1) ~= dates('1Y');
-  error("Wrong initial date in oo_.initval_series");
+  error('Wrong initial date in oo_.initval_series');
 end;
 if oo_.initval_series{'x'}.data(6) ~= 0.9;
-  error("Wrond value for x"); 
+  error('Wrong value for x');
 end;
 
 perfect_foresight_setup(periods=200);
@@ -49,10 +49,10 @@ ds1 = dseries(data1, '1Y', {'c', 'cmav', 'k', 'z_backward', 'z_forward', 'x'});
 
 initval_file(series = ds1, first_obs = 3, last_obs = 210, nobs = 208);
 if oo_.initval_series.dates(1) ~= dates('3Y');
-  error("Wrong initial date in oo_.initval_series");
+  error('Wrong initial date in oo_.initval_series');
 end;
 if oo_.initval_series{'x'}.data(6) ~= 0.9;
-  error("Wrond value for x"); 
+  error('Wrong value for x');
 end;
 
 
@@ -70,10 +70,10 @@ end
 
 initval_file(series = ds1, first_obs = 3Y, last_obs = 210Y, nobs = 208);
 if oo_.initval_series.dates(1) ~= dates('3Y');
-  error("Wrong initial date in oo_.initval_series");
+  error('Wrong initial date in oo_.initval_series');
 end;
 if oo_.initval_series{'x'}.data(6) ~= 0.9;
-  error("Wrond value for x"); 
+  error('Wrong value for x');
 end;
 
 
@@ -91,10 +91,10 @@ end
 
 initval_file(series = ds1, first_simulation_period = 7);
 if oo_.initval_series.dates(1) ~= dates('3Y');
-  error("Wrong initial date in oo_.initval_series");
+  error('Wrong initial date in oo_.initval_series');
 end;
 if oo_.initval_series{'x'}.data(6) ~= 0.9;
-  error("Wrond value for x"); 
+  error('Wrong value for x');
 end;
 
 
@@ -112,10 +112,10 @@ end
 
 initval_file(series = ds1, first_simulation_period = 7Y);
 if oo_.initval_series.dates(1) ~= dates('3Y');
-  error("Wrong initial date in oo_.initval_series");
+  error('Wrong initial date in oo_.initval_series');
 end;
 if oo_.initval_series{'x'}.data(6) ~= 0.9;
-  error("Wrond value for x"); 
+  error('Wrong value for x');
 end;
 
 
diff --git a/tests/histval_initval_file_unit_tests.m b/tests/histval_initval_file_unit_tests.m
index 925ce1a571503cdf07602ae039de6ec1a95dd26f..c8cbd8e1b5ed6e0459cd3b64d721f88b2a02867e 100644
--- a/tests/histval_initval_file_unit_tests.m
+++ b/tests/histval_initval_file_unit_tests.m
@@ -179,7 +179,8 @@ for i = 1:size(x,1)
 end
 fclose(fh);
 
-if ~verLessThan('matlab', '8.2')
+% The table() function is not implemented in Octave
+if ~isoctave && ((ispc && ~matlab_ver_less_than('8.2')) || (~ispc && ~matlab_ver_less_than('9.0')))
     writetable(table(x,y), 'data.xlsx')
     options = struct();
     options.datafile = 'data.xlsx';
@@ -189,23 +190,30 @@ if ~verLessThan('matlab', '8.2')
     failed_tests = my_assert(failed_tests, series.nobs == 10, ...
                              '*.xlsx file nobs test');
     num_tests = num_tests + 2;
+end
 
-    if ispc
-        writetable(table(x,y), 'data.xls')
-        options = struct();
-        options.datafile = 'data.xls';
-        series = histvalf_initvalf('INITVAL_FILE', M, options);
-        failed_tests = my_assert(failed_tests, series.init == dates('1Y'), ...
+% The table() function is not implemented in Octave
+% The test also does not work under GNU/Linux + MATLAB R2020b (Unicode issue in xlsread)
+if ~isoctave && (ispc && ~matlab_ver_less_than('8.2'))
+    writetable(table(x,y), 'data.xls')
+    options = struct();
+    options.datafile = 'data.xls';
+    series = histvalf_initvalf('INITVAL_FILE', M, options);
+    failed_tests = my_assert(failed_tests, series.init == dates('1Y'), ...
                              '*.xls file first_obs test');
-        failed_tests = my_assert(failed_tests, series.nobs == 10, ...        
+    failed_tests = my_assert(failed_tests, series.nobs == 10, ...
                              '*.xls file nobs test');
-        num_tests = num_tests + 2;
-    end
+    num_tests = num_tests + 2;
 end
 
 cd(getenv('TOP_TEST_DIR'));
-fid = fopen('histval_initval_file_unit_tests.m.trs', 'w+');
-num_failed_tests = length(failed_tests)
+if isoctave
+    ext = '.o.trs';
+else
+    ext = '.m.trs';
+end
+fid = fopen([ 'histval_initval_file_unit_tests' ext ], 'w+');
+num_failed_tests = length(failed_tests);
 if num_failed_tests > 0
   fprintf(fid,':test-result: FAIL\n');
   fprintf(fid,':number-tests: %d\n', num_tests);
diff --git a/tests/identification/forward_looking/forward_looking.mod b/tests/identification/forward_looking/forward_looking.mod
new file mode 100755
index 0000000000000000000000000000000000000000..bf7c18d3b815524679928d1f833872cc4884400d
--- /dev/null
+++ b/tests/identification/forward_looking/forward_looking.mod
@@ -0,0 +1,70 @@
+% Forward-looking example model from Koop, Pesaran, Smith (2013, JBES)
+% created by Willi Mutschler (@wmutschl, willi@mutschler.eu)
+% =========================================================================
+% Copyright (C) 2020 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 <http://www.gnu.org/licenses/>.
+% =========================================================================
+var r x p;
+varexo e_M e_D e_S;
+varobs r x p;
+
+parameters PSI TAU BETA KAPPA;
+
+PSI=1.1;
+TAU=2;
+BETA=0.9;
+KAPPA=0.6;
+
+model;
+r = PSI*p + e_M;
+x = x(+1) - 1/TAU*(r-p(+1)) + e_D;
+p = BETA*p(+1) + KAPPA*x + e_S;
+end;
+
+shocks;
+var e_M = 1;
+var e_D = 1;
+var e_S = 1;
+end;
+
+steady;
+check;
+
+estimated_params;
+PSI,   1.1;
+TAU,   2;
+BETA,  0.9;
+KAPPA, 0.6;
+end;
+
+identification; %this triggers sylvester3a with empty ghx
+
+% as a side note, we have the true solution:
+% [r;x;p] = TRUE_SOLUTION*[e_M;e_D;e_S] (ghx is empty)
+A = [1 0 -PSI; 1/TAU 1 0; 0 -KAPPA 1];
+TRUE_SOLUTION1 = inv(A);
+TRUE_SOLUTION2 = 1/(KAPPA*PSI/TAU +1)*[1         KAPPA*PSI PSI;
+                                      -1/TAU     1         -PSI/TAU;
+                                      -KAPPA/TAU KAPPA     1];
+% note that BETA drops out from the solution
+
+if max(max(abs(TRUE_SOLUTION1 - oo_.dr.ghu))) > 1e-15
+    error('Something wrong with perturbation');
+end
+if max(max(abs(TRUE_SOLUTION2 - oo_.dr.ghu))) > 1e-15
+    error('Something wrong with perturbation');
+end
\ No newline at end of file
diff --git a/tests/lmmcp/purely_backward.mod b/tests/lmmcp/purely_backward.mod
new file mode 100644
index 0000000000000000000000000000000000000000..7d3bce2727b07f51fde7fa06944eb5527c381e7b
--- /dev/null
+++ b/tests/lmmcp/purely_backward.mod
@@ -0,0 +1,40 @@
+// Regression test for bug #1720 (in the purely backward case)
+
+var y;
+
+varexo eps;
+
+parameters rho;
+
+rho = 0.9;
+
+model;
+  [ mcp = 'y>1' ]
+  y = y(-1)^rho*exp(eps);
+end;
+
+initval;
+    y = 1;
+  eps = 0;
+end;
+
+steady;
+
+check;
+
+shocks;
+    var eps;
+    periods 1 10;
+    values -1 1;
+end;
+
+perfect_foresight_setup(periods=20);
+perfect_foresight_solver(lmmcp);
+
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
+if any(oo_.endo_simul < 1)
+  error('y>1 constraint not enforced')
+end
diff --git a/tests/lmmcp/purely_forward.mod b/tests/lmmcp/purely_forward.mod
new file mode 100644
index 0000000000000000000000000000000000000000..eb61ad29e818032de7d2ef66c48587a8ce943f36
--- /dev/null
+++ b/tests/lmmcp/purely_forward.mod
@@ -0,0 +1,36 @@
+// Regression test for bug #1720 (in the purely forward case)
+
+var y;
+
+varexo eps;
+
+model;
+  [ mcp='y>1' ]
+  y = sqrt(y(1))*exp(eps);
+end;
+
+initval;
+  y = 1;
+end;
+
+steady;
+
+check;
+
+
+shocks;
+    var eps;
+    periods 1 10;
+    values 1 -1;
+end;
+
+perfect_foresight_setup(periods=20);
+perfect_foresight_solver(lmmcp);
+
+if ~oo_.deterministic_simulation.status
+   error('Perfect foresight simulation failed')
+end
+
+if any(oo_.endo_simul < 1)
+  error('y>1 constraint not enforced')
+end
diff --git a/tests/loglinear/example4_loglinear.mod b/tests/loglinear/example4_loglinear.mod
index ebb403a5d011d541ffb3f6ae41f995c8bac3f913..d84c80b42da7e8f534ba1360f8d23d553729c90f 100644
--- a/tests/loglinear/example4_loglinear.mod
+++ b/tests/loglinear/example4_loglinear.mod
@@ -23,7 +23,7 @@
  */
 
 
-var y, c, k, a, h, b;
+var y $y$, c $c$, k $k$, a , h, b;
 varexo e, u;
 
 parameters beta, rho, alpha, delta, theta, psi, tau;
@@ -57,13 +57,15 @@ a = 1;
 b = 1;
 end;
 resid(1);
+steady;
+
 shocks;
 var e; stderr 0.009;
 var u; stderr 0.009;
 var e, u = phi*0.009*0.009;
 end;
-
-stoch_simul(loglinear,order=1);
+steady;
+stoch_simul(loglinear,order=1,conditional_variance_decomposition=[1:2]);
 forecast;
 
 conditional_forecast_paths;
diff --git a/tests/example1_macro.mod b/tests/macro_processor/example1_macro.mod
similarity index 100%
rename from tests/example1_macro.mod
rename to tests/macro_processor/example1_macro.mod
diff --git a/tests/macro_processor/test_ifndef.mod b/tests/macro_processor/test_ifndef.mod
new file mode 100644
index 0000000000000000000000000000000000000000..2a846473eb0851e0aafd542ce64e80df4c9f05ff
--- /dev/null
+++ b/tests/macro_processor/test_ifndef.mod
@@ -0,0 +1,17 @@
+// test ifndef to prevent regressions like #1747
+@#define marco=1
+@#ifndef marco
+    def=0;
+@#else
+    def=1;
+@#endif
+
+if ~def
+    error('ifndef not reached')
+end
+
+var x;
+
+model;
+x;
+end;
\ No newline at end of file
diff --git a/tests/moments/example1_order2_pruning.mod b/tests/moments/example1_order2_pruning.mod
new file mode 100644
index 0000000000000000000000000000000000000000..bd13e0c84a4766a6adad5316dd3844b0ccbb8438
--- /dev/null
+++ b/tests/moments/example1_order2_pruning.mod
@@ -0,0 +1,46 @@
+// Example 1 from Collard's guide to Dynare
+// tests moments at order=2 with pruning
+var y, k, a, h, b;
+varexo e, u;
+
+parameters beta, rho, alpha, delta, theta, psi, tau;
+
+alpha = 0.36;
+rho   = 0.95;
+tau   = 0.025;
+beta  = 0.99;
+delta = 0.025;
+psi   = 0;
+theta = 2.95;
+
+phi   = 0.1;
+
+model;
+[endogenous='c',name='law of motion of capital']
+c*theta*h^(1+psi)=(1-alpha)*y;
+k = beta*(((exp(b)*c)/(exp(b(+1))*c(+1)))
+    *(exp(b(+1))*alpha*y(+1)+(1-delta)*k));
+y = exp(a)*(k(-1)^alpha)*(h^(1-alpha));
+k = exp(b)*(y-c)+(1-delta)*k(-1);
+a = rho*a(-1)+tau*b(-1) + e;
+b = tau*a(-1)+rho*b(-1) + u;
+end;
+
+initval;
+y = 1.08068253095672;
+c = 0.80359242014163;
+h = 0.29175631001732;
+k = 11.08360443260358;
+a = 0;
+b = 0;
+e = 0;
+u = 0;
+end;
+
+shocks;
+var e; stderr 0.009;
+var u; stderr 0.009;
+var e, u = phi*0.009*0.009;
+end;
+
+stoch_simul(order=2,pruning);
\ No newline at end of file
diff --git a/tests/occbin/dynrbc.mod b/tests/occbin/dynrbc.mod
deleted file mode 100755
index 51e6125241fa7007b0cfd302132bb7bd1fad0529..0000000000000000000000000000000000000000
--- a/tests/occbin/dynrbc.mod
+++ /dev/null
@@ -1,55 +0,0 @@
-// variables
-var a, c, i, k, kprev, lambdak;    
- 
-// innovations to shock processes
-varexo erra;
-
-
-// parameters
-parameters ALPHA, DELTAK, BETA, GAMMAC, RHOA, PHII, PHIK, PSI, PSINEG, ISS, KSS ;
-
-model;
-
-# zkss = ((1/BETA-1+DELTAK)/ALPHA)^(1/(ALPHA-1));
-# zcss = -DELTAK*zkss + zkss^ALPHA;
-# ziss = DELTAK*zkss;
-# zuss = (zcss^(1-GAMMAC)-1)/(1-GAMMAC);
-# zvss = zuss/(1-BETA);
-
-/////////////////////////////////////////////////////////////////
-// 1.
--exp(c)^(-GAMMAC)*(1+2*PSI*(exp(k)/exp(k(-1))-1)/exp(k(-1)))
-+ BETA*exp(c(1))^(-GAMMAC)*((1-DELTAK)-2*PSI*(exp(k(1))/exp(k)-1)*
-  (-exp(k(1))/exp(k)^2)+ALPHA*exp(a(1))*exp(k)^(ALPHA-1))= 
-  -lambdak+BETA*(1-DELTAK+PHIK)*lambdak(1);
-
-// 2.
-exp(c)+exp(k)-(1-DELTAK)*exp(k(-1))+
-PSI*(exp(k)/exp(k(-1))-1)^2=exp(a)*exp(k(-1))^(ALPHA);
-
-// 3.
-exp(i) = exp(k)-(1-DELTAK)*exp(k(-1));
-
-// 4.
-lambdak = 0;
-
-// 5. 
-a = RHOA*a(-1)+erra;
-
-
-kprev=k(-1);
-
-
-end;
-
-
-
-shocks;
-  var erra; stderr 0.015;
-end;
-
-
-steady;
-
-
-stoch_simul(order=1,nocorr,nomoments,irf=0,print);
diff --git a/tests/ramst_mshocks.mod b/tests/ramst_mshocks.mod
new file mode 100644
index 0000000000000000000000000000000000000000..186dbcb9713c9907056b1ca9c55318e204d7738a
--- /dev/null
+++ b/tests/ramst_mshocks.mod
@@ -0,0 +1,44 @@
+// Test mshocks block
+
+var c k;
+varexo x;
+
+parameters alph gam delt bet aa;
+alph=0.5;
+gam=0.5;
+delt=0.02;
+bet=0.05;
+aa=0.5;
+
+
+model;
+c + k - aa*x*k(-1)^alph - (1-delt)*k(-1);
+c^(-gam) - (1+bet)^(-1)*(aa*alph*x(+1)*k^(alph-1) + 1 - delt)*c(+1)^(-gam);
+end;
+
+initval;
+x = 2;
+k = ((delt+bet)/(1.0*aa*x*alph))^(1/(alph-1));
+c = aa*x*k^alph-delt*k;
+end;
+
+steady;
+
+check;
+
+mshocks;
+var x;
+periods 1 2:3;
+values 1.2 0.8;
+end;
+
+perfect_foresight_setup(periods=200);
+perfect_foresight_solver;
+
+rplot c;
+rplot k;
+
+if ~all(oo_.exo_simul(M_.maximum_lag+(1:3)) == [ 2.4; 1.6; 1.6]) ...
+    || ~all(oo_.exo_simul(M_.maximum_lag+(4:200)) == 2)
+  error("mshocks not correctly applied")
+end
diff --git a/tests/ramst_static_tag_block.mod b/tests/ramst_static_tag_block.mod
new file mode 100644
index 0000000000000000000000000000000000000000..c9736021fad4a83825a37804a2e6b61ee7cbfa58
--- /dev/null
+++ b/tests/ramst_static_tag_block.mod
@@ -0,0 +1,39 @@
+// Test the [static]/[dynamic] tags, in the context of a block decomposed model
+
+var c k;
+varexo x;
+
+parameters alph gam delt bet aa;
+alph=0.5;
+gam=0.5;
+delt=0.02;
+bet=0.05;
+aa=0.5;
+
+
+model(block);
+c + k - aa*x*k(-1)^alph - (1-delt)*k(-1);
+[dynamic] c^(-gam) - (1+bet)^(-1)*(aa*alph*x(+1)*k^(alph-1) + 1 - delt)*c(+1)^(-gam);
+[static] k = ((delt+bet)/(x*aa*alph))^(1/(alph-1));
+end;
+
+initval;
+x = 1;
+k = ((delt+bet)/(1.0*aa*alph))^(1/(alph-1));
+c = aa*k^alph-delt*k;
+end;
+
+steady;
+
+check;
+
+shocks;
+var x;
+periods 1;
+values 1.2;
+end;
+
+simul(periods=200);
+
+rplot c;
+rplot k;
diff --git a/tests/simul/simul_ZLB_purely_forward.mod b/tests/simul/simul_ZLB_purely_forward.mod
index 4df56441dccec7eff067b10d239cf62e40f930f1..d09a32764717f30cbc8b76c9a4dc569166d0e447 100644
--- a/tests/simul/simul_ZLB_purely_forward.mod
+++ b/tests/simul/simul_ZLB_purely_forward.mod
@@ -92,5 +92,5 @@ simul(periods=40,maxit=1000);
 rplot gdp_hat;
 rplot R;
 if oo_.deterministic_simulation.status~=1
-    error('This model has solution');
-end
\ No newline at end of file
+    error('This model has no solution');
+end
diff --git a/windows/build.sh b/windows/build.sh
index f27f0eec790181a3ee407bf9f1281902975a929a..4d4c7c8f12fb19ba964bf9e350b892939ddbb6af 100755
--- a/windows/build.sh
+++ b/windows/build.sh
@@ -76,6 +76,7 @@ if [[ -z $CI ]]; then
     make -j"$NTHREADS" pdf html
 fi
 make -j"$NTHREADS"
+x86_64-w64-mingw32-strip preprocessor/src/dynare-preprocessor.exe
 x86_64-w64-mingw32-strip matlab/preprocessor64/dynare_m.exe
 x86_64-w64-mingw32-strip dynare++/src/dynare++.exe
 
@@ -195,6 +196,8 @@ cp -pr contrib/jsonlab/* "$ZIPDIR"/contrib/jsonlab
 mkdir "$ZIPDIR"/mex
 cp -pr mex/octave/ "$ZIPDIR"/mex
 cp -pr mex/matlab/ "$ZIPDIR"/mex
+mkdir "$ZIPDIR"/preprocessor
+cp -p preprocessor/src/dynare-preprocessor.exe "$ZIPDIR"/preprocessor
 cp -pr matlab "$ZIPDIR"
 mkdir -p "$ZIPDIR"/matlab/modules/dseries/externals/x13/windows/64
 cp -p windows/deps/lib64/x13as/x13as.exe "$ZIPDIR"/matlab/modules/dseries/externals/x13/windows/64
diff --git a/windows/deps/Makefile b/windows/deps/Makefile
index 2cbc39b76305595732d49fd8aa412aa7dca0c056..487ff5c000659a9e7f1fa9c79a9ac6ffc5c8fd69 100644
--- a/windows/deps/Makefile
+++ b/windows/deps/Makefile
@@ -170,13 +170,13 @@ msys2: lib64-msys2 mingw64
 
 MSYS2_EXCLUDES := --exclude .MTREE --exclude .BUILDINFO --exclude .PKGINFO
 
-lib64-msys2: tarballs/mingw-w64-x86_64-boost-$(MINGW64_BOOST_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-gsl-$(MINGW64_GSL_VERSION)-any.pkg.tar.xz tarballs/mingw-w64-x86_64-openblas-$(MINGW64_OPENBLAS_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-matio-$(MINGW64_MATIO_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-zlib-$(MINGW64_ZLIB_VERSION)-any.pkg.tar.xz tarballs/mingw-w64-x86_64-hdf5-$(MINGW64_HDF5_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-szip-$(MINGW64_SZIP_VERSION)-any.pkg.tar.xz
+lib64-msys2: tarballs/mingw-w64-x86_64-boost-$(MINGW64_BOOST_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-gsl-$(MINGW64_GSL_VERSION)-any.pkg.tar.xz tarballs/mingw-w64-x86_64-openblas-$(MINGW64_OPENBLAS_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-matio-$(MINGW64_MATIO_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-zlib-$(MINGW64_ZLIB_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-hdf5-$(MINGW64_HDF5_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-szip-$(MINGW64_SZIP_VERSION)-any.pkg.tar.xz
 	rm -rf $@
 	mkdir $@
 	for f in $^; do tar xf $$f --directory $@ --strip-components 1 $(MSYS2_EXCLUDES); done
 	touch $@
 
-mingw64: tarballs/mingw-w64-x86_64-gcc-$(MINGW64_GCC_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-gcc-libs-$(MINGW64_GCC_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-gmp-$(MINGW64_GMP_VERSION)-any.pkg.tar.xz tarballs/mingw-w64-x86_64-binutils-$(MINGW64_BINUTILS_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-headers-git-$(MINGW64_HEADERS_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-crt-git-$(MINGW64_CRT_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-winpthreads-git-$(MINGW64_WINPTHREADS_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-libwinpthread-git-$(MINGW64_WINPTHREADS_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-zlib-$(MINGW64_ZLIB_VERSION)-any.pkg.tar.xz tarballs/mingw-w64-x86_64-zstd-$(MINGW64_ZSTD_VERSION)-any.pkg.tar.zst
+mingw64: tarballs/mingw-w64-x86_64-gcc-$(MINGW64_GCC_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-gcc-libs-$(MINGW64_GCC_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-gmp-$(MINGW64_GMP_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-binutils-$(MINGW64_BINUTILS_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-headers-git-$(MINGW64_HEADERS_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-crt-git-$(MINGW64_CRT_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-winpthreads-git-$(MINGW64_WINPTHREADS_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-libwinpthread-git-$(MINGW64_WINPTHREADS_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-zlib-$(MINGW64_ZLIB_VERSION)-any.pkg.tar.zst tarballs/mingw-w64-x86_64-zstd-$(MINGW64_ZSTD_VERSION)-any.pkg.tar.zst
 	rm -rf $@
 	for f in $^; do tar xf $$f $(MSYS2_EXCLUDES); done
 	touch $@
diff --git a/windows/deps/mkoctfile64 b/windows/deps/mkoctfile64
index c4dc7c2af1583bcd0181de1e70cd908e027e2319..c026d7ed3ec984c7ac9c5bca0b1e1760ceb5731a 100755
--- a/windows/deps/mkoctfile64
+++ b/windows/deps/mkoctfile64
@@ -55,7 +55,7 @@ fi
 : ${CPPFLAGS=""}
 : ${INCFLAGS=$DEFAULT_INCFLAGS}
 : ${F77="x86_64-w64-mingw32-gfortran"}
-: ${FFLAGS="-O"}
+: ${FFLAGS="-g -O2 -std=legacy"}
 : ${FPICFLAG=""}
 : ${CC="x86_64-w64-mingw32-gcc"}
 : ${CFLAGS="-g -O2"}
@@ -63,17 +63,19 @@ fi
 : ${CXX="x86_64-w64-mingw32-g++"}
 : ${CXXFLAGS="-g -O2"}
 : ${CXXPICFLAG=""}
-: ${XTRA_CFLAGS=""}
-: ${XTRA_CXXFLAGS=""}
+: ${XTRA_CFLAGS="-fopenmp"}
+: ${XTRA_CXXFLAGS="-fopenmp"}
+: ${AR="x86_64-w64-mingw32-ar"}
+: ${RANLIB="x86_64-w64-mingw32-ranlib"}
 
 : ${DEPEND_FLAGS="-M"}
 : ${DEPEND_EXTRA_SED_PATTERN=""}
 
 : ${DL_LD="x86_64-w64-mingw32-g++"}
-: ${DL_LDFLAGS="-shared -Wl,--export-all-symbols -Wl,--enable-auto-import -Wl,--enable-runtime-pseudo-reloc -static-libgcc -static-libstdc++"}
+: ${DL_LDFLAGS="-shared -static-libgcc -static-libstdc++"}
 
-: ${RLD_FLAG="-Wl,-rpath -Wl,$OCTAVE_PREFIX/lib/octave/${OCTAVE_VERSION}"}
-: ${RDYNAMIC_FLAG="-rdynamic"}
+: ${RLD_FLAG=""}
+: ${RDYNAMIC_FLAG=""}
 : ${LIBOCTAVE=-loctave}
 : ${LIBOCTINTERP=-loctinterp}
 : ${READLINE_LIBS=-lreadline}
@@ -83,10 +85,10 @@ fi
 : ${FFTW3_LIBS="-lfftw3"}
 : ${FFTW3F_LDFLAGS=""}
 : ${FFTW3F_LIBS="-lfftw3f"}
-: ${LIBS="-lm -lgfortran -llapack -lgdi32 -lws2_32 -luser32 -lkernel32"}
-: ${FLIBS="-lm -lgfortran -llapack -lmingw32 -lmoldname -lmingwex -lmsvcrt -luser32 -lkernel32 -ladvapi32 -lshell32"}
+: ${LIBS="-lpsapi -lgdi32 -lm"}
+: ${FLIBS="-lm -lgfortran -lmingw32 -lmoldname -lmingwex -lmsvcrt -lquadmath -lpthread -ladvapi32 -lshell32 -luser32 -lkernel32"}
 : ${LD_CXX="x86_64-w64-mingw32-g++"}
-: ${LDFLAGS="-Wl,--enable-auto-import -Wl,--enable-runtime-pseudo-reloc-v2 -Wl,--allow-multiple-definition -static-libgcc -static-libstdc++"}
+: ${LDFLAGS="-static-libgcc -static-libstdc++"}
 : ${LD_STATIC_FLAG=""}
 : ${LFLAGS=$DEFAULT_LFLAGS}
 : ${F77_INTEGER_8_FLAG=""}
diff --git a/windows/deps/versions.mk b/windows/deps/versions.mk
index c6f3d2666dba0d666ce938b60aa519c67474ba6a..63a55a0ef2e488f3e280eda2f52837003597e8ad 100644
--- a/windows/deps/versions.mk
+++ b/windows/deps/versions.mk
@@ -18,20 +18,20 @@ MATLAB64_VERSION = 20200930
 ## Build dependencies
 
 # pacman -Ss mingw-w64-x86_64-boost
-MINGW64_BOOST_VERSION = 1.73.0-4
+MINGW64_BOOST_VERSION = 1.75.0-1
 
 # pacman -Ss mingw-w64-x86_64-gsl
 MINGW64_GSL_VERSION = 2.6-1
 
 # pacman -Ss mingw-w64-x86_64-openblas
-MINGW64_OPENBLAS_VERSION = 0.3.10-2
+MINGW64_OPENBLAS_VERSION = 0.3.13-1
 
 # pacman -Ss mingw-w64-x86_64-matio
 MINGW64_MATIO_VERSION = 1.5.17-2
 
 # Dependency of matio (and of the MinGW compiler)
 # pacman -Ss mingw-w64-x86_64-zlib
-MINGW64_ZLIB_VERSION = 1.2.11-7
+MINGW64_ZLIB_VERSION = 1.2.11-8
 
 # Dependency of matio
 # pacman -Ss mingw-w64-x86_64-hdf5
@@ -44,22 +44,22 @@ MINGW64_SZIP_VERSION = 2.1.1-2
 ## MinGW packages for the embedded compiler
 
 # pacman -Ss mingw-w64-x86_64-gcc$
-MINGW64_GCC_VERSION = 10.2.0-1
+MINGW64_GCC_VERSION = 10.2.0-6
 
 # pacman -Ss mingw-w64-x86_64-gmp
-MINGW64_GMP_VERSION = 6.2.0-1
+MINGW64_GMP_VERSION = 6.2.0-3
 
 # pacman -Ss mingw-w64-x86_64-binutils
-MINGW64_BINUTILS_VERSION = 2.35-1
+MINGW64_BINUTILS_VERSION = 2.35.1-3
 
 # pacman -Ss mingw-w64-x86_64-headers-git
-MINGW64_HEADERS_VERSION = 8.0.0.5966.f5da805f-1
+MINGW64_HEADERS_VERSION = 9.0.0.6090.ad98746a-1
 
 # pacman -Ss mingw-w64-x86_64-crt-git
-MINGW64_CRT_VERSION = 8.0.0.5966.f5da805f-1
+MINGW64_CRT_VERSION = 9.0.0.6090.ad98746a-1
 
 # pacman -Ss mingw-w64-x86_64-winpthreads-git
-MINGW64_WINPTHREADS_VERSION = 8.0.0.5906.c9a21571-1
+MINGW64_WINPTHREADS_VERSION = 9.0.0.6029.ecb4ff54-1
 
 # pacman -Ss mingw-w64-x86_64-zstd
 MINGW64_ZSTD_VERSION = 1.4.5-1
diff --git a/windows/dynare.nsi b/windows/dynare.nsi
index 41226695d08bbdd097f35b78001f8b713cbf1733..46198acee617f0299d10c13f60db8fd2ad934295 100644
--- a/windows/dynare.nsi
+++ b/windows/dynare.nsi
@@ -54,6 +54,9 @@ Section "Dynare core (preprocessor and M-files)"
  SetOutPath $INSTDIR\matlab
  File /r ..\matlab\*.m
 
+ SetOutPath $INSTDIR\preprocessor
+ File ..\preprocessor\src\dynare-preprocessor.exe
+
  SetOutPath $INSTDIR\matlab\preprocessor64
  File ..\matlab\preprocessor64\dynare_m.exe
 
@@ -141,6 +144,7 @@ Section "Uninstall"
  Delete $INSTDIR\license.txt
  Delete $INSTDIR\VERSION
  Rmdir /r $INSTDIR\matlab
+ Rmdir /r $INSTDIR\preprocessor
  Rmdir /r $INSTDIR\contrib
  Rmdir /r $INSTDIR\mex
  Rmdir /r $INSTDIR\dynare++