diff --git a/Makefile.am b/Makefile.am
index 735b98041ee4491492e89bd3fb2f964f92f01828..eea42e168f281d2f498152bbb1787e17ad3fbe0a 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -19,16 +19,15 @@ ACLOCAL_AMFLAGS = -I m4
 EXTRA_DIST = \
 	matlab \
 	contrib \
-	uncrustify.cfg \
 	NEWS \
 	license.txt \
-	dynare.el \
 	windows/dynare.nsi \
 	windows/mexopts-win32.bat \
 	windows/mexopts-win64.bat \
 	windows/README.txt \
 	osx \
-	examples
+	examples \
+	scripts
 
 dist-hook:
 	rm -rf `find $(distdir)/matlab $(distdir)/examples -name *~`
diff --git a/NEWS b/NEWS
index 5008450d29f5f125b82dc71cb0a441ae2451226e..280f285c5e0019f8ed8b190d8f276898fcaaabf6 100644
--- a/NEWS
+++ b/NEWS
@@ -1,3 +1,211 @@
+Announcement for Dynare 4.3.0 (on 2012-06-15)
+=============================================
+
+We are pleased to announce the release of Dynare 4.3.0. This major release adds
+new features and fixes various bugs.
+
+The Windows and Mac packages are already available for download at:
+
+ http://www.dynare.org/download/dynare-4.3
+
+The GNU/Linux packages should follow soon.
+
+All users are strongly encouraged to upgrade.
+
+The new release is compatible with MATLAB versions ranging from 7.0 (R14) to
+7.14 (R2012a) and with GNU Octave versions ranging from 3.2 to 3.6.
+
+Here is the list of the main user-visible changes:
+
+
+* New major algorithms:
+
+ - Nonlinear estimation with a particle filter based on a second order
+   approximation of the model, as in Fernández-Villaverde and Rubio-Ramírez
+   (2005); this is triggered by setting `order=2' in the `estimation' command
+
+ - Extended path solution method as in Fair and Taylor (1983); see the
+   `extended_path' command
+
+ - Support for Markov-Switching Structural Bayesian VARs (MS-SBVAR) along the
+   lines of Sims, Waggoner and Zha (2008) (see the dedicated section in the
+   reference manual)
+
+ - Optimal policy under discretion along the lines of Dennis (2007); see the
+   `discretionary_policy' command
+
+ - Identification analysis along the lines of Iskrev (2010); see the
+   `identification' command
+
+ - The Global Sensitivity Analysis toolbox (Ratto, 2008) is now part of the
+   official Dynare distribution
+
+
+* Other algorithmic improvements:
+
+ - Stochastic simulation and estimation can benefit from block decomposition
+   (with the `block' option of `model'; only at 1st order)
+
+ - Possibility of running smoother and filter on a calibrated model; see the
+   `calib_smoother' command
+
+ - Possibility of doing conditional forecast on a calibrated model; see the
+   `parameter_set=calibration' option of the `conditional_forecast' command
+
+ - The default algorithm for deterministic simulations has changed and is now
+   based on sparse matrices; the historical algorithm (Laffargue, Boucekkine
+   and Juillard) is still available under the `stack_solve_algo=6'option of the
+   `simul' command
+
+ - Possibility of using an analytic gradient for the estimation; see the
+   `analytic_derivation' option of the `estimation' command
+
+ - Implementation of the Nelder-Mead simplex based optimization routine for
+   computing the posterior mode; available under the `mode_compute=8' option of
+   the `estimation' command
+
+ - Implementation of the CMA Evolution Strategy algorithm for computing the
+   posterior mode; available under the `mode_compute=9' option of the
+   `estimation' command
+
+ - New solvers for Lyapunov equations which can accelerate the estimation of
+   large models; see the `lyapunov' option of the `estimation' command
+
+ - New solvers for Sylvester equations which can accelerate the resolution of
+   large models with block decomposition; see the `sylvester' option of the
+   `stoch_simul' and `estimation' commands
+
+ - The `ramsey_policy' command now displays the planner objective value
+   function under Ramsey policy and stores it in `oo_.planner_objective_value'
+
+ - Theoretical autocovariances are now computed when the `block' option is
+   present
+
+ - The `linear' option is now compatible with the `block' and `bytecode'
+   options
+
+ - The `loglinear' option now works with purely backward or forward models at
+   first order
+
+
+* New features in the user interface:
+
+ - New mathematical primitives allowed in model block: `abs()', `sign()'
+
+ - The behavior with respect to graphs has changed:
+
+    + By default, Dynare now displays graphs and saves them to disk in EPS
+      format only
+
+    + The format can be changed to PDF or FIG with the new `graph_format'
+      option
+
+    + It is possible to save graphs to disk without displaying them with the
+      new `nodisplay' option
+
+ - New `nocheck' option to the `steady' command: tells not to check the steady
+   state and accept values given by the user (useful for models with unit
+   roots)
+
+ - A series of deterministic shocks can be passed as a pre-defined vector in
+   the `values' statement of a `shocks' block
+
+ - New option `sub_draws' in the `estimation' command for controlling the
+   number of draws used in computing the posterior distributions of various
+   objects
+
+ - New macroprocessor command `@#ifdef' for testing if a macro-variable is
+   defined
+
+ - New option `irf_shocks' of the `stoch_simul' command, to allow IRFs to be
+   created only for certain exogenous variables
+
+ - In the parallel engine, possibility of assigning different weights to nodes
+   in the cluster and of creating clusters comprised of nodes with different
+   operating systems (see the relevant section in the reference manual)
+
+ - It is now possible to redefine a parameter in the `steady_state_model' block
+   (use with caution)
+
+ - New option `maxit' in the `simul' and `steady' commands to determine the
+   maximum number of iterations of the nonlinear solver
+
+ - New option `homotopy_force_continue' in the `steady' command to control the
+   behavior when a homotopy fails
+
+ - Possibility of globally altering the defaults of options by providing a file
+   in the `GlobalInitFile' field of the configuration file (use with caution)
+
+ - New option `nolog' to the `dynare' command line to avoid creating a logfile
+
+ - New option `-D' to the `dynare' command line with for defining
+   macro-variables
+
+
+* Miscellaneous changes:
+
+ - The `use_dll' option of `model' now creates a MEX file for the static model
+   in addition to that for the dynamic model
+
+ - The `unit_root_vars' command is now obsolete; use the `diffuse_filter'
+   option of the `estimation' command instead
+
+ - New option `--burn' to Dynare++ to discard initial simulation points
+
+ - New top-level MATLAB/Octave command `internals' for internal documentation
+   and unitary tests
+
+
+* Bugs and problems identified in version 4.2.5 and that have been fixed in
+  version 4.3.0:
+
+ - Backward models with the `loglinear' option were incorrectly handled
+
+ - Solving for hyperparameters of inverse gamma priors was sometimes crashing
+
+ - The deterministic solver for purely forward models was broken
+
+ - When running `estimation' or `identification' on models with non-diagonal
+   structural error covariance matrices, while not simultaneously estimating
+   the correlation between shocks (i.e. calibrating the correlation), the
+   off-diagonal elements were incorrectly handled or crashes were occuring
+
+ - When using the `prefilter' option, smoother plots were omitting the smoothed
+   observables
+
+ - In the rare case of entering and expression x as x^(alpha-1) with x being 0
+   in steady state and alpha being a parameter equal to 2, the Jacobian was
+   evaluating to 0 instead of 1
+
+ - Setting the prior for shock correlations was failing if a lower bound was not
+   explicitly specified
+
+
+* References:
+
+ - Dennis, Richard (2007): “Optimal Policy In Rational Expectations Models: New
+   Solution Algorithms,” Macroeconomic Dynamics, 11(1), 31–55
+
+ - Fair, Ray and John Taylor (1983): “Solution and Maximum Likelihood
+   Estimation of Dynamic Nonlinear Rational Expectation Models,” Econometrica,
+   51, 1169–1185
+
+ - Fernández-Villaverde, Jesús and Juan Rubio-Ramírez (2005): “Estimating
+   Dynamic Equilibrium Economies: Linear versus Nonlinear Likelihood,” Journal
+   of Applied Econometrics, 20, 891–910
+
+ - Iskrev, Nikolay (2010): “Local identification in DSGE models,” Journal of
+   Monetary Economics, 57(2), 189–202
+
+ - Ratto, Marco (2008): “Analysing DSGE models with global sensitivity
+   analysis'', Computational Economics, 31, 115–139
+
+ - Sims, Christopher A., Daniel F. Waggoner and Tao Zha (2008): “Methods for
+   inference in large multiple-equation Markov-switching models,” Journal of
+   Econometrics, 146, 255–274
+
+
+
 Announcement for Dynare 4.2.5 (on 2012-03-14)
 =============================================
 
diff --git a/configure.ac b/configure.ac
index 0125490ae5070d25dbd7c74ba8efdbf6d001f791..533df7061d9ed67dd7f4f66985321204cc7d421c 100644
--- a/configure.ac
+++ b/configure.ac
@@ -17,10 +17,10 @@ dnl
 dnl You should have received a copy of the GNU General Public License
 dnl along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-AC_PREREQ([2.61])
-AC_INIT([dynare], [4.3-unstable])
+AC_PREREQ([2.62])
+AC_INIT([dynare], [4.4-unstable])
 AC_CONFIG_SRCDIR([preprocessor/DynareMain.cc])
-AM_INIT_AUTOMAKE([-Wall -Werror foreign no-dist-gzip dist-xz tar-pax])
+AM_INIT_AUTOMAKE([1.11 -Wall -Werror foreign no-dist-gzip dist-xz tar-pax])
 
 AC_PROG_CC
 AC_PROG_CXX
diff --git a/contrib/ms-sbvar/switch_dw b/contrib/ms-sbvar/switch_dw
index d6ef21c52fbd37402dfb331d2f444602adaf5570..458d9a3f23927247a7b4c3967c4dceca108c40a8 160000
--- a/contrib/ms-sbvar/switch_dw
+++ b/contrib/ms-sbvar/switch_dw
@@ -1 +1 @@
-Subproject commit d6ef21c52fbd37402dfb331d2f444602adaf5570
+Subproject commit 458d9a3f23927247a7b4c3967c4dceca108c40a8
diff --git a/contrib/ms-sbvar/utilities_dw b/contrib/ms-sbvar/utilities_dw
index 21e0aed46bdc905df098efe6bb7fca464b7d7fa6..caaf4b6807d231d1f2cf611e6b9dc8afdc5dd2cf 160000
--- a/contrib/ms-sbvar/utilities_dw
+++ b/contrib/ms-sbvar/utilities_dw
@@ -1 +1 @@
-Subproject commit 21e0aed46bdc905df098efe6bb7fca464b7d7fa6
+Subproject commit caaf4b6807d231d1f2cf611e6b9dc8afdc5dd2cf
diff --git a/doc/dynare.texi b/doc/dynare.texi
index 77debc657ff5e17a5fd5c079062776642967927d..014b0dd412d3c02c179144584e03b5d256d138f6 100644
--- a/doc/dynare.texi
+++ b/doc/dynare.texi
@@ -76,6 +76,7 @@ A copy of the license can be found at @uref{http://www.gnu.org/licenses/fdl.txt}
 @subtitle Reference Manual, version @value{VERSION}
 @author Stéphane Adjemian
 @author Houtan Bastani
+@author Frédéric Karamé
 @author Michel Juillard
 @author Junior Maih
 @author Ferhat Mihoubi
@@ -216,6 +217,7 @@ Typical usages
 
 The Configuration File
 
+* Dynare Configuration::        
 * Parallel Configuration::      
 
 @end detailmenu
@@ -461,7 +463,7 @@ Dynare will be installed under @file{/usr/share/dynare} and
 @subsection On Mac OS X
 
 Execute the automated installer called
-@file{dynare-4.@var{x}.@var{y}-macosx-10.5+10.6.pkg} (where
+@file{dynare-4.@var{x}.@var{y}.pkg} (where
 4.@var{x}.@var{y} is the version number), and follow the
 instructions. The default installation directory is
 @file{/Applications/Dynare/4.@var{x}.@var{y}}.
@@ -1465,8 +1467,9 @@ used outside. A model local variable declaration looks like:
 
 @item linear
 Declares the model as being linear. It spares oneself from having to
-declare initial values for computing the steady state, and it sets
-automatically @code{order=1} in @code{stoch_simul}.
+declare initial values for computing the steady state of a stationary
+linear model. This options can't be used with non-linear models, it will
+NOT trigger linearization of the model.
 
 @item use_dll
 @anchor{use_dll}
@@ -1483,9 +1486,10 @@ in those cases.}
 @item block
 @anchor{block}
 Perform the block decomposition of the model, and exploit it in
-computations. See
+computations (steady-state, deterministic simulation, 
+stochastic simulation with first order approximation and estimation). See
 @uref{http://www.dynare.org/DynareWiki/FastDeterministicSimulationAndSteadyStateComputation,Dynare
-wiki} for details on the algorithm.
+wiki} for details on the algorithms used in deterministic simulation and steady-state computation.
 
 @item bytecode
 @anchor{bytecode}
@@ -1776,7 +1780,7 @@ implemented in @code{simul}.
 For this last reason, it necessary to provide values for all the
 endogenous variables in an @code{initval} block (even though,
 theoretically, initial conditions are only necessary for lagged
-variables). If some exogenous variables are not mentionned in the
+variables). If some variables, endogenous or exogenous, are not mentionned in the
 @code{initval} block, a zero value is assumed.
 
 Note that if the @code{initval} block is immediately followed by a
@@ -1851,7 +1855,7 @@ for the non-linear solver implemented in @code{simul}.
 For this last reason, it necessary to provide values for all the
 endogenous variables in an @code{endval} block (even though,
 theoretically, initial conditions are only necessary for forward
-variables). If some exogenous variables are not mentionned in the
+variables). If some variables, endogenous or exogenous, are not mentionned in the
 @code{endval} block, a zero value is assumed.
 
 Note that if the @code{endval} block is immediately followed by a
@@ -1921,7 +1925,8 @@ Variables not initialized in the @code{histval} block are assumed to
 have a value of zero at period 0 and before. Note that this behavior
 differs from the case where there is no @code{histval} block, where all
 variables are initialized at their steady state value at period 0 and
-before.
+before (except when a @code{steady} command doesn't follow an
+@code{initval} block).
 
 @examplehead
 
@@ -2566,8 +2571,9 @@ function returning several arguments:
 [ @var{VARIABLE_NAME}, @var{VARIABLE_NAME}@dots{} ] = @var{EXPRESSION};
 @end example
 
-Dynare will automatically generate a steady state file using the
-information provided in this block.
+Dynare will automatically generate a steady state file (of the form
+@file{@var{FILENAME}_steadystate2.m}) using the information provided in
+this block.
 
 @customhead{Steady state file for deterministic models}
 
@@ -2666,6 +2672,7 @@ command.
 @end defvr
 
 @deffn Command model_info ;
+@deffnx Command model_info (@var{OPTIONS}@dots{});
 
 @descriptionhead
 
@@ -2730,6 +2737,22 @@ to @samp{SIMPLE} if the block has only one equation. If several
 equation appears in the block, @var{x} is equal to @samp{COMPLETE}.
 @end table
 
+@optionshead
+
+@table @code
+
+@item 'static'
+Prints out the block decomposition of the static model. 
+Without 'static' option model_info displays the block decomposition 
+of the dynamic model.
+
+@item 'incidence'
+Displays the gross incidence matrix and the reordered incidence matrix 
+of the block decomposed model.
+
+@end table
+
+
 @end deffn
 
 @deffn Command print_bytecode_dynamic_model ;
@@ -2795,7 +2818,7 @@ Algorithm used for computing the solution. Possible values are:
 
 @item 0
 Newton method to solve simultaneously all the equations for every
-period, see @cite{Juillard (1996)} (Default).
+period, using sparse matrices (Default).
 
 @item 1
 Use a Newton algorithm with a sparse LU solver at each iteration
@@ -2821,6 +2844,13 @@ declaration}).
 Use a Newton algorithm with a sparse Gaussian elimination (SPE) solver
 at each iteration (requires @code{bytecode} option, @pxref{Model
 declaration}).
+
+@item 6
+Use the historical algorithm proposed in @cite{Juillard (1996)}: it is
+slower than @code{stack_solve_algo=0}, but may be less memory consuming
+on big models (not available with @code{bytecode} and/or @code{block}
+options).
+
 @end table
 
 @item markowitz = @var{DOUBLE}
@@ -2849,7 +2879,8 @@ The simulated endogenous variables are available in global matrix
 @defvr {MATLAB/Octave variable} oo_.endo_simul
 This variable stores the result of a deterministic simulation
 (computed by @code{simul}) or of a stochastic simulation (computed by
-@code{stoch_simul} with the @code{periods} option).
+@code{stoch_simul} with the @code{periods} option or by
+@code{extended_path}).
 
 The variables are arranged row by row, in order of declaration (as in
 @code{M_.endo_names}). Note that this variable also contains initial
@@ -2857,16 +2888,38 @@ and terminal conditions, so it has more columns than the value of
 @code{periods} option.
 @end defvr
 
+@anchor{oo_.exo_simul}
+@defvr {MATLAB/Octave variable} oo_.exo_simul
+This variable stores the path of exogenous variables during a
+simulation (computed by @code{simul}, @code{stoch_simul} or
+@code{extended_path}).
+
+The variables are arranged in columns, in order of declaration (as in
+@code{M_.endo_names}). Periods are in rows. Note that this convention
+regarding columns and rows is the opposite of the convention for
+@code{oo_.endo_simul}!
+
+@end defvr
+
 @node Stochastic solution and simulation
 @section Stochastic solution and simulation
 
 In a stochastic context, Dynare computes one or several simulations
-corresponding to a random draw of the shocks. Dynare uses a Taylor
+corresponding to a random draw of the shocks.
+
+The main algorithm for solving stochastic models relies on a Taylor
 approximation, up to third order, of the expectation functions (see
 @cite{Judd (1996)}, @cite{Collard and Juillard (2001a)}, @cite{Collard
 and Juillard (2001b)}, and @cite{Schmitt-Grohé and Uríbe (2004)}). The
 details of the Dynare implementation of the first order solution are
-given in @cite{Villemot (2011)}.
+given in @cite{Villemot (2011)}. Such a solution is computed using
+the @code{stoch_simul} command.
+
+As an alternative, it is possible to compute a simulation to a
+stochastic model using the @emph{extended path} method presented by
+@cite{Fair and Taylor (1983)}. This method is especially useful when
+there are strong nonlinearities or binding constraints. Such a
+solution is computed using the @code{extended_path} command.
 
 @menu
 * Computing the stochastic solution::  
@@ -2928,6 +2981,8 @@ The covariance matrix of the shocks is specified with the
 When a list of @var{VARIABLE_NAME} is specified, results are displayed
 only for these variables.
 
+The @code{stoch_simul} command with a first order approximation can benefit from the block decomposition of the model (@pxref{block}).
+
 @optionshead
 
 @table @code
@@ -2962,10 +3017,6 @@ The exogenous variables for which to compute IRFs. Default: all.
 Requests the computation of normalized IRFs in percentage of the
 standard error of each shock.
 
-@item linear
-Indicates that the original model is linear (put it rather in the
-@code{model} command).
-
 @item nocorr
 Don't print the correlation matrix (printing them is the default).
 
@@ -2977,8 +3028,22 @@ them is the default).
 Don't print moments of the endogenous variables (printing them is the
 default).
 
-@item nograph.
-Doesn't do the graphs. Useful for loops.
+@item nograph
+@anchor{nograph} Do not create graphs (which implies that they are not
+saved to the disk nor displayed). If this option is not used, graphs
+will be saved to disk (to the format specified by @code{graph_format}
+option) and displayed to screen (unless @code{nodisplay} option is
+used).
+
+@item nodisplay
+@anchor{nodisplay} Do not display the graphs, but still save them to disk
+(unless @code{nograph} is used).
+
+@item graph_format = @var{FORMAT}
+@anchor{graph_format}
+Specify the file format for graphs saved to disk. Possible values are
+@code{eps} (the default), @code{pdf} and @code{fig} (the latter is not
+available under Octave).
 
 @item noprint
 Don't print anything. Useful for loops.
@@ -2992,7 +3057,8 @@ Order of Taylor approximation. Acceptable values are @code{1},
 @code{2} and @code{3}. Note that for third order,
 @code{k_order_solver} option is implied and only empirical moments are
 available (you must provide a value for @code{periods}
-option). Default: @code{2}.
+option). Default: @code{2} (except after an @code{estimation} command,
+in which case the default is the value used for the estimation).
 
 @item k_order_solver
 @anchor{k_order_solver}
@@ -3009,7 +3075,9 @@ periods to use in the simulations. Values of the @code{initval} block,
 possibly recomputed by @code{steady}, will be used as starting point
 for the simulation. The simulated endogenous variables are made
 available to the user in a vector for each variable and in the global
-matrix @code{oo_.endo_simul} (@pxref{oo_.endo_simul}). Default: @code{0}.
+matrix @code{oo_.endo_simul} (@pxref{oo_.endo_simul}). The simulated
+exogenous variables are made available in @code{oo_.exo_simul}
+(@pxref{oo_.exo_simul}). Default: @code{0}.
 
 @item qz_criterium = @var{DOUBLE}
 Value used to split stable from unstable eigenvalues in reordering the
@@ -3022,6 +3090,13 @@ problems. Default: @code{1.000001} (except when estimating with
 Number of simulated series used to compute the IRFs. Default: @code{1}
 if @code{order}=@code{1}, and @code{50} otherwise.
 
+@item simul_replic = @var{INTEGER}
+Number of series to simulate when empirical moments are requested
+(@i{i.e.} @code{periods} > 0). Note that if this option is greater
+than @code{1}, the additional series will not be used for computing
+the empirical moments but will simply be saved in binary form to the
+file @file{@var{FILENAME}_simul}. Default: @code{1}.
+
 @item solve_algo = @var{INTEGER}
 @xref{solve_algo}, for the possible values and their meaning.
 
@@ -3090,6 +3165,42 @@ Default value is @code{default}
 @anchor{sylvester_fixed_point_tol}
 It is the convergence criterion used in the fixed point sylvester solver. Its default value is 1e-12.
 
+@item dr = @var{OPTION}
+@anchor{dr}
+Determines the method used to compute the decision rule. Possible values for @code{@var{OPTION}} are:
+
+@table @code
+
+@item default
+Uses the default method to compute the decision rule based on the generalized Schur decomposition
+(see @cite{Villemot (2011)} for more information).
+
+@item cycle_reduction
+Uses the cycle reduction algorithm to solve the polynomial equation for retrieving the coefficients
+associated to the endogenous variables in the decision rule. This method is faster than the @code{default} one for large scale models.
+
+@item logarithmic_reduction
+Uses the logarithmic reduction algorithm to solve the polynomial equation for retrieving the coefficients
+associated to the endogenous variables in the decision rule. This method is in general slower than the @code{cycle_reduction}.
+
+@end table
+
+@noindent
+Default value is @code{default}
+
+@item dr_cycle_reduction_tol = @var{DOUBLE}
+@anchor{dr_cycle_reduction_tol}
+The convergence criterion used in the cycle reduction algorithm. Its default value is 1e-7.
+
+@item dr_logarithmic_reduction_tol = @var{DOUBLE}
+@anchor{dr_logarithmic_reduction_tol}
+The convergence criterion used in the logarithmic reduction algorithm. Its default value is 1e-12.
+
+@item dr_logarithmic_reduction_maxiter = @var{INTEGER}
+@anchor{dr_logarithmic_reduction_maxiter}
+The maximum number of iterations used in the logarithmic reduction algorithm. Its default value is 100.
+
+
 @end table
 
 @outputhead
@@ -3126,10 +3237,10 @@ with a single stochastic shock @code{e}, with a standard error of
 @customhead{Example 2}
 
 @example
-stoch_simul(linear,irf=60) y k;
+stoch_simul(irf=60) y k;
 @end example
 
-Performs the simulation of a linear model and displays impulse
+Performs the simulation of a model and displays impulse
 response functions on 60 periods for variables @code{y} and @code{k}.
 @end deffn
 
@@ -3207,6 +3318,37 @@ variables of the model as function of the previous state of the model and
 shocks oberved at the beginning of the period. The decision rules are stored
 in the structure @code{oo_.dr} which is described below.
 
+@deffn Command extended_path ;
+@deffnx Command extended_path (@var{OPTIONS}@dots{}) ;
+
+@descriptionhead
+
+@code{extended_path} solves a stochastic (@i{i.e.} rational
+expectations) model, using the @emph{extended path} method presented
+by @cite{Fair and Taylor (1983)}.
+
+This function first computes a random path for the exogenous variables
+(stored in @code{oo_.exo_simul}, @pxref{oo_.exo_simul}) and then
+computes the corresponding path for endogenous variables, taking the
+steady state as starting point. The result of the simulation is stored
+in @code{oo_.endo_simul} (@pxref{oo_.endo_simul}).
+
+@optionshead
+
+@table @code
+
+@item periods = @var{INTEGER}
+The number of periods for which the simulation is to be computed. No
+default value, mandatory option.
+
+@item solver_periods = @var{INTEGER}
+The number of periods used to compute the approximate solution
+at every iteration of the algorithm. Default: @code{200}.
+
+@end table
+
+@end deffn
+
 @node Typology and ordering of variables
 @subsection Typology and ordering of variables
 
@@ -3462,6 +3604,10 @@ Note that in order to avoid stochastic singularity, you must have at
 least as many shocks or measurement errors in your model as you have
 observed variables.
 
+The estimation using a first order approximation can benefit from the block 
+decomposition of the model (@pxref{block}).
+
+
 @deffn Command varobs @var{VARIABLE_NAME}@dots{};
 
 @descriptionhead
@@ -3815,8 +3961,13 @@ result in absurd prior densities.
 Default value is @code{1}.
 
 @item nograph
-@anchor{nograph}
-No graphs should be plotted
+@xref{nograph}.
+
+@item nodisplay
+@xref{nodisplay}.
+
+@item graph_format = @var{FORMAT}
+@xref{graph_format}.
 
 @item lik_init = @var{INTEGER}
 @anchor{lik_init}
@@ -4061,8 +4212,13 @@ variables.
 @vindex oo_.forecast
 @anchor{forecast} Computes the posterior distribution of a forecast on
 @var{INTEGER} periods after the end of the sample used in
-estimation. The result is stored in variable @code{oo_.forecast}
-(@pxref{Forecasting})
+estimation. If no Metropolis-Hastings is computed, the result is
+stored in variable @code{oo_.forecast} and corresponds to the forecast
+at the posterior mode. If a Metropolis-Hastings is computed, the
+distribution of forecasts is stored in variables
+@code{oo_.PointForecast} and
+@code{oo_.MeanForecast}. @xref{Forecasting}) for a description of
+these variables.
 
 @item tex
 @anchor{tex} Requests the printing of results and graphs in TeX tables
@@ -4134,7 +4290,12 @@ this covariance matrix. Default is @code{1}.
 @xref{solve_algo}.
 
 @item order = @var{INTEGER}
-@xref{order}.
+Order of approximation, either @code{1} or @code{2}. When equal to
+@code{2}, the likelihood is evaluated with a particle filter based on
+a second order approximation of the model (see
+@cite{Fernandez-Villaverde and Rubio-Ramirez (2005)}).  Default is
+@code{1}, ie the lilkelihood of the linearized model is evaluated
+using a standard Kalman filter.
 
 @item irf = @var{INTEGER}
 @xref{irf}. Only used if @ref{bayesian_irf} is passed.
@@ -4189,6 +4350,10 @@ This is the convergence criterion used in the fixed point lyapunov solver. Its d
 @anchor{lyapunov_doubling_tol}
 This is the convergence criterion used in the doubling algorithm to solve the lyapunov equation. Its default value is 1e-16.
 
+@item analytic_derivation
+Triggers estimation with analytic gradient. The final hessian is also
+computed analytically. Only works for stationary models without
+missing observations.
 
 @end table
 
@@ -4529,7 +4694,8 @@ This command computes the smoothed variables (and possible the filtered
 variables) on a @code{calibrated} model.
 
 A datafile must be provided, and the observable variables declared with
-@code{varobs}.
+@code{varobs}. The smoother is based on a first-order approximation of
+the model.
 
 @vindex oo_.SmoothedVariables
 @vindex oo_.SmoothedShocks
@@ -4561,7 +4727,7 @@ more details.
 @section Forecasting
 
 On a calibrated model, forecasting is done using the @code{forecast}
-command. On an estimated command, use the @code{forecast} option of
+command. On an estimated model, use the @code{forecast} option of
 @code{estimation} command.
 
 It is also possible to compute forecasts on a calibrated or estimated
@@ -4607,7 +4773,14 @@ Number of periods of the forecast. Default: @code{40}
 interval. Default: @code{0.90}
 
 @item nograph
-Don't display graphics.
+@xref{nograph}.
+
+@item nodisplay
+@xref{nodisplay}.
+
+@item graph_format = @var{FORMAT}
+@xref{graph_format}.
+
 @end table
 
 @customhead{Initial Values}
@@ -4642,8 +4815,9 @@ forecast;
 
 @defvr {MATLAB/Octave variable} oo_.forecast
 Variable set by the @code{forecast} command, or by the
-@code{estimation} command if used with the @code{forecast}
-option. Fields are of the form:
+@code{estimation} command if used with the @code{forecast} option and
+if no Metropolis-Hastings has been computed (in that case, the
+forecast is computed for the posterior mode). Fields are of the form:
 @example
 @code{oo_.forecast.@var{FORECAST_MOMENT}.@var{VARIABLE_NAME}}
 @end example
@@ -4679,6 +4853,37 @@ Standard deviation of the posterior distribution of forecasts
 
 @end defvr
 
+
+@defvr {MATLAB/Octave variable} oo_.PointForecast
+Set by the @code{estimation} command, if it is used with the
+@code{forecast} option and if either @code{mh_replic > 0} or
+@code{load_mh_file} option is used.
+
+Contains the distribution of forecasts taking into account the
+uncertainty about both parameters and shocks.
+
+Fields are of the form:
+@example
+@code{oo_.PointForecast.@var{MOMENT_NAME}.@var{VARIABLE_NAME}}
+@end example
+@end defvr
+
+@defvr {MATLAB/Octave variable} oo_.MeanForecast
+Set by the @code{estimation} command, if it is used with the
+@code{forecast} option and if either @code{mh_replic > 0} or
+@code{load_mh_file} option is used.
+
+Contains the distribution of forecasts where the uncertainty about
+shocks is averaged out. The distribution of forecasts therefore only
+represents the uncertainty about parameters.
+
+Fields are of the form:
+@example
+@code{oo_.MeanForecast.@var{MOMENT_NAME}.@var{VARIABLE_NAME}}
+@end example
+@end defvr
+
+
 @deffn Command conditional_forecast (@var{OPTIONS}@dots{}) [@var{VARIABLE_NAME}@dots{}];
 
 @descriptionhead
@@ -4861,7 +5066,7 @@ This block specifies quadratic objectives for optimal policy problems
 More precisely, this block specifies the nonzero elements of the
 quadratic weight matrices for the objectives in @code{osr}.
 
-A element of the diagonal of the weight matrix is given by a line of
+An element of the diagonal of the weight matrix is given by a line of
 the form:
 @example
 @var{VARIABLE_NAME} @var{EXPRESSION};
@@ -4922,7 +5127,7 @@ This command generates all the output variables of @code{stoch_simul}.
 In addition, it stores the value of planner objective function under
 Ramsey policy in @code{oo_.planner_objective_value}.
 
-@customhead{Steay state}
+@customhead{Steady state}
 
 Dynare takes advantage of the fact that the Lagrange multipliers appear
 linearly in the equations of the steady state of the model under optimal
@@ -4933,13 +5138,14 @@ endogenous variables.
 It greatly facilitates the computation, if the user provides an
 analytical solution for the steady state (in @code{steady_state_model}
 block or in a @code{@dots{}_steadystate.m} file). In this case, it is
-necessary to provide a steady state solution CONDITIONAL on the value of
-the instruments in the optimal policy problem and declared with option
-@code{instruments}. Note that choosing the instruments is partly a
-matter of interpretation and you can choose instruments that are handy
-from a mathematical point of view but different from the instruments you
-would refer to in the analysis of the paper. Typical example is choosing
-inflation or nominal interest rate as an instrument.
+necessary to provide a steady state solution CONDITIONAL on the value
+of the instruments in the optimal policy problem and declared with
+option @code{instruments}. Note that choosing the instruments is
+partly a matter of interpretation and you can choose instruments that
+are handy from a mathematical point of view but different from the
+instruments you would refer to in the analysis of the paper. A typical
+example is choosing inflation or nominal interest rate as an
+instrument.
 
 
 @end deffn
@@ -4951,7 +5157,8 @@ inflation or nominal interest rate as an instrument.
 @descriptionhead
 
 This command computes an approximation of the optimal policy under
-discretion
+discretion. The algorithm implemented is essentially an LQ solver, and
+is described by @cite{Dennis (2007)}.
 
 @optionshead
 
@@ -4963,6 +5170,9 @@ This command accepts the same options than @code{ramsey_policy}, plus:
 Sets the tolerance level used to assess convergence of the solution
 algorithm. Default: @code{1e-7}.
 
+@item solve_maxit = @var{INTEGER}
+Maximum number of iterations. Default: @code{3000}.
+
 @end table
 
 @end deffn
@@ -5178,6 +5388,8 @@ command. These are:
 @item @code{prefilter}
 @item @code{presample}
 @item @code{nograph}
+@item @code{nodisplay}
+@item @code{graph_format}
 @item @code{conf_sig}
 @item @code{loglinear}
 @item @code{mode_file}
@@ -5493,6 +5705,12 @@ Critical value for correlation @math{\rho}: plot couples of parmaters with
 @item nograph
 @xref{nograph}.
 
+@item nodisplay
+@xref{nodisplay}.
+
+@item graph_format = @var{FORMAT}
+@xref{graph_format}.
+
 @item conf_sig = @var{DOUBLE}
 @xref{conf_sig}.
 
@@ -5605,6 +5823,15 @@ Specify the parameter set to use. Default: @code{prior_mean}
 @item kalman_algo = @var{INTEGER}
 @xref{kalman_algo}.
 
+@item nograph
+@xref{nograph}.
+
+@item nodisplay
+@xref{nodisplay}.
+
+@item graph_format = @var{FORMAT}
+@xref{graph_format}.
+
 @end table
 
 @end deffn
@@ -6351,8 +6578,8 @@ line. The main directives are:
 @item
 @code{@@#define}, for defining a macro-processor variable,
 @item
-@code{@@#if}, @code{@@#ifdef}, @code{@@#else}, @code{@@#endif} for
-conditional statements,
+@code{@@#if}, @code{@@#ifdef}, @code{@@#ifndef}, @code{@@#else},
+@code{@@#endif} for conditional statements,
 @item
 @code{@@#for}, @code{@@#endfor} for constructing loops.
 @end itemize
@@ -6495,10 +6722,11 @@ end;
 
 @deffn {Macro directive} @@#if @var{MACRO_EXPRESSION}
 @deffnx {Macro directive} @@#ifdef @var{MACRO_VARIABLE}
+@deffnx {Macro directive} @@#ifndef @var{MACRO_VARIABLE}
 @deffnx {Macro directive} @@#else
 @deffnx {Macro directive} @@#endif
 Conditional inclusion of some part of the @file{.mod} file.
-The lines between @code{@@#if} or @code{@@#ifdef} and the next
+The lines between @code{@@#if}, @code{@@#ifdef} or @code{@@#ifndef} and the next
 @code{@@#else} or @code{@@#endif} is executed only if the condition
 evaluates to a non-null integer. The @code{@@#else} branch is optional
 and, if present, is only evaluated if the condition evaluates to
@@ -6537,6 +6765,21 @@ model;
 end;
 @end example
 
+Choose between two alternative monetary policy rules using a
+macro-variable. As @code{linear_mon_pol} was not previously defined in
+this example, the first equation will be chosen:
+
+@example
+model;
+@@#ifndef linear_mon_pol
+  i = w*i(-1) + (1-w)*i_ss + w2*(pie-piestar);
+@@#else
+  i = i(-1)^w * i_ss^(1-w) * (pie/piestar)^w2;
+@@#endif
+...
+end;
+@end example
+
 @end deffn
 
 @deffn {Macro directive} @@#for @var{MACRO_VARIABLE} in @var{MACRO_EXPRESSION}
@@ -6876,6 +7119,15 @@ function for more information.
 
 @end deffn
 
+@anchor{dynare_version}
+@deffn {MATLAB/Octave command} dynare_version ;
+
+Output the version of Dynare that is currently being used (@i{i.e.}
+the one that is highest on the MATLAB/Octave path).
+
+@end deffn
+
+
 @node The Configuration File
 @chapter The Configuration File
 
@@ -6932,9 +7184,43 @@ Is @code{true} or @code{false}.
 @end table
 
 @menu
+* Dynare Configuration::        
 * Parallel Configuration::      
 @end menu
 
+@node Dynare Configuration
+@section Dynare Configuration
+
+This section explains how to configure Dynare for general
+processing. Currently, there is only one option available.
+
+@deffn {Configuration block} [hooks]
+
+@descriptionhead
+
+The @code{[hooks]} block can be used to specify configuration options
+that will be used when running dynare.
+
+@optionshead
+
+@table @code
+
+@item GlobalInitFile = @var{PATH_AND_FILE}
+The location of the global initialization file to be run at the end of
+@code{global_initialization.m}
+
+@end table
+
+@examplehead
+
+@example
+[hooks]
+GlobalInitFile = /home/usern/dynare/myInitFile.m
+
+@end example
+
+@end deffn
+
 @node Parallel Configuration
 @section Parallel Configuration
 
@@ -7247,89 +7533,99 @@ Cycles: The Cycle is the Trend,'' @i{NBER Working Paper}, 10734
 @item
 Backus, David K., Patrick J. Kehoe, and Finn E. Kydland (1992):
 ``International Real Business Cycles,'' @i{Journal of Political
-Economy}, 100(4), 745--775.
+Economy}, 100(4), 745--775
 
 @item
 Boucekkine, Raouf (1995): ``An alternative methodology for solving
 nonlinear forward-looking models,'' @i{Journal of Economic Dynamics
-and Control}, 19, 711--734.
+and Control}, 19, 711--734
 
 @item
-Collard, Fabrice (2001): ``Stochastic simulations with Dynare: A practical guide''.
+Collard, Fabrice (2001): ``Stochastic simulations with Dynare: A practical guide''
 
 @item
 Collard, Fabrice and Michel Juillard (2001a): ``Accuracy of stochastic
 perturbation methods: The case of asset pricing models,'' @i{Journal
-of Economic Dynamics and Control}, 25, 979--999.
+of Economic Dynamics and Control}, 25, 979--999
 
 @item
 Collard, Fabrice and Michel Juillard (2001b): ``A Higher-Order Taylor
 Expansion Approach to Simulation of Stochastic Forward-Looking Models
 with an Application to a Non-Linear Phillips Curve,'' @i{Computational
-Economics}, 17, 125--139.
+Economics}, 17, 125--139
+
+@item
+Dennis, Richard (2007): ``Optimal Policy In Rational Expectations
+Models: New Solution Algorithms,'' @i{Macroeconomic Dynamics}, 11(1),
+31--55
 
 @item
 Durbin, J. and S. J. Koopman (2001), @i{Time Series Analysis by State
-Space Methods}, Oxford University Press.
+Space Methods}, Oxford University Press
 
 @item
 Fair, Ray and John Taylor (1983): ``Solution and Maximum Likelihood
 Estimation of Dynamic Nonlinear Rational Expectation Models,''
-@i{Econometrica}, 51, 1169--1185.
+@i{Econometrica}, 51, 1169--1185
 
 @item
-Fernandez-Villaverde, Jesus and Juan Rubio-Ramirez (2004): ``Comparing
+Fernández-Villaverde, Jesús and Juan Rubio-Ramírez (2004): ``Comparing
 Dynamic Equilibrium Economies to Data: A Bayesian Approach,''
-@i{Journal of Econometrics}, 123, 153--187.
+@i{Journal of Econometrics}, 123, 153--187
+
+@item
+Fernández-Villaverde, Jesús and Juan Rubio-Ramírez (2005): ``Estimating
+Dynamic Equilibrium Economies: Linear versus Nonlinear Likelihood,''
+@i{Journal of Applied Econometrics}, 20, 891--910
 
 @item
 Ireland, Peter (2004): ``A Method for Taking Models to the Data,''
-@i{Journal of Economic Dynamics and Control}, 28, 1205--26.
+@i{Journal of Economic Dynamics and Control}, 28, 1205--26
 
 @item
-Iskrev, Nikolay (2010). ``Local identification in DSGE models,''
-@i{Journal of Monetary Economics}, 57(2), 189--202.
+Iskrev, Nikolay (2010): ``Local identification in DSGE models,''
+@i{Journal of Monetary Economics}, 57(2), 189--202
 
 @item
 Judd, Kenneth (1996): ``Approximation, Perturbation, and Projection
 Methods in Economic Analysis'', in @i{Handbook of Computational
 Economics}, ed. by Hans Amman, David Kendrick, and John Rust, North
-Holland Press, 511--585.
+Holland Press, 511--585
 
 @item
 Juillard, Michel (1996): ``Dynare: A program for the resolution and
 simulation of dynamic models with forward variables through the use of
-a relaxation algorithm,'' CEPREMAP, @i{Couverture Orange}, 9602.
+a relaxation algorithm,'' CEPREMAP, @i{Couverture Orange}, 9602
 
 @item
 Kim, Jinill, Sunghyun Kim, Ernst Schaumburg, and Christopher A. Sims
 (2008): ``Calculating and using second-order accurate solutions of
 discrete time dynamic equilibrium models,'' @i{Journal of Economic
-Dynamics and Control}, 32(11), 3397--3414.
+Dynamics and Control}, 32(11), 3397--3414
 
 @item
 Koopman, S. J. and J. Durbin (2003): ``Filtering and Smoothing of
 State Vector for Diffuse State Space Models,'' @i{Journal of Time
-Series Analysis}, 24(1), 85--98.
+Series Analysis}, 24(1), 85--98
 
 @item
 Laffargue, Jean-Pierre (1990): ``Résolution d'un modèle
 macroéconomique avec anticipations rationnelles'', @i{Annales
-d'Économie et Statistique}, 17, 97--119.
+d'Économie et Statistique}, 17, 97--119
 
 @item
 Lubik, Thomas and Frank Schorfheide (2007): ``Do Central Banks Respond
 to Exchange Rate Movements? A Structural Investigation,'' @i{Journal
-of Monetary Economics}, 54(4), 1069--1087.
+of Monetary Economics}, 54(4), 1069--1087
 
 @item
 Mancini-Griffoli, Tommaso (2007): ``Dynare User Guide: An introduction
-to the solution and estimation of DSGE models''.
+to the solution and estimation of DSGE models''
 
 @item
 Pearlman, Joseph, David Currie, and Paul Levine (1986): ``Rational
 expectations models with partial information,'' @i{Economic
-Modelling}, 3(2), 90--105.
+Modelling}, 3(2), 90--105
 
 @item
 Rabanal, Pau and Juan Rubio-Ramirez (2003): ``Comparing New Keynesian
@@ -7337,28 +7633,28 @@ Models of the Business Cycle: A Bayesian Approach,'' Federal Reserve
 of Atlanta, @i{Working Paper Series}, 2003-30.
 
 @item
-Ratto, Marco (2008): ``Analysing dsge models with global sensitivity
-analysis''. @i{Computational Economics}, 31, 115--139.
+Ratto, Marco (2008): ``Analysing DSGE models with global sensitivity
+analysis'', @i{Computational Economics}, 31, 115--139
 
 @item
 Schorfheide, Frank (2000): ``Loss Function-based evaluation of DSGE
-models,'' @i{Journal of Applied Econometrics}, 15(6), 645--670.
+models,'' @i{Journal of Applied Econometrics}, 15(6), 645--670
 
 @item
 Schmitt-Grohé, Stephanie and Martin Uríbe (2004): ``Solving Dynamic
 General Equilibrium Models Using a Second-Order Approximation to the
 Policy Function,'' @i{Journal of Economic Dynamics and Control},
-28(4), 755--775.
+28(4), 755--775
 
 @item
 Sims, Christopher A., Daniel F. Waggoner and Tao Zha (2008): ``Methods for
 inference in large multiple-equation Markov-switching models,''
-@i{Journal of Econometrics}, 146, 255--274.
+@i{Journal of Econometrics}, 146, 255--274
 
 @item
 Smets, Frank and Rafael Wouters (2003): ``An Estimated Dynamic
 Stochastic General Equilibrium Model of the Euro Area,'' @i{Journal of
-the European Economic Association}, 1(5), 1123--1175.
+the European Economic Association}, 1(5), 1123--1175
 
 @item
 Villemot, Sébastien (2011): ``Solving rational expectations models at
diff --git a/doc/gsa/gsa.tex b/doc/gsa/gsa.tex
index 3e9bcdbdf30a957000b82836b69736b6662b492f..5950e9619ee3e2adbbaa42f94c750fc4ae8c1ec2 100644
--- a/doc/gsa/gsa.tex
+++ b/doc/gsa/gsa.tex
@@ -32,13 +32,13 @@
 
 \author{Marco Ratto\\
 European Commission, Joint Research Centre \\
-TP361, IPSC, via E. Fermi 1\\21020 Ispra
+TP361, IPSC, \\21027 Ispra
 (VA) Italy\\
-\texttt{marco.ratto@jrc.it}
+\texttt{marco.ratto@jrc.ec.europa.eu}
 \thanks{The author gratefully thanks Christophe Planas, Kenneth Judd, Michel Juillard,
 Alessandro Rossi, Frank Schorfheide and the participants to the
 Courses on Global Sensitivity Analysis for Macroeconomic
-Models (Ispra, 2006-2007-2008) for interesting discussions and
+Models (Ispra, 2006-2007-2008-2010) for interesting discussions and
 helpful suggestions.}}
 
 %%% To have the current date inserted, use \date{\today}:
@@ -123,7 +123,10 @@ beforehand}.
           \verb"morris_ntra"& 20& number of trajectories in Morris design\\
                 \verb"ppost"& 0& 0 = don't use Metropolis posterior sample\\
                             &  & 1 = use Metropolis posterior sample: this \\
-                            &  & \hspace{0.5 cm} overrides any other sampling option!  \\ \hline
+                            &  & \hspace{0.5 cm} overrides any other sampling option!  \\
+    \verb"neighborhood_width"& []& $\delta$ (real number$>0$) uniform sample in the\\
+                            &  & neighborhood of the posterior mode $\hat{\theta}$ \\
+                            &  & interval width: $\hat{\theta}(1\pm\delta)$ \\\hline
 \end{tabular}
 \subsection{Stability mapping}
 \begin{tabular}{r|l|l}
@@ -132,11 +135,13 @@ beforehand}.
                             &  & 0 = no stability mapping is performed\\
             \verb"load_stab"& 0& 0 =  generate a new sample\\
                             &  & 1 = load a previously created sample \\
-          \verb"alpha2_stab"& 0.4& critical value for correlations $\rho$ in filtered samples:\\
+          \verb"pvalue_corr"& 0.001& critical p-value for correlations $\rho$ in filtered samples:\\
                             &    & plot couples of parameters with \\
-                            &   & $|\rho|>$\verb"alpha2_stab"\\
-               \verb"ksstat"& 0.1& critical value for Smirnov statistics $d$: \\
-                            &   & plot parameters with $d>$\verb"ksstat"\\ \hline
+                            &   & p-value$<$\verb"pvalue_corr"\\
+          \verb"pvalue_ks"  & 0.001& critical p-value for Smirnov statistics $d$: \\
+                            &   & plot parameters with p-value$<$\verb"pvalue_ks"\\
+          \verb"lik_init"  & 1& 1 = the model is stationary (unit roots are `explosive')\\
+                            &   & 3 = the model has unit roots (unit roots are `stable')\\ \hline
 \end{tabular}
 
 \newpage
@@ -167,10 +172,13 @@ out-of-sample validation. \vspace{0.5cm}
                             &   & of reduced form coefficients\\
                             &   & [\verb"max" \verb"max"] =  analyse filtered \\
                             &   & entries within the range [\verb"max" \verb"max"] \\
-       \verb"ksstat_redform"& 0.1& critical value for Smirnov statistics $d$ \\
-                            &   & when reduced form entries are filtered\\
-       \verb"alpha2_redform"& 0.3& critical value for correlation $\rho$ \\
-                            &   & when reduced form entries are filtered\\
+       \verb"ksstat_redform"& 0.001& critical p-value for Smirnov statistics $d$ \\
+                            &   & when \verb"threshold_redform" is active\\
+                            &   & plot parameters with p-value$<$\verb"ksstat_redform"\\
+       \verb"alpha2_redform"& 0& critical p-value for correlation $\rho$ \\
+                            &   & when \verb"threshold_redform" is active\\
+                            &    & plot couples of parameters with \\
+                            &   & p-value$<$\verb"alpha2_redform"\\
               \verb"namendo"& () & list of endogenous variables \\
                             & : & jolly character to indicate ALL endogenous \\
            \verb"namlagendo"& () & list of lagged endogenous variables:\\
@@ -212,6 +220,7 @@ options of \verb"dynare_estimation". These are:
   \item \verb"datafile"
   \item \verb"mode_file"
   \item \verb"first_obs"
+  \item \verb"lik_init"
   \item \verb"nobs"
   \item \verb"prefilter"
   \item \verb"presample"
@@ -234,12 +243,11 @@ options of \verb"dynare_estimation". These are:
                             &    & filter the best 10\% for each observed series\\
           \verb"istart_rmse"& 1& start computing RMSE's from \verb"istart_rmse":\\
                             &  & use 2 to avoid big initial error \\
-           \verb"alpha_rmse"& 0.002& critical value for Smirnov statistics $d$:\\
-                            &   & plot parameters with $d>$\verb"alpha_rmse"\\
-          \verb"alpha2_rmse"& 1& critical value for correlation $\rho$\\
+           \verb"alpha_rmse"& 0.001& p-value for Smirnov statistics $d$:\\
+                            &   & plot parameters with p-value$<$\verb"alpha_rmse"\\
+          \verb"alpha2_rmse"& 0& p-value for correlation $\rho$\\
                             &  & plot couples of parameters with
-                            $|\rho|>$\verb"alpha2_rmse"\\
-                 \verb"glue"& 0& prepare for GLUE graphical interface\\\hline
+                            p-value$<$\verb"alpha2_rmse"\\
 \end{tabular}
 
 \subsection{Screening analysis}
@@ -249,14 +257,12 @@ with respect to those listed in the `Sampling options':
 performs all the analyses required and displays results.
 
 
-\subsection{Identification analysis (under development)}
+\subsection{Identification analysis}
 Setting the option \verb"identification=1", an identification
 analysis based on theoretical moments is performed. Sensitivity plots are provided that
 allow to infer which parameters are most likely to be less
 identifiable.
 
-Prerequisite for properly running all the identification routines, is the keyword
-\verb"identification;" in the DYNARE model file. This keyword triggers the computation of analytic derivatives of the model with respect to estimated parameters and shocks. This is required for options \verb"morris=2" below, which implement \cite{Iskrev2009} identification analysis.
 \vspace{1cm}
 
 
@@ -264,36 +270,23 @@ Prerequisite for properly running all the identification routines, is the keywor
                 option name & default & description  \\ \hline
        \verb"identification"& 0 & 0 = no identification analysis  \\
                             &   & 1 = performs identification analysis:\\
-                            &   & this forces \verb"redform"=0 and default\verb"morris"=1\\
+                            &   & this forces \verb"redform"=0 and default \verb"morris"=1\\
                \verb"morris"& 1 & 1 = Screening analysis (Type II error)\\
-                            &   & 0 = ANOVA Mapping (Type I error)\\
-                            &   & 2 = Analytic derivatives (similar to Type II error)\\
+                            &   & 2 = Analytic derivatives \citep{Iskrev2010,Iskrev2011}\\
           \verb"morris_nliv"& 6 & number of levels in Morris design\\
           \verb"morris_ntra"& 20& number of trajectories in Morris design\\
-          \verb"trans_ident"& 0 & data transformation for ANOVA Mapping\\
-                            &   & 0 = no transformation\\
-                            &   & 1 = log-transformation\\
-                            &   & 2 = rank-transformation\\\hline
 \end{tabular}
 
 \vspace{1cm}
 \noindent For example, the following commands in the DYNARE model file
 
 \vspace{1cm}
-\noindent\verb"identification;"\\
-\verb"dynare_sensitivity(identification=1, morris=2);"
+\noindent\verb"dynare_sensitivity(identification=1, morris=2);"
 
 \vspace{1cm}
-\noindent trigger the identification analysis using analytic derivatives \citep{Iskrev2009}, jointly with the mapping of the acceptable region.
-
-The identification analysis with derivatives can also be triggered by the commands
+\noindent trigger the identification analysis using \cite{Iskrev2010,Iskrev2011}, jointly with the mapping of the acceptable region.
 
-\vspace{1cm}
-\noindent\verb"identification;"\\
-\verb"dynare_identification;"
 
-\vspace{1cm}
-This does not do the mapping of acceptable regions for the model and uses the standard random sampler of DYNARE. It completely offsets any use of the sensitivity analysis toolbox.
 \newpage
 \section{Directory structure}
 Sensitivity analysis results are saved on the hard-disk of the
diff --git a/doc/gsa/marco.bib b/doc/gsa/marco.bib
index a6fbcdd20956e139d28e76631259a763da23d7fb..7fa5c1bf9427b7e36196a694ed21521934a5e00f 100644
--- a/doc/gsa/marco.bib
+++ b/doc/gsa/marco.bib
@@ -1,10 +1,3 @@
-@TECHREPORT{Iskrev2009,
-AUTHOR={Iskrev, Nikolay},
-TITLE={Local Identification in \textsc{DSGE} Models},
-YEAR=2009,
-TYPE={mimeo},
-}
-
 @ARTICLE{Ratto_CompEcon_2008,
   author =       {Ratto, M.},
   title =        {Analysing DSGE Models with Global Sensitivity Analysis},
@@ -13,3 +6,20 @@ TYPE={mimeo},
   volume =       {31},
   pages =        {115--139},
 }
+
+@ARTICLE{Iskrev2010,
+  author = {Nikolay Iskrev},
+  title = {Local Identification in {DSGE} Models},
+  journal = {Journal of Monetary Economics},
+  year = {2010},
+  volume = {57},
+  pages = {189-202}
+}
+
+@UNPUBLISHED{Iskrev2011,
+  author = {Nikolay Iskrev},
+  title = {Evaluating the strenght of identification in {DSGE} models. An a priori
+	approach},
+  note = {mimeo},
+  year = {2011}
+}
diff --git a/doc/macroprocessor/macroprocessor.tex b/doc/macroprocessor/macroprocessor.tex
index 98c6caa30fd777a9ed2ac6bfbe82bdc9344854f1..8ecaf9510741ff16c739ef1311f38683292eb21c 100644
--- a/doc/macroprocessor/macroprocessor.tex
+++ b/doc/macroprocessor/macroprocessor.tex
@@ -2,23 +2,13 @@
 \usepackage[utf8]{inputenc}
 \usepackage{amsmath}
 
-\mode<handout>
-{
-  \usepackage{pgfpages}
-  \pgfpagesuselayout{4 on 1}[a4paper,border shrink=3mm,landscape]
-  \usetheme{Madrid}
-  \usecolortheme{seagull}
-}
-
-\mode<beamer>
-{
-  \usetheme{Madrid}
-}
+\usetheme{Boadilla}
 
 \title{The Dynare Macro-processor}
+\subtitle{Dynare Summer School 2012}
 \author{Sébastien Villemot}
 \institute{CEPREMAP}
-\date{June 20, 2011}
+\date{June 22, 2012}
 
 \AtBeginSection[]
 {
@@ -95,7 +85,7 @@
     \begin{itemize}
     \item file inclusion: \verb+@#include+
     \item definition a variable of the macro-processor: \verb+@#define+
-    \item conditional statements (\verb+@#if/@#else/@#endif+)
+    \item conditional statements (\verb+@#if/@#ifdef/@#else/@#endif+)
     \item loop statements (\verb+@#for/@#endfor+)
     \end{itemize}
   \item In most cases, directives occupy exactly one line of text. In case of need, two anti-slashes (\verb+\\+) at the end of the line indicates that the directive is continued on the next line.
@@ -254,7 +244,7 @@ end;
 \end{frame}
 
 \begin{frame}[fragile=singleslide]
-  \frametitle{Conditional inclusion directive}
+  \frametitle{Conditional inclusion directives (1/2)}
 
   \begin{columns}[T]
     \column{0.47\linewidth}
@@ -292,6 +282,28 @@ end;
   \end{block}
 \end{frame}
 
+\begin{frame}[fragile=singleslide]
+  \frametitle{Conditional inclusion directives (2/2)}
+
+  \begin{columns}[T]
+    \column{0.47\linewidth}
+    \begin{block}{Syntax 1}
+\verb+@#ifdef +\textit{variable\_name} \\
+\verb+   +\textit{body included if variable defined} \\
+\verb+@#endif+
+    \end{block}
+
+    \column{0.47\linewidth}
+    \begin{block}{Syntax 2}
+\verb+@#ifdef +\textit{variable\_name} \\
+\verb+   +\textit{body included if variable defined} \\
+\verb+@#else+ \\
+\verb+   +\textit{body included if variable not defined} \\
+\verb+@#endif+
+    \end{block}
+  \end{columns}
+\end{frame}
+
 \begin{frame}[fragile=singleslide]
   \frametitle{Echo and error directives}
 
@@ -573,7 +585,7 @@ rhos = [ 0.8, 0.9, 1];
   \begin{itemize}
   \item GNU Octave (or simply Octave) is a high-level language, primarily intended for numerical computations
   \item Basically, it is a free clone of MATLAB: same syntax, almost same set of functions
-  \item Runs on Windows, Linux and Mac OS X
+  \item Runs on Windows, GNU/Linux and Mac OS X
   \item Advantages:
     \begin{itemize}
     \item free software, no license fee to pay
@@ -584,7 +596,8 @@ rhos = [ 0.8, 0.9, 1];
     \begin{itemize}
     \item slower than MATLAB
     \item less user friendly (however note that there is a graphical fronted
-      called ``qtoctave'' that can be installed on top of Octave)
+      called ``qtoctave'' that can be installed on top of Octave; a native
+      frontend is under development)
     \end{itemize}
   \end{itemize}
 \end{frame}
diff --git a/doc/userguide/models/fs2000ns_steadystate.m b/doc/userguide/models/fs2000ns_steadystate.m
index e55b408730c1fd01cc8dc831c86e4f35b74d9e75..3720ec68e6157cb1f3ab910d2e08d94552c818fa 100644
--- a/doc/userguide/models/fs2000ns_steadystate.m
+++ b/doc/userguide/models/fs2000ns_steadystate.m
@@ -1,53 +1,53 @@
-% computes the steady state of fs2000 analyticaly
-% largely inspired by the program of F. Schorfheide
-function [ys,check] = fs2000ns_steadystate(ys,exe)
-  global M_
-  
-  alp = M_.params(1); 
-  bet = M_.params(2); 
-  gam = M_.params(3); 
-  mst = M_.params(4); 
-  rho = M_.params(5); 
-  psi = M_.params(6); 
-  del = M_.params(7); 
-
-  check = 0;
-  
-  dA = exp(gam);
-  gst = 1/dA;
-  m = mst;
-  
-  khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1));
-  xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1);
-  nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp );
-  n  = xist/(nust+xist);
-  P  = xist + nust;
-  k  = khst*n;
-  l  = psi*mst*n/( (1-psi)*(1-n) );
-  c  = mst/P;
-  d  = l - mst + 1;
-  y  = k^alp*n^(1-alp)*gst^alp;
-  R  = mst/bet;
-  W  = l/n;
-  ist  = y-c;
-  q  = 1 - d;
-  e = 1;
-  
-  P_obs = 1;
-  Y_obs = 1;
-  
-  ys =[
-m     
-P     
-c     
-e     
-W     
-R     
-k     
-d     
-n     
-l     
-Y_obs 
-P_obs 
-y     
+% computes the steady state of fs2000 analyticaly
+% largely inspired by the program of F. Schorfheide
+function [ys,check] = fs2000ns_steadystate(ys,exe)
+  global M_
+  
+  alp = M_.params(1); 
+  bet = M_.params(2); 
+  gam = M_.params(3); 
+  mst = M_.params(4); 
+  rho = M_.params(5); 
+  psi = M_.params(6); 
+  del = M_.params(7); 
+
+  check = 0;
+  
+  dA = exp(gam);
+  gst = 1/dA;
+  m = mst;
+  
+  khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1));
+  xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1);
+  nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp );
+  n  = xist/(nust+xist);
+  P  = xist + nust;
+  k  = khst*n;
+  l  = psi*mst*n/( (1-psi)*(1-n) );
+  c  = mst/P;
+  d  = l - mst + 1;
+  y  = k^alp*n^(1-alp)*gst^alp;
+  R  = mst/bet;
+  W  = l/n;
+  ist  = y-c;
+  q  = 1 - d;
+  e = 1;
+  
+  P_obs = 1;
+  Y_obs = 1;
+  
+  ys =[
+m     
+P     
+c     
+e     
+W     
+R     
+k     
+d     
+n     
+l     
+Y_obs 
+P_obs 
+y     
 dA          ];
\ No newline at end of file
diff --git a/doc/userguide/models/fsdat.m b/doc/userguide/models/fsdat.m
index 5a0e3658d4031fe8f32bee59f33c515549b8ee23..aba209b908a794044e570302331b8efe9eaac673 100644
--- a/doc/userguide/models/fsdat.m
+++ b/doc/userguide/models/fsdat.m
@@ -1,210 +1,210 @@
-data_q = [
-18.02 1474.5 150.2
-17.94 1538.2 150.9
-18.01 1584.5 151.4
-18.42 1644.1 152
-18.73 1678.6 152.7
-19.46 1693.1 153.3
-19.55 1724   153.9
-19.56 1758.2 154.7
-19.79 1760.6 155.4
-19.77 1779.2 156
-19.82 1778.8 156.6
-20.03 1790.9 157.3
-20.12 1846   158
-20.1  1882.6 158.6
-20.14 1897.3 159.2
-20.22 1887.4 160
-20.27 1858.2 160.7
-20.34 1849.9 161.4
-20.39 1848.5 162
-20.42 1868.9 162.8
-20.47 1905.6 163.6
-20.56 1959.6 164.3
-20.62 1994.4 164.9
-20.78 2020.1 165.7
-21    2030.5 166.5
-21.2  2023.6 167.2
-21.33 2037.7 167.9
-21.62 2033.4 168.7
-21.71 2066.2 169.5
-22.01 2077.5 170.2
-22.15 2071.9 170.9
-22.27 2094   171.7
-22.29 2070.8 172.5
-22.56 2012.6 173.1
-22.64 2024.7 173.8
-22.77 2072.3 174.5
-22.88 2120.6 175.3
-22.92 2165   176.045
-22.91 2223.3  176.727
-22.94 2221.4  177.481
-23.03 2230.95 178.268
-23.13 2279.22 179.694
-23.22 2265.48 180.335
-23.32 2268.29 181.094
-23.4  2238.57 181.915
-23.45 2251.68 182.634
-23.51 2292.02 183.337
-23.56 2332.61 184.103
-23.63 2381.01 184.894
-23.75 2422.59 185.553
-23.81 2448.01 186.203
-23.87 2471.86 186.926
-23.94 2476.67 187.68
-24    2508.7  188.299
-24.07 2538.05 188.906
-24.12 2586.26 189.631
-24.29 2604.62 190.362
-24.35 2666.69 190.954
-24.41 2697.54 191.56
-24.52 2729.63 192.256
-24.64 2739.75 192.938
-24.77 2808.88 193.467
-24.88 2846.34 193.994
-25.01 2898.79 194.647
-25.17 2970.48 195.279
-25.32 3042.35 195.763
-25.53 3055.53 196.277
-25.79 3076.51 196.877
-26.02 3102.36 197.481
-26.14 3127.15 197.967
-26.31 3129.53 198.455
-26.6  3154.19 199.012
-26.9  3177.98 199.572
-27.21 3236.18 199.995
-27.49 3292.07 200.452
-27.75 3316.11 200.997
-28.12 3331.22 201.538
-28.39 3381.86 201.955
-28.73 3390.23 202.419
-29.14 3409.65 202.986
-29.51 3392.6  203.584
-29.94 3386.49 204.086
-30.36 3391.61 204.721
-30.61 3422.95 205.419
-31.02 3389.36 206.13
-31.5  3481.4  206.763
-31.93 3500.95 207.362
-32.27 3523.8  208
-32.54 3533.79 208.642
-33.02 3604.73 209.142
-33.2  3687.9  209.637
-33.49 3726.18 210.181
-33.95 3790.44 210.737
-34.36 3892.22 211.192
-34.94 3919.01 211.663
-35.61 3907.08 212.191
-36.29 3947.11 212.708
-37.01 3908.15 213.144
-37.79 3922.57 213.602
-38.96 3879.98 214.147
-40.13 3854.13 214.7
-41.05 3800.93 215.135
-41.66 3835.21 215.652
-42.41 3907.02 216.289
-43.19 3952.48 216.848
-43.69 4044.59 217.314
-44.15 4072.19 217.776
-44.77 4088.49 218.338
-45.57 4126.39 218.917
-46.32 4176.28 219.427
-47.07 4260.08 219.956
-47.66 4329.46 220.573
-48.63 4328.33 221.201
-49.42 4345.51 221.719
-50.41 4510.73 222.281
-51.27 4552.14 222.933
-52.35 4603.65 223.583
-53.51 4605.65 224.152
-54.65 4615.64 224.737
-55.82 4644.93 225.418
-56.92 4656.23 226.117
-58.18 4678.96 226.754
-59.55 4566.62 227.389
-61.01 4562.25 228.07
-62.59 4651.86 228.689
-64.15 4739.16 229.155
-65.37 4696.82 229.674
-66.65 4753.02 230.301
-67.87 4693.76 230.903
-68.86 4615.89 231.395
-69.72 4634.88 231.906
-70.66 4612.08 232.498
-71.44 4618.26 233.074
-72.08 4662.97 233.546
-72.83 4763.57 234.028
-73.48 4849    234.603
-74.19 4939.23 235.153
-75.02 5053.56 235.605
-75.58 5132.87 236.082
-76.25 5170.34 236.657
-76.81 5203.68 237.232
-77.63 5257.26 237.673
-78.25 5283.73 238.176
-78.76 5359.6  238.789
-79.45 5393.57 239.387
-79.81 5460.83 239.861
-80.22 5466.95 240.368
-80.84 5496.29 240.962
-81.45 5526.77 241.539
-82.09 5561.8  242.009
-82.68 5618    242.52
-83.33 5667.39 243.12
-84.09 5750.57 243.721
-84.67 5785.29 244.208
-85.56 5844.05 244.716
-86.66 5878.7  245.354
-87.44 5952.83 245.966
-88.45 6010.96 246.46
-89.39 6055.61 247.017
-90.13 6087.96 247.698
-90.88 6093.51 248.374
-92    6152.59 248.928
-93.18 6171.57 249.564
-94.14 6142.1  250.299
-95.11 6078.96 251.031
-96.27 6047.49 251.65
-97    6074.66 252.295
-97.7  6090.14 253.033
-98.31 6105.25 253.743
-99.13 6175.69 254.338
-99.79 6214.22 255.032
-100.17 6260.74 255.815
-100.88 6327.12 256.543
-101.84 6327.93 257.151
-102.35 6359.9  257.785
-102.83 6393.5  258.516
-103.51 6476.86 259.191
-104.13 6524.5  259.738
-104.71 6600.31 260.351
-105.39 6629.47 261.04
-106.09 6688.61 261.692
-106.75 6717.46 262.236
-107.24 6724.2  262.847
-107.75 6779.53 263.527
-108.29 6825.8  264.169
-108.91 6882    264.681
-109.24 6983.91 265.258
-109.74 7020    265.887
-110.23 7093.12 266.491
-111    7166.68 266.987
-111.43 7236.5  267.545
-111.76 7311.24 268.171
-112.08 7364.63 268.815
-];
-%GDPD  GDPQ   GPOP
-
-series = zeros(193,2);
-series(:,2) = data_q(:,1);
-series(:,1) = 1000*data_q(:,2)./data_q(:,3);
-
-Y_obs = series(:,1);
-P_obs = series(:,2);
-
-series = series(2:193,:)./series(1:192,:);
-
-gy_obs = series(:,1);
-gp_obs = series(:,2);
-
+data_q = [
+18.02 1474.5 150.2
+17.94 1538.2 150.9
+18.01 1584.5 151.4
+18.42 1644.1 152
+18.73 1678.6 152.7
+19.46 1693.1 153.3
+19.55 1724   153.9
+19.56 1758.2 154.7
+19.79 1760.6 155.4
+19.77 1779.2 156
+19.82 1778.8 156.6
+20.03 1790.9 157.3
+20.12 1846   158
+20.1  1882.6 158.6
+20.14 1897.3 159.2
+20.22 1887.4 160
+20.27 1858.2 160.7
+20.34 1849.9 161.4
+20.39 1848.5 162
+20.42 1868.9 162.8
+20.47 1905.6 163.6
+20.56 1959.6 164.3
+20.62 1994.4 164.9
+20.78 2020.1 165.7
+21    2030.5 166.5
+21.2  2023.6 167.2
+21.33 2037.7 167.9
+21.62 2033.4 168.7
+21.71 2066.2 169.5
+22.01 2077.5 170.2
+22.15 2071.9 170.9
+22.27 2094   171.7
+22.29 2070.8 172.5
+22.56 2012.6 173.1
+22.64 2024.7 173.8
+22.77 2072.3 174.5
+22.88 2120.6 175.3
+22.92 2165   176.045
+22.91 2223.3  176.727
+22.94 2221.4  177.481
+23.03 2230.95 178.268
+23.13 2279.22 179.694
+23.22 2265.48 180.335
+23.32 2268.29 181.094
+23.4  2238.57 181.915
+23.45 2251.68 182.634
+23.51 2292.02 183.337
+23.56 2332.61 184.103
+23.63 2381.01 184.894
+23.75 2422.59 185.553
+23.81 2448.01 186.203
+23.87 2471.86 186.926
+23.94 2476.67 187.68
+24    2508.7  188.299
+24.07 2538.05 188.906
+24.12 2586.26 189.631
+24.29 2604.62 190.362
+24.35 2666.69 190.954
+24.41 2697.54 191.56
+24.52 2729.63 192.256
+24.64 2739.75 192.938
+24.77 2808.88 193.467
+24.88 2846.34 193.994
+25.01 2898.79 194.647
+25.17 2970.48 195.279
+25.32 3042.35 195.763
+25.53 3055.53 196.277
+25.79 3076.51 196.877
+26.02 3102.36 197.481
+26.14 3127.15 197.967
+26.31 3129.53 198.455
+26.6  3154.19 199.012
+26.9  3177.98 199.572
+27.21 3236.18 199.995
+27.49 3292.07 200.452
+27.75 3316.11 200.997
+28.12 3331.22 201.538
+28.39 3381.86 201.955
+28.73 3390.23 202.419
+29.14 3409.65 202.986
+29.51 3392.6  203.584
+29.94 3386.49 204.086
+30.36 3391.61 204.721
+30.61 3422.95 205.419
+31.02 3389.36 206.13
+31.5  3481.4  206.763
+31.93 3500.95 207.362
+32.27 3523.8  208
+32.54 3533.79 208.642
+33.02 3604.73 209.142
+33.2  3687.9  209.637
+33.49 3726.18 210.181
+33.95 3790.44 210.737
+34.36 3892.22 211.192
+34.94 3919.01 211.663
+35.61 3907.08 212.191
+36.29 3947.11 212.708
+37.01 3908.15 213.144
+37.79 3922.57 213.602
+38.96 3879.98 214.147
+40.13 3854.13 214.7
+41.05 3800.93 215.135
+41.66 3835.21 215.652
+42.41 3907.02 216.289
+43.19 3952.48 216.848
+43.69 4044.59 217.314
+44.15 4072.19 217.776
+44.77 4088.49 218.338
+45.57 4126.39 218.917
+46.32 4176.28 219.427
+47.07 4260.08 219.956
+47.66 4329.46 220.573
+48.63 4328.33 221.201
+49.42 4345.51 221.719
+50.41 4510.73 222.281
+51.27 4552.14 222.933
+52.35 4603.65 223.583
+53.51 4605.65 224.152
+54.65 4615.64 224.737
+55.82 4644.93 225.418
+56.92 4656.23 226.117
+58.18 4678.96 226.754
+59.55 4566.62 227.389
+61.01 4562.25 228.07
+62.59 4651.86 228.689
+64.15 4739.16 229.155
+65.37 4696.82 229.674
+66.65 4753.02 230.301
+67.87 4693.76 230.903
+68.86 4615.89 231.395
+69.72 4634.88 231.906
+70.66 4612.08 232.498
+71.44 4618.26 233.074
+72.08 4662.97 233.546
+72.83 4763.57 234.028
+73.48 4849    234.603
+74.19 4939.23 235.153
+75.02 5053.56 235.605
+75.58 5132.87 236.082
+76.25 5170.34 236.657
+76.81 5203.68 237.232
+77.63 5257.26 237.673
+78.25 5283.73 238.176
+78.76 5359.6  238.789
+79.45 5393.57 239.387
+79.81 5460.83 239.861
+80.22 5466.95 240.368
+80.84 5496.29 240.962
+81.45 5526.77 241.539
+82.09 5561.8  242.009
+82.68 5618    242.52
+83.33 5667.39 243.12
+84.09 5750.57 243.721
+84.67 5785.29 244.208
+85.56 5844.05 244.716
+86.66 5878.7  245.354
+87.44 5952.83 245.966
+88.45 6010.96 246.46
+89.39 6055.61 247.017
+90.13 6087.96 247.698
+90.88 6093.51 248.374
+92    6152.59 248.928
+93.18 6171.57 249.564
+94.14 6142.1  250.299
+95.11 6078.96 251.031
+96.27 6047.49 251.65
+97    6074.66 252.295
+97.7  6090.14 253.033
+98.31 6105.25 253.743
+99.13 6175.69 254.338
+99.79 6214.22 255.032
+100.17 6260.74 255.815
+100.88 6327.12 256.543
+101.84 6327.93 257.151
+102.35 6359.9  257.785
+102.83 6393.5  258.516
+103.51 6476.86 259.191
+104.13 6524.5  259.738
+104.71 6600.31 260.351
+105.39 6629.47 261.04
+106.09 6688.61 261.692
+106.75 6717.46 262.236
+107.24 6724.2  262.847
+107.75 6779.53 263.527
+108.29 6825.8  264.169
+108.91 6882    264.681
+109.24 6983.91 265.258
+109.74 7020    265.887
+110.23 7093.12 266.491
+111    7166.68 266.987
+111.43 7236.5  267.545
+111.76 7311.24 268.171
+112.08 7364.63 268.815
+];
+%GDPD  GDPQ   GPOP
+
+series = zeros(193,2);
+series(:,2) = data_q(:,1);
+series(:,1) = 1000*data_q(:,2)./data_q(:,3);
+
+Y_obs = series(:,1);
+P_obs = series(:,2);
+
+series = series(2:193,:)./series(1:192,:);
+
+gy_obs = series(:,1);
+gp_obs = series(:,2);
+
 ti = [1950:0.25:1997.75];
\ No newline at end of file
diff --git a/dynare++/kord/approximation.hweb b/dynare++/kord/approximation.hweb
index 137511c219d4d40e4dc9043a1d76bdaaa40d68e2..82e2236e256bb188020e495fc5f00239bf25fbdc 100644
--- a/dynare++/kord/approximation.hweb
+++ b/dynare++/kord/approximation.hweb
@@ -145,6 +145,10 @@ public:@;
 
 	void walkStochSteady();
 	TwoDMatrix* calcYCov() const;
+	const FGSContainer* get_rule_ders() const
+	      	{@+ return rule_ders;@+}	   
+	const FGSContainer* get_rule_ders_ss() const
+	      	{@+ return rule_ders;@+}	   
 protected:@;
 	void approxAtSteady();
 	void calcStochShift(Vector& out, double at_sigma) const;
diff --git a/dynare++/kord/decision_rule.hweb b/dynare++/kord/decision_rule.hweb
index bc96bb130138c40e3237c4b91ef593ed71156538..bad14cc1fdedb7dff06f87c7681cc61501bde65f 100644
--- a/dynare++/kord/decision_rule.hweb
+++ b/dynare++/kord/decision_rule.hweb
@@ -300,7 +300,7 @@ TwoDMatrix* simulate(emethod em, int np, const Vector& ystart,
 	@<initialize vectors and subvectors for simulation@>;
 	@<perform the first step of simulation@>;
 	@<perform all other steps of simulations@>;
-	@<add the steady state to all columns of |res|@>;
+	@<add the steady state to columns of |res|@>;
 	return res;
 }
 
@@ -327,10 +327,11 @@ evaluate the polynomial.
 	eval(em, out, dyu);
 
 @ Also clear. If the result at some period is not finite, we pad the
-rest of the matrix with zeros and return immediatelly.
+rest of the matrix with zeros.
 
 @<perform all other steps of simulations@>=
-	for (int i = 1; i < np; i++) {
+        int i=1;
+	while (i < np) {
 		ConstVector ym(*res, i-1);
 		ConstVector dym(ym, ypart.nstat, ypart.nys());
 		dy = dym;
@@ -342,14 +343,16 @@ rest of the matrix with zeros and return immediatelly.
 				TwoDMatrix rest(*res, i+1, np-i-1);
 				rest.zeros();
 			}
-			return res;
+			break;
 		}
+		i++;
 	}
 
-@ Even clearer.
-@<add the steady state to all columns of |res|@>=
-	for (int i = 0; i < res->ncols(); i++) {
-		Vector col(*res, i);
+@ Even clearer. We add the steady state to the numbers computed above and leave the padded columns to zero.
+
+@<add the steady state to columns of |res|@>=
+	for (int j = 0; j < i; j++) {
+		Vector col(*res, j);
 		col.add(1.0, ysteady);
 	}
 
diff --git a/dynare++/src/nlsolve.cpp b/dynare++/src/nlsolve.cpp
index c335d8fde735ffb80261f71a0db9d55dfeb4fc96..1210176b3f6d8a853e198976754f1c66ba057e51 100644
--- a/dynare++/src/nlsolve.cpp
+++ b/dynare++/src/nlsolve.cpp
@@ -21,7 +21,7 @@ double GoldenSectionSearch::search(OneDFunction& f, double x1, double x2)
 	if (init_bracket(f, x1, x2, b)) {
 		double fb = f.eval(b);
 		double f1 = f.eval(x1);
-		double f2 = f.eval(x2);
+		f.eval(x2);
 		double dx;
 		do {
 			double w = (b-x1)/(x2-x1);
@@ -38,7 +38,6 @@ double GoldenSectionSearch::search(OneDFunction& f, double x1, double x2)
 				// x is on the left from b
 				if (f1 > fx && fx < fb) {
 					// pickup bracket [f1,fx,fb]
-					f2 = fb;
 					x2 = b;
 					fb = fx;
 					b = x;
@@ -51,7 +50,6 @@ double GoldenSectionSearch::search(OneDFunction& f, double x1, double x2)
 				// x is on the right from b
 				if (f1 > fb && fb < fx) {
 					// pickup bracket [f1,fb,fx]
-					f2 = fx;
 					x2 = x;
 				} else {
 					// pickup bracket [fb,fx,f2]
diff --git a/dynare++/tl/cc/t_container.hweb b/dynare++/tl/cc/t_container.hweb
index be411b7f946b0fd49257a10e8a569133adf470e3..00f7c6807ed4d1eb2d28f4b1a45ec962c9113dd8 100644
--- a/dynare++/tl/cc/t_container.hweb
+++ b/dynare++/tl/cc/t_container.hweb
@@ -268,7 +268,7 @@ int getMaxDim() const
 @<|TensorContainer::print| code@>=
 void print() const
 {
-	printf("Tensor container: nvars=%d, tensors=%d\n", n, m.size());
+	printf("Tensor container: nvars=%d, tensors=%D\n", n, m.size());
 	for (const_iterator it = m.begin(); it != m.end(); ++it) {
 		printf("Symmetry: ");
 		(*it).first.print();
diff --git a/license.txt b/license.txt
index 2cbd05b835863c8e1965d91c78e449c1af9fd593..d4789aa7dde4e89d32110e9ec15a61be0125e5f1 100644
--- a/license.txt
+++ b/license.txt
@@ -124,7 +124,7 @@ Copyright: 2002-2003 Ralph Schleicher
            2009 Dynare Team
 License: GPL-2+ with Autoconf exception
 
-Files: dynare.el
+Files: scripts/dynare.el
 Copyright: 2010 Yannick Kalantzis
 License: GPL-3+
 
diff --git a/matlab/@dynTime/setFreq.m b/matlab/@dynTime/setFreq.m
index 4c329468f20830bc9b90107926d15b7a4ccd9f00..2530e564906f5e69a526b33c1a448174ab71073d 100644
--- a/matlab/@dynTime/setFreq.m
+++ b/matlab/@dynTime/setFreq.m
@@ -44,4 +44,21 @@ function sp = setFreq(sp,freq)
 %! @end deftypefn
 %@eod:
 
+% Copyright (C) 2012 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/>.
+
 sp.freq = freq;
\ No newline at end of file
diff --git a/matlab/@dynTime/setSize.m b/matlab/@dynTime/setSize.m
index 5818a90b6a17e527bbb9b96653d742c81af489de..7cdf33224433a41a4e90d6dccc29f49212d3b0eb 100644
--- a/matlab/@dynTime/setSize.m
+++ b/matlab/@dynTime/setSize.m
@@ -41,4 +41,22 @@ function sp = setSize(sp,n)
 %!
 %! @end deftypefn
 %@eod:
+
+% Copyright (C) 2012 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/>.
+
     sp.time = NaN(n,2);
diff --git a/matlab/@dynTime/setTime.m b/matlab/@dynTime/setTime.m
index 77d06401f30def24f2d816e794e975e8fe9dce35..739c1cba908ad5a5006b54f02ad9e63cf35dbd90 100644
--- a/matlab/@dynTime/setTime.m
+++ b/matlab/@dynTime/setTime.m
@@ -48,6 +48,23 @@ function sp = setTime(sp,i,date)
 %! @end deftypefn
 %@eod:
 
+% Copyright (C) 2012 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==3
     sp.time(i,:) = date;
 elseif nargin==2
diff --git a/matlab/@dynTime/subsref.m b/matlab/@dynTime/subsref.m
index f715e683952f950cf56d01688a033c8d66708186..71e1688004451362d3c3e759af1ad8c13899c79d 100644
--- a/matlab/@dynTime/subsref.m
+++ b/matlab/@dynTime/subsref.m
@@ -33,6 +33,23 @@ function B = subsref(A, S)
 %! @end deftypefn
 %@eod:
 
+% Copyright (C) 2012 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 isequal(S(1).type,'.')
     switch S(1).subs
       case {'time','freq','init','last'}                                   % Public members.
diff --git a/matlab/AHessian.m b/matlab/AHessian.m
index f1046c8dc08a9cb6e9240a8b63de7d8970131ed8..02cd7f0a3f66008e660ad058d69056d37c97c625 100644
--- a/matlab/AHessian.m
+++ b/matlab/AHessian.m
@@ -50,7 +50,7 @@ end
 %         DOm = DR(:,:,ii)*Q*transpose(R) + R*DQ(:,:,ii)*transpose(R) + R*Q*transpose(DR(:,:,ii)); 
 %     end
     
-    while notsteady & t<smpl
+    while notsteady && t<smpl
         t  = t+1;
         v  = Y(:,t)-a(mf);
         F  = P(mf,mf) + H;
@@ -112,7 +112,7 @@ end
             a = T*(a+K*v);
         lik(t) = transpose(v)*iF*v;
         end
-        AHess = AHess + .5*(smpl+t0-1)*(vecDPmf' * kron(iF,iF) * vecDPmf);
+        AHess = AHess + .5*(smpl-t0+1)*(vecDPmf' * kron(iF,iF) * vecDPmf);
         if nargout > 1
         for ii = 1:k
 %             DLIK(ii,1)  = DLIK(ii,1) + (smpl-t0+1)*trace( iF*DF(:,:,ii) );
diff --git a/matlab/AIM/SPAmalg.m b/matlab/AIM/SPAmalg.m
index 6438cf39b8a06232670cd4ff7b716cb7742ecfcc..41307b445e118ca8721e93952706d9be876bdc5e 100644
--- a/matlab/AIM/SPAmalg.m
+++ b/matlab/AIM/SPAmalg.m
@@ -1,3 +1,5 @@
+function [b,rts,ia,nexact,nnumeric,lgroots,aimcode] = ...
+                        SPAmalg(h,neq,nlag,nlead,condn,uprbnd)
 %  [b,rts,ia,nexact,nnumeric,lgroots,aimcode] = ...
 %                       SPAmalg(h,neq,nlag,nlead,condn,uprbnd)
 %
@@ -54,8 +56,6 @@
 % Journal of Economic Dynamics and Control, 2010, vol. 34, issue 3,
 % pages 472-489
 
-function [b,rts,ia,nexact,nnumeric,lgroots,aimcode] = ...
-                        SPAmalg(h,neq,nlag,nlead,condn,uprbnd)
 b=[];rts=[];ia=[];nexact=[];nnumeric=[];lgroots=[];aimcode=[];
 if(nlag<1 || nlead<1) 
     error('Aim_eig: model must have at least one lag and one lead');
diff --git a/matlab/AIM/SPBuild_a.m b/matlab/AIM/SPBuild_a.m
index b2d8d9022546c0837d7923fb703f1a35fe42b98f..eb12473a8afef4a70b8088a7fc40233508253ed1 100644
--- a/matlab/AIM/SPBuild_a.m
+++ b/matlab/AIM/SPBuild_a.m
@@ -1,3 +1,4 @@
+function [a,ia,js] = SPBuild_a(h,qcols,neq)
 %  [a,ia,js] = SPBuild_a(h,qcols,neq)
 %
 %  Build the companion matrix, deleting inessential lags.
@@ -27,7 +28,6 @@
 % Journal of Economic Dynamics and Control, 2010, vol. 34, issue 3,
 % pages 472-489
 
-function [a,ia,js] = SPBuild_a(h,qcols,neq)
 
 left  = 1:qcols;
 right = qcols+1:qcols+neq;
diff --git a/matlab/AIM/SPCopy_w.m b/matlab/AIM/SPCopy_w.m
index de39c0ec1bdf134eda9374a3af58121cea73c45e..714a1e27466116e2d35df8838c535cbd8e519009 100644
--- a/matlab/AIM/SPCopy_w.m
+++ b/matlab/AIM/SPCopy_w.m
@@ -1,3 +1,4 @@
+function  q = SPCopy_w(q,w,js,iq,qrows)
 % q = SPCopy_w(q,w,js,iq,qrows)
 %
 %  Copy the eigenvectors corresponding to the largest roots into the
@@ -27,7 +28,6 @@
 % Journal of Economic Dynamics and Control, 2010, vol. 34, issue 3,
 % pages 472-489
 
-function  q = SPCopy_w(q,w,js,iq,qrows)
 
 if(iq < qrows)
    lastrows = iq+1:qrows;
diff --git a/matlab/AIM/SPEigensystem.m b/matlab/AIM/SPEigensystem.m
index 7a83c36cce684be5ffd8c02b29e50b6d1678c898..16855401a521704a22778f62c1dce3edcaa39f99 100644
--- a/matlab/AIM/SPEigensystem.m
+++ b/matlab/AIM/SPEigensystem.m
@@ -1,3 +1,4 @@
+function [w,rts,lgroots,flag_trouble] = SPEigensystem(a,uprbnd,rowsLeft)
 %  [w,rts,lgroots] = SPEigensystem(a,uprbnd)
 %
 %  Compute the roots and the left eigenvectors of the companion
@@ -29,7 +30,6 @@
 % Journal of Economic Dynamics and Control, 2010, vol. 34, issue 3,
 % pages 472-489
 
-function [w,rts,lgroots,flag_trouble] = SPEigensystem(a,uprbnd,rowsLeft) 
 opts.disp=0; 
 % next block is commented out because eigs() intermitently returns different rts
 %try
diff --git a/matlab/AIM/SPExact_shift.m b/matlab/AIM/SPExact_shift.m
index 5f3700553a0dfbf387741590ff8c5bd51e221302..c9034e319bd3d309b4e49ebb53d6fa28a1e261d1 100644
--- a/matlab/AIM/SPExact_shift.m
+++ b/matlab/AIM/SPExact_shift.m
@@ -1,3 +1,4 @@
+function [h,q,iq,nexact] = SPExact_shift(h,q,iq,qrows,qcols,neq)
 % [h,q,iq,nexact] = exact_shift(h,q,iq,qrows,qcols,neq)
 %
 % Compute the exact shiftrights and store them in q.
@@ -26,7 +27,6 @@
 % Journal of Economic Dynamics and Control, 2010, vol. 34, issue 3,
 % pages 472-489
 
-function [h,q,iq,nexact] = SPExact_shift(h,q,iq,qrows,qcols,neq)
 
 %hs=SPSparse(h);
 hs=sparse(h);
diff --git a/matlab/AIM/SPNumeric_shift.m b/matlab/AIM/SPNumeric_shift.m
index 38ee85759120a13d54354e50deab3aba89417440..cc1e1825f7588a1481d6fabe986c86b8d1b60616 100644
--- a/matlab/AIM/SPNumeric_shift.m
+++ b/matlab/AIM/SPNumeric_shift.m
@@ -1,3 +1,4 @@
+function [h,q,iq,nnumeric] = SPNumeric_shift(h,q,iq,qrows,qcols,neq,condn)
 %  [h,q,iq,nnumeric] = ...
 %             SPNumeric_shift(h,q,iq,qrows,qcols,neq,condn)
 %
@@ -27,7 +28,6 @@
 % Journal of Economic Dynamics and Control, 2010, vol. 34, issue 3,
 % pages 472-489
 
-function [h,q,iq,nnumeric] = SPNumeric_shift(h,q,iq,qrows,qcols,neq,condn)
 
 nnumeric = 0;
 left     = 1:qcols;
diff --git a/matlab/AIM/SPObstruct.m b/matlab/AIM/SPObstruct.m
index 392781081bb80891d46e70e046487df94eb3485a..8620ca1b9b562ae859f342dfa093bc4337b29a68 100644
--- a/matlab/AIM/SPObstruct.m
+++ b/matlab/AIM/SPObstruct.m
@@ -1,3 +1,4 @@
+function scof = SPObstruct(cof,cofb,neq,nlag,nlead)
 % scof = SPObstruct(cof,cofb,neq,nlag,nlead)
 %
 % Construct the coefficients in the observable structure.
@@ -38,7 +39,6 @@
 % Journal of Economic Dynamics and Control, 2010, vol. 34, issue 3,
 % pages 472-489
 
-function scof = SPObstruct(cof,cofb,neq,nlag,nlead)
 
 
 % Append the negative identity to cofb
diff --git a/matlab/AIM/SPReduced_form.m b/matlab/AIM/SPReduced_form.m
index d7ddd8a91b33a145a13ba06d98b5f3d9a096e551..3d5c8899078e52eb3f401904bad949351c48d73c 100644
--- a/matlab/AIM/SPReduced_form.m
+++ b/matlab/AIM/SPReduced_form.m
@@ -1,3 +1,4 @@
+function [nonsing,b] = SPReduced_form(q,qrows,qcols,bcols,neq,condn);
 % [nonsing,b] = SPReduced_form(q,qrows,qcols,bcols,neq,b,condn);
 %
 % Compute reduced-form coefficient matrix, b.
@@ -26,7 +27,6 @@
 % Journal of Economic Dynamics and Control, 2010, vol. 34, issue 3,
 % pages 472-489
 
-function [nonsing,b] = SPReduced_form(q,qrows,qcols,bcols,neq,condn);
 b=[];
 %qs=SPSparse(q);
 qs=sparse(q);
diff --git a/matlab/AIM/dynAIMsolver1.m b/matlab/AIM/dynAIMsolver1.m
index 9945c380115448118deebd8b72bb1cc1a418cda0..2e23e0222004d70c4341fd48fbf81147f7f0719f 100644
--- a/matlab/AIM/dynAIMsolver1.m
+++ b/matlab/AIM/dynAIMsolver1.m
@@ -46,7 +46,7 @@ function [dr,aimcode,rts]=dynAIMsolver1(jacobia_,M_,dr)
 %
 % GP July 2008 
 
-% Copyright (C) 2008-2009 Dynare Team
+% Copyright (C) 2008-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/AIM_first_order_solver.m b/matlab/AIM_first_order_solver.m
index bc4f870ddd21fe50200067cf7782e81d5486f24a..b95c952caffa631955e8f1934b8a152e88e2e53c 100644
--- a/matlab/AIM_first_order_solver.m
+++ b/matlab/AIM_first_order_solver.m
@@ -51,7 +51,7 @@ function [dr,info]=AIM_first_order_solver(jacobia,M,dr,qz_criterium)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2001-2011 Dynare Team
+% Copyright (C) 2001-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/CheckPath.m b/matlab/CheckPath.m
index 4513c3b8a2d5be04ca30bdcb818ca5edb55b4993..209a0d609a89904380c2255589709fbe2575e924 100644
--- a/matlab/CheckPath.m
+++ b/matlab/CheckPath.m
@@ -11,7 +11,7 @@ function DirectoryName = CheckPath(type,dname)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2005-2009 Dynare Team
+% Copyright (C) 2005-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/DsgeSmoother.m b/matlab/DsgeSmoother.m
index 149e3851818f047dc2560db3c04f0713c5ea7a5f..9eba636c3d31e070ff84b27d90d60033d1b6272c 100644
--- a/matlab/DsgeSmoother.m
+++ b/matlab/DsgeSmoother.m
@@ -28,7 +28,7 @@ function [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T,R,P,PK,de
 % SPECIAL REQUIREMENTS
 %   None
 
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -62,7 +62,7 @@ decomp        = [];
 nobs            = size(options_.varobs,1);
 smpl          = size(Y,2);
 
-set_all_parameters(xparam1);
+M_ = set_all_parameters(xparam1,estim_params_,M_);
 
 %------------------------------------------------------------------------------
 % 2. call model setup & reduction program
diff --git a/matlab/DsgeVarLikelihood.m b/matlab/DsgeVarLikelihood.m
index 05f8908148fc21e55343a8153a2253c0b526af0d..840842cef89a46fcd4534994a5248167574fe75f 100644
--- a/matlab/DsgeVarLikelihood.m
+++ b/matlab/DsgeVarLikelihood.m
@@ -17,7 +17,7 @@ function [fval,grad,hess,exit_flag,info,PHI,SIGMAu,iXX,prior] = DsgeVarLikelihoo
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/GetAllPosteriorDraws.m b/matlab/GetAllPosteriorDraws.m
index 3a3a489ecbe6d873ff8c8027f5185353df3bf3a0..88e80f9182121cfe739d460349c2fe93b3151738 100644
--- a/matlab/GetAllPosteriorDraws.m
+++ b/matlab/GetAllPosteriorDraws.m
@@ -16,7 +16,7 @@ function Draws = GetAllPosteriorDraws(column, FirstMhFile, FirstLine, TotalNumbe
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2005-2009 Dynare Team
+% Copyright (C) 2005-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/GetOneDraw.m b/matlab/GetOneDraw.m
index e7ea3e7f7785d53a3f659fb116f8d14f73879766..2a84e7b7d019886975a57ea2a59aa2c312a1f400 100644
--- a/matlab/GetOneDraw.m
+++ b/matlab/GetOneDraw.m
@@ -14,7 +14,7 @@ function [xparams, logpost] = GetOneDraw(type)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2005-2009 Dynare Team
+% Copyright (C) 2005-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/GetPosteriorMeanVariance.m b/matlab/GetPosteriorMeanVariance.m
index fd22bea40081d191ba2b64eb545392b56696dd69..b5a1f3439efa2893eab796150a6c1c25ba3e1104 100644
--- a/matlab/GetPosteriorMeanVariance.m
+++ b/matlab/GetPosteriorMeanVariance.m
@@ -1,4 +1,21 @@
 function [mean,variance] = GetPosteriorMeanVariance(M,drop)
+
+% Copyright (C) 2012 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/>.
     
     DirectoryName = CheckPath('metropolis',M.dname);
     o=load([ DirectoryName '/'  M.fname '_mh_history']);
diff --git a/matlab/GetPosteriorParametersStatistics.m b/matlab/GetPosteriorParametersStatistics.m
index eeddf67c1fb9d4ef6fd269fbe020cd1aa046ef01..ef706b584926f508f9197141010404d13acff3a1 100644
--- a/matlab/GetPosteriorParametersStatistics.m
+++ b/matlab/GetPosteriorParametersStatistics.m
@@ -15,7 +15,7 @@ function oo_ = GetPosteriorParametersStatistics(estim_params_, M_, options_, bay
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/McMCDiagnostics.m b/matlab/McMCDiagnostics.m
index 8ac86e44d81945f0574d69c6ba506287eb700340..4af9ccb80fadceb4fc0861e521945c221287b224 100644
--- a/matlab/McMCDiagnostics.m
+++ b/matlab/McMCDiagnostics.m
@@ -16,7 +16,7 @@ function McMCDiagnostics(options_, estim_params_, M_)
 % PARALLEL CONTEXT
 % See the comment in random_walk_metropolis_hastings.m funtion.
 
-% Copyright (C) 2005-2011 Dynare Team
+% Copyright (C) 2005-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/PlotPosteriorDistributions.m b/matlab/PlotPosteriorDistributions.m
index dbbe3d3b6ae0796199686911cb443a12fc2c4240..ba6510eea5017c5ccef193fe451ec4da0a81f5bb 100644
--- a/matlab/PlotPosteriorDistributions.m
+++ b/matlab/PlotPosteriorDistributions.m
@@ -16,7 +16,7 @@ function oo_ = PlotPosteriorDistributions(estim_params_, M_, options_, bayestopt
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2005-2011 Dynare Team
+% Copyright (C) 2005-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/PosteriorFilterSmootherAndForecast.m b/matlab/PosteriorFilterSmootherAndForecast.m
index 4cce1159e5a9c8068ec79b80c5e5b7df05dec99e..eba61007d2127d87a446b691e4ee9ab7d2ffd32d 100644
--- a/matlab/PosteriorFilterSmootherAndForecast.m
+++ b/matlab/PosteriorFilterSmootherAndForecast.m
@@ -16,7 +16,7 @@ function PosteriorFilterSmootherAndForecast(Y,gend, type,data_index)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2005-2011 Dynare Team
+% Copyright (C) 2005-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -135,7 +135,7 @@ end
 for b=1:B
     %deep = GetOneDraw(NumberOfDraws,FirstMhFile,LastMhFile,FirstLine,MAX_nruns,DirectoryName);
     [deep, logpo] = GetOneDraw(type);
-    set_all_parameters(deep);
+    M_ = set_all_parameters(deep,estim_params_,M_);
     [dr,info,M_,options_,oo_] = resol(0,M_,options_,oo_);
     [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK] = ...
         DsgeSmoother(deep,gend,Y,data_index);
diff --git a/matlab/PosteriorIRF.m b/matlab/PosteriorIRF.m
index ec7cdf17372efcbe6f1a4a36065114f3d4d4fe0e..c78733e383101727c1ef345a16edc1ca3bdfcaa3 100644
--- a/matlab/PosteriorIRF.m
+++ b/matlab/PosteriorIRF.m
@@ -16,7 +16,7 @@ function PosteriorIRF(type)
 % functions associated with it(the _core1 and _core2).
 % See also the comments random_walk_metropolis_hastings.m funtion.
 
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -162,7 +162,6 @@ end
 % function.
 
 b = 0;
-nosaddle = 0;
 
 localVars=[];
 
@@ -171,7 +170,6 @@ localVars=[];
 localVars.IRUN = IRUN;
 localVars.irun = irun;
 localVars.irun2=irun2;
-localVars.nosaddle=nosaddle;
 localVars.npar = npar;
 
 localVars.type=type;
@@ -208,6 +206,7 @@ localVars.MhDirectoryName=MhDirectoryName;
 % Like sequential execution!
 if isnumeric(options_.parallel),
     [fout] = PosteriorIRF_core1(localVars,1,B,0);
+    nosaddle = fout.nosaddle;
 else
     % Parallel execution!
     [nCPU, totCPU, nBlockPerCPU] = distributeJobs(options_.parallel, 1, B);
@@ -241,6 +240,10 @@ else
         NamFileInput(length(NamFileInput)+1,:)={'',[M_.fname '_steadystate.m']};
     end
     [fout] = masterParallel(options_.parallel, 1, B,NamFileInput,'PosteriorIRF_core1', localVars, globalVars, options_.parallel_info);
+    nosaddle=0;
+    for j=1:length(fout),
+        nosaddle = nosaddle + fout(j).nosaddle;
+    end
     
 end
 
diff --git a/matlab/PosteriorIRF_core1.m b/matlab/PosteriorIRF_core1.m
index d89308db9b46ec20d0308ae8df70fd72584d5d72..115327fa8afcab8d918e0927df0739b311730f21 100644
--- a/matlab/PosteriorIRF_core1.m
+++ b/matlab/PosteriorIRF_core1.m
@@ -1,4 +1,4 @@
-function myoutput=PosteriorIRF_core1(myinputs,fpar,npar,whoiam, ThisMatlab)
+function myoutput=PosteriorIRF_core1(myinputs,fpar,B,whoiam, ThisMatlab)
 %   PARALLEL CONTEXT
 %   This function perfom in parallel a portion of  PosteriorIRF.m code.
 %   This is a special kind of parallel function. Unlike of other parallel functions,
@@ -22,7 +22,7 @@ function myoutput=PosteriorIRF_core1(myinputs,fpar,npar,whoiam, ThisMatlab)
 % SPECIAL REQUIREMENTS.
 %   None.
 %
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -52,7 +52,6 @@ end
 IRUN = myinputs.IRUN;
 irun =myinputs.irun;
 irun2=myinputs.irun2;
-nosaddle=myinputs.nosaddle;
 npar=myinputs.npar;
 type=myinputs.type;
 if ~strcmpi(type,'prior'),
@@ -124,6 +123,7 @@ OutputFileName_param = {};
 
 fpar = fpar-1;
 fpar0=fpar;
+nosaddle=0;
 
 if whoiam
     ifil2=ifil2(whoiam);
@@ -134,7 +134,7 @@ end
 % Parallel 'while' very good!!!
 stock_param=zeros(MAX_nruns,npar);
 stock_irf_dsge=zeros(options_.irf,nvar,M_.exo_nbr,MAX_nirfs_dsge);
-while fpar<npar
+while fpar<B
     fpar = fpar + 1;
     irun = irun+1;
     irun2 = irun2+1;
@@ -163,8 +163,12 @@ while fpar<npar
         elseif info(1) == 5
             errordef = 'Rank condition  is not satisfied';
         end
-        disp(['PosteriorIRF :: Dynare is unable to solve the model (' errordef ')'])
-        continue
+        if strcmpi(type,'prior'),
+            disp(['PosteriorIRF :: Dynare is unable to solve the model (' errordef ')'])
+            continue
+        else
+            error(['PosteriorIRF :: Dynare is unable to solve the model (' errordef ') with sample ' type])
+        end
     end
     SS(M_.exo_names_orig_ord,M_.exo_names_orig_ord) = M_.Sigma_e+1e-14*eye(M_.exo_nbr);
     SS = transpose(chol(SS));
@@ -240,10 +244,10 @@ while fpar<npar
             stock_irf_dsgevar = zeros(options_.irf,dataset_.info.nvobs,M_.exo_nbr,MAX_nirfs_dsgevar);
         end
     end
-    if irun == MAX_nirfs_dsge || irun == npar || fpar == npar
-        if fpar == npar
+    if irun == MAX_nirfs_dsge || irun == B || fpar == B
+        if fpar == B
             stock_irf_dsge = stock_irf_dsge(:,:,:,1:irun);
-            if MAX_nirfs_dsgevar && (fpar == npar || IRUN == npar)
+            if MAX_nirfs_dsgevar && (fpar == B || IRUN == B)
                 stock_irf_bvardsge = stock_irf_bvardsge(:,:,:,1:IRUN);
                 instr = [MhDirectoryName '/' M_.fname '_irf_bvardsge' ...
                          int2str(NumberOfIRFfiles_dsgevar) '.mat stock_irf_bvardsge;'];
@@ -262,8 +266,8 @@ while fpar<npar
         NumberOfIRFfiles_dsge = NumberOfIRFfiles_dsge+1;
         irun = 0;
     end
-    if irun2 == MAX_nruns || fpar == npar
-        if fpar == npar
+    if irun2 == MAX_nruns || fpar == B
+        if fpar == B
             stock_param = stock_param(1:irun2,:);
         end
         stock = stock_param;
@@ -276,26 +280,26 @@ while fpar<npar
     end
 %     if exist('OCTAVE_VERSION'),
 %         if (whoiam==0),
-%             printf(['Posterior IRF  %3.f%% done\r'],(fpar/npar*100));
+%             printf(['Posterior IRF  %3.f%% done\r'],(fpar/B*100));
 %         end
 %     elseif ~whoiam,
-%         waitbar(fpar/npar,h);
+%         waitbar(fpar/B,h);
 %     end
 %     if whoiam,
 %         if ~exist('OCTAVE_VERSION')
 %             fprintf('Done! \n');
 %         end
-%         waitbarString = [ 'Subdraw ' int2str(fpar) '/' int2str(npar) ' done.'];
-%         fMessageStatus((fpar-fpar0)/(npar-fpar0),whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab));
+%         waitbarString = [ 'Subdraw ' int2str(fpar) '/' int2str(B) ' done.'];
+%         fMessageStatus((fpar-fpar0)/(B-fpar0),whoiam,waitbarString, waitbarTitle, Parallel(ThisMatlab));
 %     end
-    dyn_waitbar((fpar-fpar0)/(npar-fpar0),h);
+    dyn_waitbar((fpar-fpar0)/(B-fpar0),h);
 end
 
 dyn_waitbar_close(h);
 
 if whoiam==0
     if nosaddle
-        disp(['PosteriorIRF :: Percentage of discarded posterior draws = ' num2str(nosaddle/(npar+nosaddle))])
+        disp(['PosteriorIRF :: Percentage of discarded posterior draws = ' num2str(nosaddle/(B+nosaddle))])
     end
 end
 
@@ -305,6 +309,8 @@ end
 myoutput.OutputFileName = [OutputFileName_dsge;
                     OutputFileName_param;
                     OutputFileName_bvardsge];
+                
+myoutput.nosaddle = nosaddle;
 
 
 
diff --git a/matlab/PosteriorIRF_core2.m b/matlab/PosteriorIRF_core2.m
index ba0f686018809a0405a9e0a62bb4befef04bd74c..6a693a4a387d85d8bcdbe0d7acafa95e5f8e06ae 100644
--- a/matlab/PosteriorIRF_core2.m
+++ b/matlab/PosteriorIRF_core2.m
@@ -17,7 +17,7 @@ function myoutput=PosteriorIRF_core2(myinputs,fpar,npar,whoiam, ThisMatlab)
 % SPECIAL REQUIREMENTS.
 %   None.
 %
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -89,7 +89,6 @@ for i=fpar:npar,
     for j=1:nvar
         if max(abs(MeanIRF(:,j,i))) > 10^(-6)
             subplotnum = subplotnum+1;
-            dyn_figure(options_,'Name',['Relative response to orthogonalized shock to ' tit(i,:)])
             if subplotnum == 1 && options_.relative_irf
                 hh = dyn_figure(options_,'Name',['Relative response to orthogonalized shock to ' tit(i,:)]);
             elseif subplotnum == 1 && ~options_.relative_irf
diff --git a/matlab/ReshapeMatFiles.m b/matlab/ReshapeMatFiles.m
index fc99e4afbb36c23897d16c3fd191a104bd67491b..06acd73722da37d768502f447384d7e93a871c7f 100644
--- a/matlab/ReshapeMatFiles.m
+++ b/matlab/ReshapeMatFiles.m
@@ -25,7 +25,7 @@ function ReshapeMatFiles(type, type2)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2010 Dynare Team
+% Copyright (C) 2003-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/UnivariateSpectralDensity.m b/matlab/UnivariateSpectralDensity.m
index c8c2725865ba6b34b437e660c1fdd9090821874c..d5f854b516648a18bc2705ad25dd48857d9d06b8 100644
--- a/matlab/UnivariateSpectralDensity.m
+++ b/matlab/UnivariateSpectralDensity.m
@@ -5,7 +5,7 @@ function [omega,f] = UnivariateSpectralDensity(dr,var_list)
 % 
 % Adapted from th_autocovariances.m.  
 
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/block_mfs_steadystate.m b/matlab/block_mfs_steadystate.m
index e027ecb4c26fe58885604ab66c209031f4cec590..78a87b442a4bf19333613963bd979b22ed2878c6 100644
--- a/matlab/block_mfs_steadystate.m
+++ b/matlab/block_mfs_steadystate.m
@@ -2,7 +2,7 @@ function [r, g1] = block_mfs_steadystate(y, b, y_all, exo, params, M)
 % Wrapper around the *_static.m file, for use with dynare_solve,
 % when block_mfs option is given to steady.
 
-% Copyright (C) 2009-2010 Dynare Team
+% Copyright (C) 2009-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/bvar_forecast.m b/matlab/bvar_forecast.m
index 632330bb965e325dcf020ff379a09101967cbe5c..62b6f847cf5f901db9c18645c6a48cafb851a8b6 100644
--- a/matlab/bvar_forecast.m
+++ b/matlab/bvar_forecast.m
@@ -11,7 +11,7 @@ function bvar_forecast(nlags)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2007-2010,2012 Dynare Team
+% Copyright (C) 2007-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/bvar_irf.m b/matlab/bvar_irf.m
index 0e8d3b27221cebd20f57dc3877a55aaefe9e4412..b46799f6afec66acec9fb30d991513b52c806381 100644
--- a/matlab/bvar_irf.m
+++ b/matlab/bvar_irf.m
@@ -11,7 +11,7 @@ function bvar_irf(nlags,identification)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2007-2009,2012 Dynare Team
+% Copyright (C) 2007-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/bytecode_steadystate.m b/matlab/bytecode_steadystate.m
index 3544034969a326c41f5a4aef218fe5ec581fe00f..4c3e2f46f9e4883d906171c038add32e5e15ada7 100644
--- a/matlab/bytecode_steadystate.m
+++ b/matlab/bytecode_steadystate.m
@@ -2,7 +2,7 @@ function [r, g1] = bytecode_steadystate(y, exo, params)
 % Wrapper around the *_static.m file, for use with dynare_solve,
 % when block_mfs option is given to steady.
 
-% Copyright (C) 2009-2010 Dynare Team
+% Copyright (C) 2009-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/check.m b/matlab/check.m
index 381b95f9ebc69a876d4df264f681dc41d801bc05..6014bfdf192f8e6c5363accdc3f78839f2233732 100644
--- a/matlab/check.m
+++ b/matlab/check.m
@@ -66,7 +66,7 @@ if isempty(options.qz_criterium)
     options.qz_criterium = 1+1e-6;
 end
 
-oo.dr=set_state_space(oo.dr,M);
+oo.dr=set_state_space(oo.dr,M,options);
 
 [dr,info,M,options,oo] = resol(1,M,options,oo);
 
diff --git a/matlab/check_list_of_variables.m b/matlab/check_list_of_variables.m
index 23696fd6f61eda8128a7771a2ffd9111d7cdb7a1..4b1b693847c2fcdeead8292ad98e604472ab4cca 100644
--- a/matlab/check_list_of_variables.m
+++ b/matlab/check_list_of_variables.m
@@ -14,7 +14,7 @@ function varlist = check_list_of_variables(options_, M_, varlist)
 %        
 % SPECIAL REQUIREMENTS
 
-% Copyright (C) 2003-2010 Dynare Team
+% Copyright (C) 2003-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/check_model.m b/matlab/check_model.m
index 7e15d8d1c7523e4e2978b2a5ff4d6b29f275e257..8ab34e39312bc7e05e30cad716c3cafbb521f6a2 100644
--- a/matlab/check_model.m
+++ b/matlab/check_model.m
@@ -1,4 +1,4 @@
-function check_model()
+function check_model(DynareModel)
 
 % Copyright (C) 2005-2011 Dynare Team
 %
@@ -17,10 +17,8 @@ function check_model()
 % 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_
-
-xlen = M_.maximum_exo_lag+M_.maximum_exo_lead + 1;
-if ~ M_.lead_lag_incidence(M_.maximum_lag+1,:) > 0
+xlen = DynareModel.maximum_exo_lag+DynareModel.maximum_exo_lead + 1;
+if ~ DynareModel.lead_lag_incidence(DynareModel.maximum_lag+1,:) > 0
     error ('RESOL: Error in model specification: some variables don"t appear as current') ;
 end
 
@@ -29,8 +27,7 @@ if xlen > 1
             ' current period. Use additional endogenous variables']) ;
 end
 
-if (M_.exo_det_nbr > 0) && (M_.maximum_lag > 1 || M_.maximum_lead > 1)
+if (DynareModel.exo_det_nbr > 0) && (DynareModel.maximum_lag > 1 || DynareModel.maximum_lead > 1)
     error(['Exogenous deterministic variables are currently only allowed in' ...
            ' models with leads and lags on only one period'])
-end
-
+end
\ No newline at end of file
diff --git a/matlab/check_prior_analysis_data.m b/matlab/check_prior_analysis_data.m
index e60d586d28d61aef193e013f6539a1401c99b995..cb4e2913c665960201cd2c93c33a5cc4a0eb4081 100644
--- a/matlab/check_prior_analysis_data.m
+++ b/matlab/check_prior_analysis_data.m
@@ -1,5 +1,5 @@
 function [info,description] = check_prior_analysis_data(type,M_)
-% Copyright (C) 2009 Dynare Team
+% Copyright (C) 2009-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/compute_mh_covariance_matrix.m b/matlab/compute_mh_covariance_matrix.m
index 90c4a5e9d7fd54e13160463d9d22ce8d2bf5c0c8..558c19d4c3056ba8f3d96b6195738a7b605eea2f 100644
--- a/matlab/compute_mh_covariance_matrix.m
+++ b/matlab/compute_mh_covariance_matrix.m
@@ -15,7 +15,7 @@ function [posterior_mean,posterior_covariance,posterior_mode,posterior_kernel_at
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2006-2010 Dynare Team
+% Copyright (C) 2006-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/conditional_variance_decomposition.m b/matlab/conditional_variance_decomposition.m
index 806fe94ba31df6ab904cd0b24f7d12698cdc76fd..3ecf7441039d3f1ef60b8c729d45f0b3b1f00d06 100644
--- a/matlab/conditional_variance_decomposition.m
+++ b/matlab/conditional_variance_decomposition.m
@@ -16,7 +16,7 @@ function ConditionalVarianceDecomposition = conditional_variance_decomposition(S
 %
 % [1] In this version, absence of measurement errors is assumed...
 
-% Copyright (C) 2010 Dynare Team
+% Copyright (C) 2010-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/convertAimCodeToInfo.m b/matlab/convertAimCodeToInfo.m
index 877bf24475ee4a45e3543773552f0a1ad85b9f35..2aaf05be70e1f4c83fa808285489b187aa7683d6 100644
--- a/matlab/convertAimCodeToInfo.m
+++ b/matlab/convertAimCodeToInfo.m
@@ -19,7 +19,7 @@ function [info] = convertAimCodeToInfo(aimCode)
 % OUTPUTS
 %   info        [integer]    Code to be used to print error in print_info.m
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/cosn.m b/matlab/cosn.m
index 7d60c88e58e7182b2c030a7ea191cff5734a87f6..216efd19388339ac1a0927b53c6125cb5d2716a3 100644
--- a/matlab/cosn.m
+++ b/matlab/cosn.m
@@ -7,7 +7,7 @@ function [co, b, yhat] = cosn(H);
 % Not the same as multiple correlation coefficient since the means are not
 % zero
 %
-% Copyright (C) 2008-2010 Dynare Team
+% Copyright (C) 2008-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -28,6 +28,9 @@ y = H(:,1);
 X = H(:,2:end);
 
 b=(X\y);
+if any(isnan(b)) || any(isinf(b)),
+    b=0;
+end
 yhat =  X*b;
 if rank(yhat),
     co = abs(y'*yhat/sqrt((y'*y)*(yhat'*yhat)));
diff --git a/matlab/csminwel1.m b/matlab/csminwel1.m
index 0698c05958d19451e4fd5a994685f1bbd843fa59..4981da01d044ef24ed2bcaaeb215731cf886bbd7 100644
--- a/matlab/csminwel1.m
+++ b/matlab/csminwel1.m
@@ -23,7 +23,7 @@ function [fh,xh,gh,H,itct,fcount,retcodeh] = csminwel1(fcn,x0,H0,grad,crit,nit,m
 % http://sims.princeton.edu/yftp/optimize/mfiles/csminwel.m
 
 % Copyright (C) 1993-2007 Christopher Sims
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -288,7 +288,7 @@ while ~done
     %badgh
     stuck = (abs(fh-f) < crit);
     if (~badg) && (~badgh) && (~stuck)
-        H = bfgsi(H,gh-g,xh-x);
+        H = bfgsi1(H,gh-g,xh-x);
     end
     if Verbose
         disp('----')
diff --git a/matlab/cycle_reduction.m b/matlab/cycle_reduction.m
new file mode 100644
index 0000000000000000000000000000000000000000..04fca27a746eac1ae6a9a45eda18c618782b4703
--- /dev/null
+++ b/matlab/cycle_reduction.m
@@ -0,0 +1,134 @@
+function [X, info] = cycle_reduction(A0, A1, A2, cvg_tol, ch)
+
+%@info:
+%! @deftypefn {Function File} {[@var{X}, @var{info}] =} cycle_reduction (@var{A0},@var{A1},@var{A2},@var{cvg_tol},@var{ch})
+%! @anchor{cycle_reduction}
+%! @sp 1
+%! Solves the quadratic matrix equation A2*X^2 + A1*X + A0 = 0.
+%! @sp 2
+%! @strong{Inputs}
+%! @sp 1
+%! @table @ @var
+%! @item A0
+%! Square matrix of doubles, n*n.
+%! @item A1
+%! Square matrix of doubles, n*n.
+%! @item A2
+%! Square matrix of doubles, n*n.
+%! @item cvg_tol
+%! Scalar double, tolerance parameter.
+%! @item ch
+%! Any matlab object, if not empty the solution is checked.
+%! @end table
+%! @sp 1
+%! @strong{Outputs}
+%! @sp 1
+%! @table @ @var
+%! @item X
+%! Square matrix of doubles, n*n, solution of the matrix equation.
+%! @item info
+%! Scalar integer, if nonzero the algorithm failed in finding the solution of the matrix equation.
+%! @end table
+%! @sp 2
+%! @strong{This function is called by:}
+%! @sp 2
+%! @strong{This function calls:}
+%! @sp 2
+%! @strong{References:}
+%! @sp 1
+%! D.A. Bini, G. Latouche, B. Meini (2002), "Solving matrix polynomial equations arising in queueing problems", Linear Algebra and its Applications 340, pp. 222-244
+%! @sp 1
+%! D.A. Bini, B. Meini (1996), "On the solution of a nonlinear matrix equation arising in queueing problems", SIAM J. Matrix Anal. Appl. 17, pp. 906-926.
+%! @sp 2
+%! @end deftypefn
+%@eod:
+
+% Copyright (C) 2012 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/>.
+
+max_it = 300;
+it = 0;
+info = 0;
+X = [];
+crit = Inf;
+A0_0 = A0;
+Ahat1 = A1;
+if (nargin == 5 && ~isempty(ch) )
+    A1_0 = A1;
+    A2_0 = A2;
+end
+n = length(A0);
+id0 = 1:n;
+id2 = id0+n;
+
+cont = 1;
+while cont 
+    tmp = ([A0; A2]/A1)*[A0 A2];
+    A1 = A1 - tmp(id0,id2) - tmp(id2,id0);
+    A0 = -tmp(id0,id0);
+    A2 = -tmp(id2,id2);
+    Ahat1 = Ahat1 -tmp(id2,id0);
+    crit = norm(A0,1);
+    if crit < cvg_tol
+        % keep iterating until condition on A2 is met
+        if norm(A2,1) < cvg_tol
+            cont = 0;
+        end
+    elseif isnan(crit) || it == max_it
+        if crit < cvg_tol
+            info(1) = 4;
+            info(2) = log(norm(A2,1));
+        else
+            info(1) = 3;
+            info(2) = log(norm(A1,1));
+        end
+        return
+    end        
+    it = it + 1;
+end
+
+X = -Ahat1\A0_0;
+
+if (nargin == 5 && ~isempty(ch) )
+    %check the solution
+    res = A0_0 + A1_0 * X + A2_0 * X * X;
+    if (sum(sum(abs(res))) > cvg_tol)
+        disp(['the norm residual of the residu ' num2str(res) ' compare to the tolerance criterion ' num2str(cvg_tol)]);
+    end
+end
+
+%@test:1
+%$ addpath ../matlab
+%$
+%$ % Set the dimension of the problem to be solved
+%$ n = 2000;
+%$ % Set the equation to be solved
+%$ A = eye(n);
+%$ B = diag(30*ones(n,1)); B(1,1) = 20; B(end,end) = 20; B = B - diag(10*ones(n-1,1),-1); B = B - diag(10*ones(n-1,1),1);
+%$ C = diag(15*ones(n,1)); C = C - diag(5*ones(n-1,1),-1); C = C - diag(5*ones(n-1,1),1);
+%$
+%$ % Solve the equation with the cycle reduction algorithm
+%$ tic, X1 = cycle_reduction(C,B,A,1e-7); toc
+%$
+%$ % Solve the equation with the logarithmic reduction algorithm
+%$ tic, X2 = logarithmic_reduction(A,B,C,1e-16,100); toc
+%$
+%$ % Check the results.
+%$ t(1) = dyn_assert(X1,X2,1e-12);
+%$
+%$ T = all(t);
+%@eof:1
\ No newline at end of file
diff --git a/matlab/discretionary_policy_1.m b/matlab/discretionary_policy_1.m
index 2541df0a7824474a5ea943f945e0fe5466436c6c..b7be8f028278fa9ab6e7c2456430ca4dd9c9e190 100644
--- a/matlab/discretionary_policy_1.m
+++ b/matlab/discretionary_policy_1.m
@@ -1,157 +1,161 @@
-function [dr,ys,info]=discretionary_policy_1(oo_,Instruments)
-
-% Copyright (C) 2007-2012 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_
-persistent Hold
-
-options_ = set_default_option(options_,'qz_criterium',1.000001);
-options_ = set_default_option(options_,'solve_maxit',3000);
-
-% safeguard against issues like running ramsey policy first and then running discretion
-if isfield(M_,'orig_model')
-    orig_model = M_.orig_model;
-    M_.endo_nbr = orig_model.endo_nbr;
-    M_.endo_names = orig_model.endo_names;
-    M_.lead_lag_incidence = orig_model.lead_lag_incidence;
-    M_.maximum_lead = orig_model.maximum_lead;
-    M_.maximum_endo_lead = orig_model.maximum_endo_lead;
-    M_.maximum_lag = orig_model.maximum_lag;
-    M_.maximum_endo_lag = orig_model.maximum_endo_lag;
-else
-	M_.orig_model = M_;
-end
-
-beta = get_optimal_policy_discount_factor(M_.params,M_.param_names);
-
-exo_nbr = M_.exo_nbr;
-if isfield(M_,'orig_model')
-    orig_model = M_.orig_model;
-    endo_nbr = orig_model.endo_nbr;
-    endo_names = orig_model.endo_names;
-    lead_lag_incidence = orig_model.lead_lag_incidence;
-    MaxLead = orig_model.maximum_lead;
-    MaxLag = orig_model.maximum_lag;
-else
-	endo_names = M_.endo_names;
-	endo_nbr = M_.endo_nbr;
-	MaxLag=M_.maximum_lag;
-	MaxLead=M_.maximum_lead;
-    lead_lag_incidence = M_.lead_lag_incidence;
-end
-
-[U,Uy,W] = feval([M_.fname,'_objective_static'],zeros(endo_nbr,1),[], M_.params);
-if any(any(Uy~=0))
-    error(['discretionary_policy: the objective function must have zero ' ...
-           'first order derivatives'])
-end
-
-W=reshape(W,endo_nbr,endo_nbr);
-
-klen = MaxLag + MaxLead + 1;
-iyv=lead_lag_incidence';
-% Find the jacobian
-z = repmat(zeros(endo_nbr,1),1,klen);
-z = z(nonzeros(iyv)) ;
-it_ = MaxLag + 1 ;
-
-if exo_nbr == 0
-    oo_.exo_steady_state = [] ;
-end
-[junk,jacobia_] = feval([M_.fname '_dynamic'],z, [oo_.exo_simul ...
-                    oo_.exo_det_simul], M_.params, zeros(endo_nbr,1), it_);
-if any(junk~=0)
-    error(['discretionary_policy: the model must be written in deviation ' ...
-           'form and not have constant terms'])
-end
-
-eq_nbr= size(jacobia_,1);
-instr_nbr=endo_nbr-eq_nbr;
-
-instr_id=nan(instr_nbr,1);
-for j=1:instr_nbr
-	vj=deblank(Instruments(j,:));
-	vj_id=strmatch(vj,endo_names,'exact');
-	if ~isempty(vj_id)
-		instr_id(j)=vj_id;
-	else
-		error([mfilename,':: instrument ',vj,' not found'])
-	end
-end
-
-Indices={'lag','0','lead'};
-iter=1;
-for j=1:numel(Indices)
-    eval(['A',Indices{j},'=zeros(eq_nbr,endo_nbr);'])
-	if strcmp(Indices{j},'0')||(strcmp(Indices{j},'lag') && MaxLag)||(strcmp(Indices{j},'lead') && MaxLead)
-	    [junk,row,col]=find(lead_lag_incidence(iter,:));
-	    eval(['A',Indices{j},'(:,row)=jacobia_(:,col);'])
-		iter=iter+1;
-	end
-end
-B=jacobia_(:,nnz(iyv)+1:end);
-
-%%% MAIN ENGINE %%%
-qz_criterium = options_.qz_criterium;
-solve_maxit = options_.solve_maxit;
-discretion_tol = options_.discretionary_tol;
-
-if ~isempty(Hold)
-	[H,G,info]=discretionary_policy_engine(Alag,A0,Alead,B,W,instr_id,beta,solve_maxit,discretion_tol,qz_criterium,Hold);
-else
-	[H,G,info]=discretionary_policy_engine(Alag,A0,Alead,B,W,instr_id,beta,solve_maxit,discretion_tol,qz_criterium);
-end
-
-if info
-    dr=[];
-    return
-else
-	Hold=H;
-	% Hold=[]; use this line if persistent command is not used.
-end
-% update the following elements
-
-LLI=lead_lag_incidence;
-LLI(MaxLag,:)=any(H);
-
-LLI=LLI';
-tmp=find(LLI);
-LLI(tmp)=1:numel(tmp);
-
-M_.lead_lag_incidence = LLI';
-
-% set the state
-dr=oo_.dr;
-dr.ys =zeros(endo_nbr,1);
-dr=set_state_space(dr,M_);
-order_var=dr.order_var;
-
-T=H(order_var,order_var);
-dr.ghu=G(order_var,:);
-Selection=any(T);
-dr.ghx=T(:,Selection);
-
-ys=NondistortionarySteadyState(M_);
-dr.ys=ys; % <--- dr.ys =zeros(NewEndo_nbr,1);
-
-function ys=NondistortionarySteadyState(M_)
-if exist([M_.fname,'_steadystate.m'],'file')
-	eval(['ys=',M_.fname,'_steadystate.m;'])
-else
-	ys=zeros(M_.endo_nbr,1);
-end
+function [dr,ys,info]=discretionary_policy_1(oo_,Instruments)
+
+% Copyright (C) 2007-2012 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_
+persistent Hold
+
+dr = [];
+ys = [];
+info = 0;
+
+options_ = set_default_option(options_,'qz_criterium',1.000001);
+options_ = set_default_option(options_,'solve_maxit',3000);
+
+% safeguard against issues like running ramsey policy first and then running discretion
+if isfield(M_,'orig_model')
+    orig_model = M_.orig_model;
+    M_.endo_nbr = orig_model.endo_nbr;
+    M_.endo_names = orig_model.endo_names;
+    M_.lead_lag_incidence = orig_model.lead_lag_incidence;
+    M_.maximum_lead = orig_model.maximum_lead;
+    M_.maximum_endo_lead = orig_model.maximum_endo_lead;
+    M_.maximum_lag = orig_model.maximum_lag;
+    M_.maximum_endo_lag = orig_model.maximum_endo_lag;
+else
+	M_.orig_model = M_;
+end
+
+beta = get_optimal_policy_discount_factor(M_.params,M_.param_names);
+
+exo_nbr = M_.exo_nbr;
+if isfield(M_,'orig_model')
+    orig_model = M_.orig_model;
+    endo_nbr = orig_model.endo_nbr;
+    endo_names = orig_model.endo_names;
+    lead_lag_incidence = orig_model.lead_lag_incidence;
+    MaxLead = orig_model.maximum_lead;
+    MaxLag = orig_model.maximum_lag;
+else
+	endo_names = M_.endo_names;
+	endo_nbr = M_.endo_nbr;
+	MaxLag=M_.maximum_lag;
+	MaxLead=M_.maximum_lead;
+    lead_lag_incidence = M_.lead_lag_incidence;
+end
+
+[U,Uy,W] = feval([M_.fname,'_objective_static'],zeros(endo_nbr,1),[], M_.params);
+if any(any(Uy~=0))
+    error(['discretionary_policy: the objective function must have zero ' ...
+           'first order derivatives'])
+end
+
+W=reshape(W,endo_nbr,endo_nbr);
+
+klen = MaxLag + MaxLead + 1;
+iyv=lead_lag_incidence';
+% Find the jacobian
+z = repmat(zeros(endo_nbr,1),1,klen);
+z = z(nonzeros(iyv)) ;
+it_ = MaxLag + 1 ;
+
+if exo_nbr == 0
+    oo_.exo_steady_state = [] ;
+end
+[junk,jacobia_] = feval([M_.fname '_dynamic'],z, [oo_.exo_simul ...
+                    oo_.exo_det_simul], M_.params, zeros(endo_nbr,1), it_);
+if any(junk~=0)
+    error(['discretionary_policy: the model must be written in deviation ' ...
+           'form and not have constant terms'])
+end
+
+eq_nbr= size(jacobia_,1);
+instr_nbr=endo_nbr-eq_nbr;
+
+instr_id=nan(instr_nbr,1);
+for j=1:instr_nbr
+	vj=deblank(Instruments(j,:));
+	vj_id=strmatch(vj,endo_names,'exact');
+	if ~isempty(vj_id)
+		instr_id(j)=vj_id;
+	else
+		error([mfilename,':: instrument ',vj,' not found'])
+	end
+end
+
+Indices={'lag','0','lead'};
+iter=1;
+for j=1:numel(Indices)
+    eval(['A',Indices{j},'=zeros(eq_nbr,endo_nbr);'])
+	if strcmp(Indices{j},'0')||(strcmp(Indices{j},'lag') && MaxLag)||(strcmp(Indices{j},'lead') && MaxLead)
+	    [junk,row,col]=find(lead_lag_incidence(iter,:));
+	    eval(['A',Indices{j},'(:,row)=jacobia_(:,col);'])
+		iter=iter+1;
+	end
+end
+B=jacobia_(:,nnz(iyv)+1:end);
+
+%%% MAIN ENGINE %%%
+qz_criterium = options_.qz_criterium;
+solve_maxit = options_.solve_maxit;
+discretion_tol = options_.discretionary_tol;
+
+if ~isempty(Hold)
+	[H,G,info]=discretionary_policy_engine(Alag,A0,Alead,B,W,instr_id,beta,solve_maxit,discretion_tol,qz_criterium,Hold);
+else
+	[H,G,info]=discretionary_policy_engine(Alag,A0,Alead,B,W,instr_id,beta,solve_maxit,discretion_tol,qz_criterium);
+end
+
+if info
+    dr=[];
+    return
+else
+	Hold=H;
+	% Hold=[]; use this line if persistent command is not used.
+end
+% update the following elements
+
+LLI=lead_lag_incidence;
+LLI(MaxLag,:)=any(H);
+
+LLI=LLI';
+tmp=find(LLI);
+LLI(tmp)=1:numel(tmp);
+
+M_.lead_lag_incidence = LLI';
+
+% set the state
+dr=oo_.dr;
+dr.ys =zeros(endo_nbr,1);
+dr=set_state_space(dr,M_,options_);
+order_var=dr.order_var;
+
+T=H(order_var,order_var);
+dr.ghu=G(order_var,:);
+Selection=any(T);
+dr.ghx=T(:,Selection);
+
+ys=NondistortionarySteadyState(M_);
+dr.ys=ys; % <--- dr.ys =zeros(NewEndo_nbr,1);
+
+function ys=NondistortionarySteadyState(M_)
+if exist([M_.fname,'_steadystate.m'],'file')
+	eval(['ys=',M_.fname,'_steadystate.m;'])
+else
+	ys=zeros(M_.endo_nbr,1);
+end
diff --git a/matlab/discretionary_policy_engine.m b/matlab/discretionary_policy_engine.m
index 67aef9f237e132b7e374ba7075083c8d1b63a112..9b94d7301b5f7708f71f8f3dfb517160610b23c6 100644
--- a/matlab/discretionary_policy_engine.m
+++ b/matlab/discretionary_policy_engine.m
@@ -1,298 +1,299 @@
-function [H,G,retcode]=discretionary_policy_engine(AAlag,AA0,AAlead,BB,bigw,instr_id,beta,solve_maxit,discretion_tol,qz_criterium,H00,verbose)
-
-% Solves the discretionary problem for a model of the form:
-% AAlag*yy_{t-1}+AA0*yy_t+AAlead*yy_{t+1}+BB*e=0, with W the weight on the
-% variables in vector y_t and instr_id is the location of the instruments
-% in the yy_t vector.
-% We use the Dennis algorithm and so we need to re-write the model in the
-% form A0*y_t=A1*y_{t-1}+A2*y_{t+1}+A3*x_t+A4*x_{t+1}+A5*e_t, with W the
-% weight on the y_t vector and Q the weight on the x_t vector of
-% instruments.
-
-% Copyright (C) 2007-2011 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<12
-    verbose=0;
-    if nargin<11
-        H00=[];
-        if nargin<10
-            qz_criterium=1.000001;
-            if nargin<9
-                discretion_tol=sqrt(eps);
-                if nargin<8
-                    solve_maxit=3000;
-                    if nargin<7
-                        beta=.99;
-                        if nargin<6
-                            error([mfilename,':: Insufficient number of input arguments'])
-                        elseif nargin>12
-                            error([mfilename,':: Number of input arguments cannot exceed 12'])
-                        end
-                    end
-                end
-            end
-        end
-    end
-end
-
-[A0,A1,A2,A3,A4,A5,W,Q,endo_nbr,exo_nbr,aux,endo_augm_id]=GetDennisMatrices(AAlag,AA0,AAlead,BB,bigw,instr_id);
-% aux is a logical index of the instruments which appear with lags in the
-% model. Their location in the state vector is instr_id(aux)
-% endo_augm_id is index (not logical) of locations of the augmented vector
-% of non-instrumental variables
-
-AuxiliaryVariables_nbr=sum(aux);
-H0=zeros(endo_nbr+AuxiliaryVariables_nbr);
-if ~isempty(H00)
-    H0(1:endo_nbr,1:endo_nbr)=H00;clear H00
-end
-
-H10=H0(endo_augm_id,endo_augm_id);
-F10=H0(instr_id,endo_augm_id);
-
-iter=0;
-H1=H10;
-F1=F10;
-while 1
-    iter=iter+1;
-    P=SylvesterDoubling(W+beta*F1'*Q*F1,beta*H1',H1,discretion_tol,solve_maxit);
-    if any(any(isnan(P)))
-        P=SylvesterHessenbergSchur(W+beta*F1'*Q*F1,beta*H1',H1);
-        if any(any(isnan(P)))
-            retcode=2;
-            return
-        end
-    end
-    D=A0-A2*H1-A4*F1;
-    Dinv=inv(D);
-    A3DPD=A3'*Dinv'*P*Dinv;
-    F1=-(Q+A3DPD*A3)\(A3DPD*A1);
-    H1=Dinv*(A1+A3*F1);
-    
-    [rcode,NQ]=CheckConvergence([H1;F1]-[H10;F10],iter,solve_maxit,discretion_tol);
-    if rcode
-        break
-    else
-        if verbose
-            disp(NQ)
-        end
-    end
-    H10=H1;
-    F10=F1;
-end
-
-retcode = 0;
-switch rcode
-  case 3 % nan
-    retcode=63;
-    retcode(2)=10000;
-    if verbose
-        disp([mfilename,':: NAN elements in the solution'])
-    end
-  case 2% maxiter
-    retcode = 61
-    if verbose
-        disp([mfilename,':: Maximum Number of Iterations reached'])
-    end
-  case 1
-    BadEig=max(abs(eig(H1)))>qz_criterium;
-    if BadEig
-        retcode=62;
-        retcode(2)=100*max(abs(eig(H1)));
-        if verbose
-            disp([mfilename,':: Some eigenvalues greater than qz_criterium, Model potentially unstable'])
-        end
-    end
-end
-
-if retcode(1)
-    H=[];
-    G=[];
-else
-    F2=-(Q+A3DPD*A3)\(A3DPD*A5);
-    H2=Dinv*(A5+A3*F2);
-    H=zeros(endo_nbr+AuxiliaryVariables_nbr);
-    G=zeros(endo_nbr+AuxiliaryVariables_nbr,exo_nbr);
-    H(endo_augm_id,endo_augm_id)=H1;
-    H(instr_id,endo_augm_id)=F1;
-    G(endo_augm_id,:)=H2;
-    G(instr_id,:)=F2;
-    
-    % Account for auxilliary variables
-    H(:,instr_id(aux))=H(:,end-(AuxiliaryVariables_nbr-1:-1:0));
-    H=H(1:endo_nbr,1:endo_nbr);
-    G=G(1:endo_nbr,:);
-end
-
-end
-
-
-function [rcode,NQ]=CheckConvergence(Q,iter,MaxIter,crit)
-
-NQ=max(max(abs(Q)));% norm(Q); seems too costly
-if isnan(NQ)
-    rcode=3;
-elseif iter>MaxIter;
-    rcode=2;
-elseif NQ<crit
-    rcode=1;
-else
-    rcode=0;
-end
-
-end
-
-function [A00,A11,A22,A33,A44,A55,WW,Q,endo_nbr,exo_nbr,aux,endo_augm_id]=GetDennisMatrices(AAlag,AA0,AAlead,BB,bigw,instr_id)
-[eq_nbr,endo_nbr]=size(AAlag);
-exo_nbr=size(BB,2);
-y=setdiff(1:endo_nbr,instr_id);
-instr_nbr=numel(instr_id);
-
-A0=AA0(:,y);
-A1=-AAlag(:,y);
-A2=-AAlead(:,y);
-A3=-AA0(:,instr_id);
-A4=-AAlead(:,instr_id);
-A5=-BB;
-W=bigw(y,y);
-Q=bigw(instr_id,instr_id);
-% Adjust for possible lags in instruments by creating auxiliary equations
-A6=-AAlag(:,instr_id);
-aux=any(A6);
-AuxiliaryVariables_nbr=sum(aux);
-ny=eq_nbr;
-m=eq_nbr+AuxiliaryVariables_nbr;
-A00=zeros(m);A00(1:ny,1:ny)=A0;A00(ny+1:end,ny+1:end)=eye(AuxiliaryVariables_nbr);
-A11=zeros(m);A11(1:ny,1:ny)=A1;A11(1:ny,ny+1:end)=A6(:,aux);
-A22=zeros(m);A22(1:ny,1:ny)=A2;
-A33=zeros(m,instr_nbr);A33(1:ny,1:end)=A3;A33(ny+1:end,aux)=eye(AuxiliaryVariables_nbr);
-A44=zeros(m,instr_nbr);A44(1:ny,1:end)=A4;
-A55=zeros(m,exo_nbr);A55(1:ny,1:end)=A5;
-WW=zeros(m);WW(1:ny,1:ny)=W;
-endo_augm_id=setdiff(1:endo_nbr+AuxiliaryVariables_nbr,instr_id);
-
-end
-
-function v= SylvesterDoubling (d,g,h,tol,maxit)
-
-% DOUBLES  Solves a Sylvester equation using doubling
-%
-%  [v,info] = doubles (g,d,h,tol,maxit)  uses a doubling algorithm
-%   to solve the  Sylvester equation v  = d + g v h
-
-v = d;
-for i =1:maxit,
-    vadd = g*v*h;
-    v = v+vadd;
-    if norm (vadd,1) <= (tol*norm(v,1))
-        break;
-    end
-    g = g*g;
-    h = h*h;
-end
-
-end
-
-function v = SylvesterHessenbergSchur(d,g,h)
-%
-% DSYLHS  Solves a discrete time sylvester equation	 using the
-% Hessenberg-Schur algorithm
-%
-% v = DSYLHS(g,d,h) computes the matrix v that satisfies the
-% discrete time sylvester equation
-%
-%           v = d + g'vh
-
-if size(g,1) >= size(h,1)
-    [u,gbarp] = hess(g');
-    [t,hbar] = schur(h);
-    [vbar] = sylvest_private(gbarp,u'*d*t,hbar,1e-15);
-    v = u*vbar*t';
-else
-    [u,gbar] = schur(g);
-    [t,hbarp] = hess(h');
-    [vbar] = sylvest_private(hbarp,t'*d'*u,gbar,1e-15);
-    v = u*vbar'*t';
-end
-
-end
-
-
-function v = sylvest_private(g,d,h,tol)
-%
-% SYLVEST  Solves a Sylvester equation
-%
-%  solves the Sylvester equation
-%         v = d + g v h
-%  for v where both g and h must be  upper block triangular.
-%  The output info is zero on a successful return.
-%  The input tol indicates when an element of g or h should be considered
-%  zero.
-
-[m,n] = size(d);
-v = zeros(m,n);
-w = eye(m);
-i = 1;
-temp = [];
-
-%First handle the i = 1 case outside the loop
-
-if i< n,
-    if abs(h(i+1,i)) < tol,
-        v(:,i)= (w - g*h(i,i))\d(:,i);
-        i = i+1;
-    else
-        A = [w-g*h(i,i)     (-g*h(i+1,i));...
-            -g*h(i,i+1)    w-g*h(i+1,i+1)];
-        C = [d(:,i); d(:,i+1)];
-        X = A\C;
-        v(:,i) = X(1:m,:);
-        v(:,i+1) = X(m+1:2*m,  :);
-        i = i+2;
-    end
-end
-
-%Handle the rest of the matrix with the possible exception of i=n
-
-while i<n,
-    b= i-1;
-    temp = [temp g*v(:,size(temp,2)+1:b)]; %#ok<AGROW>
-    if abs(h(i+1,i)) < tol,
-        v(:,i) = (w - g*h(i,i))\(d(:,i) + temp*h(1:b,i));
-        i = i+1;
-    else
-        A = [w - g*h(i,i)    (-g*h(i+1,i));   ...
-            -g*h(i,i+1)    w - g*h(i+1,i+1)];
-        C = [d(:,i) + temp*h(1:b,i);         ...
-            d(:,i+1) + temp*h(1:b,i+1)];
-        X = A\C;
-        v(:,i) = X(1:m,:);
-        v(:,i+1) = X(m+1:2*m, :);
-        i = i+2;
-    end
-end
-
-%Handle the i = n case if i=n was not in a 2-2 block
-
-if i==n,
-    b = i-1;
-    temp = [temp g*v(:,size(temp,2)+1:b)];
-    v(:,i) = (w-g*h(i,i))\(d(:,i) + temp*h(1:b,i));
-end
-
-end
+function [H,G,retcode]=discretionary_policy_engine(AAlag,AA0,AAlead,BB,bigw,instr_id,beta,solve_maxit,discretion_tol,qz_criterium,H00,verbose)
+
+% Solves the discretionary problem for a model of the form:
+% AAlag*yy_{t-1}+AA0*yy_t+AAlead*yy_{t+1}+BB*e=0, with W the weight on the
+% variables in vector y_t and instr_id is the location of the instruments
+% in the yy_t vector.
+% We use the Dennis (2007, Macroeconomic Dynamics) algorithm and so we need
+% to re-write the model in the form
+%  A0*y_t=A1*y_{t-1}+A2*y_{t+1}+A3*x_t+A4*x_{t+1}+A5*e_t, with W the
+% weight on the y_t vector and Q the weight on the x_t vector of
+% instruments.
+
+% Copyright (C) 2007-2012 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<12
+    verbose=0;
+    if nargin<11
+        H00=[];
+        if nargin<10
+            qz_criterium=1.000001;
+            if nargin<9
+                discretion_tol=sqrt(eps);
+                if nargin<8
+                    solve_maxit=3000;
+                    if nargin<7
+                        beta=.99;
+                        if nargin<6
+                            error([mfilename,':: Insufficient number of input arguments'])
+                        elseif nargin>12
+                            error([mfilename,':: Number of input arguments cannot exceed 12'])
+                        end
+                    end
+                end
+            end
+        end
+    end
+end
+
+[A0,A1,A2,A3,A4,A5,W,Q,endo_nbr,exo_nbr,aux,endo_augm_id]=GetDennisMatrices(AAlag,AA0,AAlead,BB,bigw,instr_id);
+% aux is a logical index of the instruments which appear with lags in the
+% model. Their location in the state vector is instr_id(aux)
+% endo_augm_id is index (not logical) of locations of the augmented vector
+% of non-instrumental variables
+
+AuxiliaryVariables_nbr=sum(aux);
+H0=zeros(endo_nbr+AuxiliaryVariables_nbr);
+if ~isempty(H00)
+    H0(1:endo_nbr,1:endo_nbr)=H00;clear H00
+end
+
+H10=H0(endo_augm_id,endo_augm_id);
+F10=H0(instr_id,endo_augm_id);
+
+iter=0;
+H1=H10;
+F1=F10;
+while 1
+    iter=iter+1;
+    P=SylvesterDoubling(W+beta*F1'*Q*F1,beta*H1',H1,discretion_tol,solve_maxit);
+    if any(any(isnan(P)))
+        P=SylvesterHessenbergSchur(W+beta*F1'*Q*F1,beta*H1',H1);
+        if any(any(isnan(P)))
+            retcode=2;
+            return
+        end
+    end
+    D=A0-A2*H1-A4*F1;
+    Dinv=inv(D);
+    A3DPD=A3'*Dinv'*P*Dinv;
+    F1=-(Q+A3DPD*A3)\(A3DPD*A1);
+    H1=Dinv*(A1+A3*F1);
+    
+    [rcode,NQ]=CheckConvergence([H1;F1]-[H10;F10],iter,solve_maxit,discretion_tol);
+    if rcode
+        break
+    else
+        if verbose
+            disp(NQ)
+        end
+    end
+    H10=H1;
+    F10=F1;
+end
+
+retcode = 0;
+switch rcode
+  case 3 % nan
+    retcode=63;
+    retcode(2)=10000;
+    if verbose
+        disp([mfilename,':: NAN elements in the solution'])
+    end
+  case 2% maxiter
+    retcode = 61
+    if verbose
+        disp([mfilename,':: Maximum Number of Iterations reached'])
+    end
+  case 1
+    BadEig=max(abs(eig(H1)))>qz_criterium;
+    if BadEig
+        retcode=62;
+        retcode(2)=100*max(abs(eig(H1)));
+        if verbose
+            disp([mfilename,':: Some eigenvalues greater than qz_criterium, Model potentially unstable'])
+        end
+    end
+end
+
+if retcode(1)
+    H=[];
+    G=[];
+else
+    F2=-(Q+A3DPD*A3)\(A3DPD*A5);
+    H2=Dinv*(A5+A3*F2);
+    H=zeros(endo_nbr+AuxiliaryVariables_nbr);
+    G=zeros(endo_nbr+AuxiliaryVariables_nbr,exo_nbr);
+    H(endo_augm_id,endo_augm_id)=H1;
+    H(instr_id,endo_augm_id)=F1;
+    G(endo_augm_id,:)=H2;
+    G(instr_id,:)=F2;
+    
+    % Account for auxilliary variables
+    H(:,instr_id(aux))=H(:,end-(AuxiliaryVariables_nbr-1:-1:0));
+    H=H(1:endo_nbr,1:endo_nbr);
+    G=G(1:endo_nbr,:);
+end
+
+end
+
+
+function [rcode,NQ]=CheckConvergence(Q,iter,MaxIter,crit)
+
+NQ=max(max(abs(Q)));% norm(Q); seems too costly
+if isnan(NQ)
+    rcode=3;
+elseif iter>MaxIter;
+    rcode=2;
+elseif NQ<crit
+    rcode=1;
+else
+    rcode=0;
+end
+
+end
+
+function [A00,A11,A22,A33,A44,A55,WW,Q,endo_nbr,exo_nbr,aux,endo_augm_id]=GetDennisMatrices(AAlag,AA0,AAlead,BB,bigw,instr_id)
+[eq_nbr,endo_nbr]=size(AAlag);
+exo_nbr=size(BB,2);
+y=setdiff(1:endo_nbr,instr_id);
+instr_nbr=numel(instr_id);
+
+A0=AA0(:,y);
+A1=-AAlag(:,y);
+A2=-AAlead(:,y);
+A3=-AA0(:,instr_id);
+A4=-AAlead(:,instr_id);
+A5=-BB;
+W=bigw(y,y);
+Q=bigw(instr_id,instr_id);
+% Adjust for possible lags in instruments by creating auxiliary equations
+A6=-AAlag(:,instr_id);
+aux=any(A6);
+AuxiliaryVariables_nbr=sum(aux);
+ny=eq_nbr;
+m=eq_nbr+AuxiliaryVariables_nbr;
+A00=zeros(m);A00(1:ny,1:ny)=A0;A00(ny+1:end,ny+1:end)=eye(AuxiliaryVariables_nbr);
+A11=zeros(m);A11(1:ny,1:ny)=A1;A11(1:ny,ny+1:end)=A6(:,aux);
+A22=zeros(m);A22(1:ny,1:ny)=A2;
+A33=zeros(m,instr_nbr);A33(1:ny,1:end)=A3;A33(ny+1:end,aux)=eye(AuxiliaryVariables_nbr);
+A44=zeros(m,instr_nbr);A44(1:ny,1:end)=A4;
+A55=zeros(m,exo_nbr);A55(1:ny,1:end)=A5;
+WW=zeros(m);WW(1:ny,1:ny)=W;
+endo_augm_id=setdiff(1:endo_nbr+AuxiliaryVariables_nbr,instr_id);
+
+end
+
+function v= SylvesterDoubling (d,g,h,tol,maxit)
+
+% DOUBLES  Solves a Sylvester equation using doubling
+%
+%  [v,info] = doubles (g,d,h,tol,maxit)  uses a doubling algorithm
+%   to solve the  Sylvester equation v  = d + g v h
+
+v = d;
+for i =1:maxit,
+    vadd = g*v*h;
+    v = v+vadd;
+    if norm (vadd,1) <= (tol*norm(v,1))
+        break;
+    end
+    g = g*g;
+    h = h*h;
+end
+
+end
+
+function v = SylvesterHessenbergSchur(d,g,h)
+%
+% DSYLHS  Solves a discrete time sylvester equation	 using the
+% Hessenberg-Schur algorithm
+%
+% v = DSYLHS(g,d,h) computes the matrix v that satisfies the
+% discrete time sylvester equation
+%
+%           v = d + g'vh
+
+if size(g,1) >= size(h,1)
+    [u,gbarp] = hess(g');
+    [t,hbar] = schur(h);
+    [vbar] = sylvest_private(gbarp,u'*d*t,hbar,1e-15);
+    v = u*vbar*t';
+else
+    [u,gbar] = schur(g);
+    [t,hbarp] = hess(h');
+    [vbar] = sylvest_private(hbarp,t'*d'*u,gbar,1e-15);
+    v = u*vbar'*t';
+end
+
+end
+
+
+function v = sylvest_private(g,d,h,tol)
+%
+% SYLVEST  Solves a Sylvester equation
+%
+%  solves the Sylvester equation
+%         v = d + g v h
+%  for v where both g and h must be  upper block triangular.
+%  The output info is zero on a successful return.
+%  The input tol indicates when an element of g or h should be considered
+%  zero.
+
+[m,n] = size(d);
+v = zeros(m,n);
+w = eye(m);
+i = 1;
+temp = [];
+
+%First handle the i = 1 case outside the loop
+
+if i< n,
+    if abs(h(i+1,i)) < tol,
+        v(:,i)= (w - g*h(i,i))\d(:,i);
+        i = i+1;
+    else
+        A = [w-g*h(i,i)     (-g*h(i+1,i));...
+            -g*h(i,i+1)    w-g*h(i+1,i+1)];
+        C = [d(:,i); d(:,i+1)];
+        X = A\C;
+        v(:,i) = X(1:m,:);
+        v(:,i+1) = X(m+1:2*m,  :);
+        i = i+2;
+    end
+end
+
+%Handle the rest of the matrix with the possible exception of i=n
+
+while i<n,
+    b= i-1;
+    temp = [temp g*v(:,size(temp,2)+1:b)]; %#ok<AGROW>
+    if abs(h(i+1,i)) < tol,
+        v(:,i) = (w - g*h(i,i))\(d(:,i) + temp*h(1:b,i));
+        i = i+1;
+    else
+        A = [w - g*h(i,i)    (-g*h(i+1,i));   ...
+            -g*h(i,i+1)    w - g*h(i+1,i+1)];
+        C = [d(:,i) + temp*h(1:b,i);         ...
+            d(:,i+1) + temp*h(1:b,i+1)];
+        X = A\C;
+        v(:,i) = X(1:m,:);
+        v(:,i+1) = X(m+1:2*m, :);
+        i = i+2;
+    end
+end
+
+%Handle the i = n case if i=n was not in a 2-2 block
+
+if i==n,
+    b = i-1;
+    temp = [temp g*v(:,size(temp,2)+1:b)];
+    v(:,i) = (w-g*h(i,i))\(d(:,i) + temp*h(1:b,i));
+end
+
+end
diff --git a/matlab/disp_dr.m b/matlab/disp_dr.m
index 9e5deeab0faeb7f6c4eb84361950f95809705330..91fb3c17d7e28c080a5066c9b277bbfdd5b957e2 100644
--- a/matlab/disp_dr.m
+++ b/matlab/disp_dr.m
@@ -1,3 +1,4 @@
+
 function disp_dr(dr,order,var_list)
 % Display the decision rules
 %
@@ -102,11 +103,11 @@ end
 %
 for k=1:nx
     flag = 0;
-    if options_.block
+    if isfield(dr,'state_var')
         str1 = subst_auxvar(dr.state_var(k),-1);
     else
         str1 = subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2);
-    end;
+    end
     str = sprintf('%-20s',str1);
     for i=1:nvar
         x = dr.ghx(ivar(i),k);
diff --git a/matlab/disp_identification.m b/matlab/disp_identification.m
index 057981de8862baaac86dea86e3f6d4e8afd5007d..16e25924bce107cff245b78b72de7e7cdc0dcfd8 100644
--- a/matlab/disp_identification.m
+++ b/matlab/disp_identification.m
@@ -1,4 +1,4 @@
-function disp_identification(pdraws, idemodel, idemoments, name)
+function disp_identification(pdraws, idemodel, idemoments, name, advanced)
 
 % Copyright (C) 2008-2011 Dynare Team
 %
@@ -19,6 +19,10 @@ function disp_identification(pdraws, idemodel, idemoments, name)
 
 global options_
 
+if nargin < 5 || isempty(advanced),
+    advanced=0;
+end
+
 [SampleSize, npar] = size(pdraws);
 % jok = 0;
 % jokP = 0;
@@ -261,3 +265,27 @@ end
 % end
 % disp(' ')
 
+% identificaton patterns
+if SampleSize==1 && advanced,
+    disp(' ')
+    disp('Press ENTER to print advanced diagnostics'), pause(5),
+    for  j=1:size(idemoments.cosnJ,2),
+        pax=NaN(npar,npar);
+        fprintf('\n')
+        disp(['Collinearity patterns with ', int2str(j) ,' parameter(s)'])
+        fprintf('%-15s [%-*s] %10s\n','Parameter',(15+1)*j,' Expl. params ','cosn')
+        for i=1:npar,
+            namx='';
+            for in=1:j,
+                dumpindx = idemoments.pars{i,j}(in);
+                if isnan(dumpindx),
+                    namx=[namx ' ' sprintf('%-15s','--')];
+                else
+                    namx=[namx ' ' sprintf('%-15s',name{dumpindx})];
+                    pax(i,dumpindx)=idemoments.cosnJ(i,j);
+                end
+            end
+            fprintf('%-15s [%s] %10.3f\n',name{i},namx,idemoments.cosnJ(i,j))
+        end
+    end
+end
diff --git a/matlab/dr_block.m b/matlab/dr_block.m
index 886731cae615f957ffa45c020ed01e199973e3db..44b95efcbd539fb09d46b952986580fb773045b3 100644
--- a/matlab/dr_block.m
+++ b/matlab/dr_block.m
@@ -33,7 +33,7 @@ function [dr,info,M_,options_,oo_] = dr_block(dr,task,M_,options_,oo_)
 %   none.
 %  
 
-% Copyright (C) 2010-2011 Dynare Team
+% Copyright (C) 2010-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -413,97 +413,110 @@ for i = 1:Size;
         index_0m = (n_static+1:n_static+n_pred) + indexi_0 - 1;
         index_0p = (n_static+n_pred+1:n) + indexi_0 - 1;
         index_m = 1:(n_pred+n_both);
-        indexi_p = max(lead_lag_incidence(2,:))+1;
-        index_p = indexi_p:size(jacob, 2);
+        index_p  = lead_lag_incidence(3,find(lead_lag_incidence(3,:)));
         nyf = n_fwrd + n_both;
         A = aa(:,index_m);  % Jacobain matrix for lagged endogeneous variables
         B = aa(:,index_c);  % Jacobian matrix for contemporaneous endogeneous variables
         C = aa(:,index_p);  % Jacobain matrix for led endogeneous variables
 
         row_indx = n_static+1:n;
+
+        if task ~= 1 && options_.dr_cycle_reduction == 1
+            A1 = [aa(row_indx,index_m ) zeros(n_dynamic,n_fwrd)];
+            B1 = [aa(row_indx,index_0m) aa(row_indx,index_0p) ];
+            C1 = [zeros(n_dynamic,n_pred) aa(row_indx,index_p)];
+            [ghx, info] = cycle_reduction(A1, B1, C1, options_.dr_cycle_reduction_tol);
+            %ghx
+            ghx = ghx(:,index_m);
+            hx = ghx(1:n_pred+n_both,:);
+            gx = ghx(1+n_pred:end,:);
+        end
         
-        D = [[aa(row_indx,index_0m) zeros(n_dynamic,n_both) aa(row_indx,index_p)] ; [zeros(n_both, n_pred) eye(n_both) zeros(n_both, n_both + n_fwrd)]];
-        E = [-aa(row_indx,[index_m index_0p])  ; [zeros(n_both, n_both + n_pred) eye(n_both, n_both + n_fwrd) ] ];
+        if (task ~= 1 && ((options_.dr_cycle_reduction == 1 && info ==1) || options_.dr_cycle_reduction == 0)) || task == 1
+            D = [[aa(row_indx,index_0m) zeros(n_dynamic,n_both) aa(row_indx,index_p)] ; [zeros(n_both, n_pred) eye(n_both) zeros(n_both, n_both + n_fwrd)]];
+            E = [-aa(row_indx,[index_m index_0p])  ; [zeros(n_both, n_both + n_pred) eye(n_both, n_both + n_fwrd) ] ];
 
-        [err, ss, tt, w, sdim, data(i).eigval, info1] = mjdgges(E,D,options_.qz_criterium);
+            [err, ss, tt, w, sdim, data(i).eigval, info1] = mjdgges(E,D,options_.qz_criterium);
 
-        if (verbose)
-            disp('eigval');
-            disp(data(i).eigval);
-        end;
-        if info1
-            info(1) = 2;
-            info(2) = info1;
-            return
-        end
-        nba = nd-sdim;
-        if task == 1
-            data(i).rank = rank(w(nd-nyf+1:end,nd-nyf+1:end));
-            dr.rank = dr.rank + data(i).rank;
-            if ~exist('OCTAVE_VERSION','builtin')
-                data(i).eigval = eig(E,D);
+            if (verbose)
+                disp('eigval');
+                disp(data(i).eigval);
+            end;
+            if info1
+                info(1) = 2;
+                info(2) = info1;
+                return
             end
-            dr.eigval = [dr.eigval ; data(i).eigval];
-        end
-        if (verbose)
-            disp(['sum eigval > 1 = ' int2str(sum(abs(data(i).eigval) > 1.)) ' nyf=' int2str(nyf) ' and dr.rank=' int2str(data(i).rank)]);
-            disp(['data(' int2str(i) ').eigval']);
-            disp(data(i).eigval);
-        end;
-        
-        %First order approximation
-        if task ~= 1
-            if nba ~= nyf
-                sorted_roots = sort(abs(dr.eigval));
-                if isfield(options_,'indeterminacy_continuity')
-                    if options_.indeterminacy_msv == 1
-                        [ss,tt,w,q] = qz(e',d');
-                        [ss,tt,w,junk] = reorder(ss,tt,w,q);
-                        ss = ss';
-                        tt = tt';
-                        w  = w';
-                        %nba = nyf;
+            nba = nd-sdim;
+            if task == 1
+                data(i).rank = rank(w(nd-nyf+1:end,nd-nyf+1:end));
+                dr.rank = dr.rank + data(i).rank;
+                if ~exist('OCTAVE_VERSION','builtin')
+                    data(i).eigval = eig(E,D);
+                end
+                dr.eigval = [dr.eigval ; data(i).eigval];
+            end
+            if (verbose)
+                disp(['sum eigval > 1 = ' int2str(sum(abs(data(i).eigval) > 1.)) ' nyf=' int2str(nyf) ' and dr.rank=' int2str(data(i).rank)]);
+                disp(['data(' int2str(i) ').eigval']);
+                disp(data(i).eigval);
+            end;
+
+            %First order approximation
+            if task ~= 1
+                if nba ~= nyf
+                    sorted_roots = sort(abs(dr.eigval));
+                    if isfield(options_,'indeterminacy_continuity')
+                        if options_.indeterminacy_msv == 1
+                            [ss,tt,w,q] = qz(e',d');
+                            [ss,tt,w,junk] = reorder(ss,tt,w,q);
+                            ss = ss';
+                            tt = tt';
+                            w  = w';
+                            %nba = nyf;
+                        end
+                    else
+                        if nba > nyf
+                            temp = sorted_roots(nd-nba+1:nd-nyf)-1-options_.qz_criterium;
+                            info(1) = 3;
+                        elseif nba < nyf;
+                            temp = sorted_roots(nd-nyf+1:nd-nba)-1-options_.qz_criterium;
+                            info(1) = 4;
+                        end
+                        info(2) = temp'*temp;
+                        return
                     end
+                end
+                indx_stable_root = 1: (nd - nyf);     %=> index of stable roots
+                indx_explosive_root = n_pred + n_both + 1:nd;  %=> index of explosive roots
+                % derivatives with respect to dynamic state variables
+                % forward variables
+                Z = w';
+                Z11t = Z(indx_stable_root,    indx_stable_root)';
+                Z21  = Z(indx_explosive_root, indx_stable_root);
+                Z22  = Z(indx_explosive_root, indx_explosive_root);
+                if ~isfloat(Z21) && (condest(Z21) > 1e9)
+                    % condest() fails on a scalar under Octave
+                    info(1) = 5;
+                    info(2) = condest(Z21);
+                    return;
                 else
-                    if nba > nyf
-                        temp = sorted_roots(nd-nba+1:nd-nyf)-1-options_.qz_criterium;
-                        info(1) = 3;
-                    elseif nba < nyf;
-                        temp = sorted_roots(nd-nyf+1:nd-nba)-1-options_.qz_criterium;
-                        info(1) = 4;
-                    end
-                    info(2) = temp'*temp;
-                    return
+                    %gx = -inv(Z22) * Z21;
+                    gx = - Z22 \ Z21;
                 end
-            end
-            indx_stable_root = 1: (nd - nyf);     %=> index of stable roots
-            indx_explosive_root = n_pred + n_both + 1:nd;  %=> index of explosive roots
-            % derivatives with respect to dynamic state variables
-            % forward variables
-            Z = w';
-            Z11t = Z(indx_stable_root,    indx_stable_root)';
-            Z21  = Z(indx_explosive_root, indx_stable_root);
-            Z22  = Z(indx_explosive_root, indx_explosive_root);
-            if ~isfloat(Z21) && (condest(Z21) > 1e9)
-                % condest() fails on a scalar under Octave
-                info(1) = 5;
-                info(2) = condest(Z21);
-                return;
-            else
-                %gx = -inv(Z22) * Z21;
-                gx = - Z22 \ Z21;
-            end
 
-            % predetermined variables
-            hx =  Z11t * inv(tt(indx_stable_root, indx_stable_root)) * ss(indx_stable_root, indx_stable_root) * inv(Z11t);
-            
-            k1 = 1:(n_pred+n_both);
-            k2 = 1:(n_fwrd+n_both);
+                % predetermined variables
+                hx =  Z11t * inv(tt(indx_stable_root, indx_stable_root)) * ss(indx_stable_root, indx_stable_root) * inv(Z11t);
 
-            ghx = [hx(k1,:); gx(k2(n_both+1:end),:)];
-            
+                k1 = 1:(n_pred+n_both);
+                k2 = 1:(n_fwrd+n_both);
+
+                ghx = [hx(k1,:); gx(k2(n_both+1:end),:)];
+            end;
+        end;
+        
+        if  task~= 1 
             %lead variables actually present in the model
-            
             j4 = n_static+n_pred+1:n_static+n_pred+n_both+n_fwrd;   % Index on the forward and both variables
             j3 = nonzeros(lead_lag_incidence(2,j4)) - n_static - 2 * n_pred - n_both;  % Index on the non-zeros forward and both variables
             j4 = find(lead_lag_incidence(2,j4)); 
diff --git a/matlab/dsge_likelihood.m b/matlab/dsge_likelihood.m
index 08c985a758e2271a50e98288052f082c6a06cd16..0b770a0d4738b1d982c0c7a0194f1d966429e5ca 100644
--- a/matlab/dsge_likelihood.m
+++ b/matlab/dsge_likelihood.m
@@ -80,8 +80,12 @@ function [fval,DLIK,Hess,exit_flag,ys,trend_coeff,info,Model,DynareOptions,Bayes
 %! The covariance matrix of the measurement errors is not positive definite.
 %! @item info==45
 %! Likelihood is not a number (NaN).
-%! @item info==45
+%! @item info==46
 %! Likelihood is a complex valued number.
+%! @item info==47
+%! Posterior kernel is not a number (logged prior density is NaN)
+%! @item info==48
+%! Posterior kernel is a complex valued number (logged prior density is complex).
 %! @end table
 %! @item Model
 %! Matlab's structure describing the model (initialized by dynare, see @ref{M_}).
@@ -107,7 +111,7 @@ function [fval,DLIK,Hess,exit_flag,ys,trend_coeff,info,Model,DynareOptions,Bayes
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2004-2011 Dynare Team
+% Copyright (C) 2004-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -133,7 +137,7 @@ function [fval,DLIK,Hess,exit_flag,ys,trend_coeff,info,Model,DynareOptions,Bayes
 % set also 'exit_flag' equal to 0 instead of 1.  It is only when
 % dsge_likelihood() is called by an optimizer called by
 % dynare_estimation_1() that 'exit_flag' is ignored and penalized 'fval' is
-% actually used.  
+% actually used.
 % In that case, 'penalty' is properly initialized, at the very end of the
 % present function, by a call to dsge_likelihood() made in
 % initial_estimation_checks(). If a condition triggers exit_flag ==
@@ -168,10 +172,19 @@ end
 
 % Set flag related to analytical derivatives.
 analytic_derivation = DynareOptions.analytic_derivation;
+
+if analytic_derivation && DynareOptions.loglinear
+    error('The analytic_derivation and loglinear options are not compatible')
+end
+
 if nargout==1,
     analytic_derivation=0;
 end
-    
+
+if analytic_derivation,
+    kron_flag=DynareOptions.analytic_derivation_mode;
+end
+
 %------------------------------------------------------------------------------
 % 1. Get the structural parameters & define penalties
 %------------------------------------------------------------------------------
@@ -201,31 +214,13 @@ if ~isequal(DynareOptions.mode_compute,1) && any(xparam1>BayesInfo.ub)
 end
 
 % Get the diagonal elements of the covariance matrices for the structural innovations (Q) and the measurement error (H).
+Model = set_all_parameters(xparam1,EstimatedParameters,Model);
+
 Q = Model.Sigma_e;
 H = Model.H;
-for i=1:EstimatedParameters.nvx
-    k =EstimatedParameters.var_exo(i,1);
-    Q(k,k) = xparam1(i)*xparam1(i);
-end
-offset = EstimatedParameters.nvx;
-if EstimatedParameters.nvn
-    for i=1:EstimatedParameters.nvn
-        k = EstimatedParameters.var_endo(i,1);
-        H(k,k) = xparam1(i+offset)*xparam1(i+offset);
-    end
-    offset = offset+EstimatedParameters.nvn;
-else
-    H = zeros(DynareDataset.info.nvobs);
-end
 
-% Get the off-diagonal elements of the covariance matrix for the structural innovations. Test if Q is positive definite.
+% Test if Q is positive definite.
 if EstimatedParameters.ncx
-    for i=1:EstimatedParameters.ncx
-        k1 =EstimatedParameters.corrx(i,1);
-        k2 =EstimatedParameters.corrx(i,2);
-        Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2));
-        Q(k2,k1) = Q(k1,k2);
-    end
     % Try to compute the cholesky decomposition of Q (possible iff Q is positive definite)
     [CholQ,testQ] = chol(Q);
     if testQ
@@ -239,17 +234,10 @@ if EstimatedParameters.ncx
             return
         end
     end
-    offset = offset+EstimatedParameters.ncx;
 end
 
-% Get the off-diagonal elements of the covariance matrix for the measurement errors. Test if H is positive definite.
+% Test if H is positive definite.
 if EstimatedParameters.ncn
-    for i=1:EstimatedParameters.ncn
-        k1 = DynareOptions.lgyidx2varobs(EstimatedParameters.corrn(i,1));
-        k2 = DynareOptions.lgyidx2varobs(EstimatedParameters.corrn(i,2));
-        H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2));
-        H(k2,k1) = H(k1,k2);
-    end
     % Try to compute the cholesky decomposition of H (possible iff H is positive definite)
     [CholH,testH] = chol(H);
     if testH
@@ -263,17 +251,8 @@ if EstimatedParameters.ncn
             return
         end
     end
-    offset = offset+EstimatedParameters.ncn;
 end
 
-% Update estimated structural parameters in Mode.params.
-if EstimatedParameters.np > 0
-    Model.params(EstimatedParameters.param_vals(:,1)) = xparam1(offset+1:end);
-end
-
-% Update Model.Sigma_e and Model.H.
-Model.Sigma_e = Q;
-Model.H = H;
 
 %------------------------------------------------------------------------------
 % 2. call model setup & reduction program
@@ -353,7 +332,7 @@ if (kalman_algo == 2) || (kalman_algo == 4)
     else
         if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
             H = diag(H);
-            mmm = mm; 
+            mmm = mm;
         else
             Z = [Z, eye(pp)];
             T = blkdiag(T,zeros(pp));
@@ -402,7 +381,7 @@ switch DynareOptions.lik_init
         % Use standard kalman filter except if the univariate filter is explicitely choosen.
     if kalman_algo == 0
         kalman_algo = 3;
-    elseif ~((kalman_algo == 3) || (kalman_algo == 4)) 
+    elseif ~((kalman_algo == 3) || (kalman_algo == 4))
             error(['diffuse filter: options_.kalman_algo can only be equal ' ...
                    'to 0 (default), 3 or 4'])
     end
@@ -438,7 +417,7 @@ switch DynareOptions.lik_init
         else
             if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
                 H1 = diag(H);
-                mmm = mm; 
+                mmm = mm;
             else
                 Z = [Z, eye(pp)];
                 T = blkdiag(T,zeros(pp));
@@ -467,9 +446,9 @@ switch DynareOptions.lik_init
         kalman_algo = 1;
     end
     if isequal(H,0)
-        [err,Pstar] = kalman_steady_state(transpose(T),R*Q*transpose(R),transpose(build_selection_matrix(Z,np,length(Z))));
+        [err,Pstar] = kalman_steady_state(transpose(T),R*Q*transpose(R),transpose(build_selection_matrix(Z,mm,length(Z))));
     else
-        [err,Pstar] = kalman_steady_state(transpose(T),R*Q*transpose(R),transpose(build_selection_matrix(Z,np,length(Z))),H);
+        [err,Pstar] = kalman_steady_state(transpose(T),R*Q*transpose(R),transpose(build_selection_matrix(Z,mm,length(Z))),H);
     end
     if err
         disp(['dsge_likelihood:: I am not able to solve the Riccati equation, so I switch to lik_init=1!']);
@@ -477,17 +456,28 @@ switch DynareOptions.lik_init
         Pstar = lyapunov_symm(T,R*Q*R',DynareOptions.qz_criterium,DynareOptions.lyapunov_complex_threshold);
     end
     Pinf  = [];
+    a = zeros(mm,1);
+    Zflag = 0;
   otherwise
     error('dsge_likelihood:: Unknown initialization approach for the Kalman filter!')
 end
 
-if analytic_derivation
+if analytic_derivation,
+    offset = EstimatedParameters.nvx;
+    offset = offset+EstimatedParameters.nvn;
+    offset = offset+EstimatedParameters.ncx;
+    offset = offset+EstimatedParameters.ncn;
+
     no_DLIK = 0;
     full_Hess = analytic_derivation==2;
     asy_Hess = analytic_derivation==-2;
+    outer_product_gradient = analytic_derivation==-1;
     if asy_Hess,
         analytic_derivation=1;
     end
+    if outer_product_gradient,
+        analytic_derivation=1;
+    end
     DLIK = [];
     AHess = [];
     if nargin<8 || isempty(derivatives_info)
@@ -504,9 +494,9 @@ if analytic_derivation
         end
 
         if full_Hess,
-            [dum, DT, DOm, DYss, dum2, D2T, D2Om, D2Yss] = getH(A, B, Model,DynareResults,0,indparam,indexo);
+            [dum, DT, DOm, DYss, dum2, D2T, D2Om, D2Yss] = getH(A, B, Model,DynareResults,DynareOptions,kron_flag,indparam,indexo);
         else
-            [dum, DT, DOm, DYss] = getH(A, B, Model,DynareResults,0,indparam,indexo);
+            [dum, DT, DOm, DYss] = getH(A, B, Model,DynareResults,DynareOptions,kron_flag,indparam,indexo);
         end
     else
         DT = derivatives_info.DT;
@@ -530,7 +520,7 @@ if analytic_derivation
     DT = DT(iv,iv,:);
     DOm = DOm(iv,iv,:);
     DYss = DYss(iv,:);
-    DH=zeros([size(H),length(xparam1)]);
+    DH=zeros([length(H),length(H),length(xparam1)]);
     DQ=zeros([size(Q),length(xparam1)]);
     DP=zeros([size(T),length(xparam1)]);
     if full_Hess,
@@ -592,7 +582,7 @@ if analytic_derivation
         end
     end
     if analytic_derivation==1,
-        analytic_deriv_info={analytic_derivation,DT,DYss,DOm,DH,DP};
+        analytic_deriv_info={analytic_derivation,DT,DYss,DOm,DH,DP,asy_Hess};
     else
         analytic_deriv_info={analytic_derivation,DT,DYss,DOm,DH,DP,D2T,D2Yss,D2Om,D2H,D2P};
     end
@@ -606,7 +596,7 @@ end
 
 if ((kalman_algo==1) || (kalman_algo==3))% Multivariate Kalman Filter
     if no_missing_data_flag
-        if DynareOptions.block == 1
+        if DynareOptions.block
             [err, LIK] = block_kalman_filter(T,R,Q,H,Pstar,Y,start,Z,kalman_tol,riccati_tol, Model.nz_state_var, Model.n_diag, Model.nobs_non_statevar);
             mexErrCheck('block_kalman_filter', err);
         else
@@ -615,19 +605,26 @@ if ((kalman_algo==1) || (kalman_algo==3))% Multivariate Kalman Filter
                                 kalman_tol, riccati_tol, ...
                                 DynareOptions.presample, ...
                                 T,Q,R,H,Z,mm,pp,rr,Zflag,diffuse_periods, ...
-                                analytic_deriv_info{:}); 
-                            
+                                analytic_deriv_info{:});
+
         end
     else
-        [LIK,lik] = missing_observations_kalman_filter(DynareDataset.missing.aindex,DynareDataset.missing.number_of_observations,DynareDataset.missing.no_more_missing_observations,Y,diffuse_periods+1,size(Y,2), ...
+        if 0 %DynareOptions.block
+            [err, LIK,lik] = block_kalman_filter(DynareDataset.missing.aindex,DynareDataset.missing.number_of_observations,DynareDataset.missing.no_more_missing_observations,...
+                                                                 T,R,Q,H,Pstar,Y,start,Z,kalman_tol,riccati_tol, Model.nz_state_var, Model.n_diag, Model.nobs_non_statevar);
+        else
+            [LIK,lik] = missing_observations_kalman_filter(DynareDataset.missing.aindex,DynareDataset.missing.number_of_observations,DynareDataset.missing.no_more_missing_observations,Y,diffuse_periods+1,size(Y,2), ...
                                                a, Pstar, ...
                                                kalman_tol, DynareOptions.riccati_tol, ...
                                                DynareOptions.presample, ...
                                                T,Q,R,H,Z,mm,pp,rr,Zflag,diffuse_periods);
+        end;
     end
     if analytic_derivation,
         LIK1=LIK;
         LIK=LIK1{1};
+        lik1=lik;
+        lik=lik1{1};
     end
     if isinf(LIK)
         if kalman_algo == 1
@@ -647,7 +644,7 @@ end
 
 if (kalman_algo==2) || (kalman_algo==4)
     % Univariate Kalman Filter
-    % resetting measurement error covariance matrix when necessary                                                           % 
+    % resetting measurement error covariance matrix when necessary                                                           %
     if ~correlated_errors_have_been_checked
         if isequal(H,0)
             H = zeros(pp,1);
@@ -659,6 +656,7 @@ if (kalman_algo==2) || (kalman_algo==4)
             if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
                 H = diag(H);
                 mmm = mm;
+                clear tmp
                 if analytic_derivation,
                     for j=1:pp,
                         tmp(j,:)=DH(j,j,:);
@@ -690,6 +688,8 @@ if (kalman_algo==2) || (kalman_algo==4)
     if analytic_derivation,
         LIK1=LIK;
         LIK=LIK1{1};
+        lik1=lik;
+        lik=lik1{1};
     end
     if DynareOptions.lik_init==3
         LIK = LIK+dLIK;
@@ -704,28 +704,34 @@ if analytic_derivation
         DLIK = LIK1{2};
         %                 [DLIK] = score(T,R,Q,H,Pstar,Y,DT,DYss,DOm,DH,DP,start,Z,kalman_tol,riccati_tol);
     end
-    if full_Hess,
+    if full_Hess ,
         Hess = -LIK1{3};
         %                     [Hess, DLL] = get_Hessian(T,R,Q,H,Pstar,Y,DT,DYss,DOm,DH,DP,D2T,D2Yss,D2Om,D2H,D2P,start,Z,kalman_tol,riccati_tol);
         %                     Hess0 = getHessian(Y,T,DT,D2T, R*Q*transpose(R),DOm,D2Om,Z,DYss,D2Yss);
     end
     if asy_Hess,
-        [Hess] = AHessian(T,R,Q,H,Pstar,Y,DT,DYss,DOm,DH,DP,start,Z,kalman_tol,riccati_tol);
+%         if ~((kalman_algo==2) || (kalman_algo==4)),
+%             [Hess] = AHessian(T,R,Q,H,Pstar,Y,DT,DYss,DOm,DH,DP,start,Z,kalman_tol,riccati_tol);
+%         else
+        Hess = LIK1{3};
+%         end
     end
 end
 
-
 if isnan(LIK)
     info = 45;
     exit_flag = 0;
     return
 end
+
 if imag(LIK)~=0
-    likelihood = penalty;
-else
-    likelihood = LIK;
+    info = 46;
+    exit_flag = 0;
+    return
 end
 
+likelihood = LIK;
+
 % ------------------------------------------------------------------------------
 % 5. Adds prior if necessary
 % ------------------------------------------------------------------------------
@@ -739,11 +745,29 @@ if analytic_derivation
     if no_DLIK==0
         DLIK = DLIK - dlnprior';
     end
+    if outer_product_gradient,
+        dlik = lik1{2};
+        dlik=[- dlnprior; dlik(start:end,:)];
+        Hess = dlik'*dlik;
+    end
 else
     lnprior = priordens(xparam1,BayesInfo.pshape,BayesInfo.p6,BayesInfo.p7,BayesInfo.p3,BayesInfo.p4);
 end
+
 fval    = (likelihood-lnprior);
 
+if isnan(fval)
+    info = 47;
+    exit_flag = 0;
+    return
+end
+
+if imag(fval)~=0
+    info = 48;
+    exit_flag = 0;
+    return
+end
+
 % Update DynareOptions.kalman_algo.
 DynareOptions.kalman_algo = kalman_algo;
 
diff --git a/matlab/dsge_simulated_theoretical_conditional_variance_decomposition.m b/matlab/dsge_simulated_theoretical_conditional_variance_decomposition.m
index 60c9aaf9f5db015f652d089e6196fee60ca45ab5..cf6a5442ff888f4de267a5f3967c035bdb6bc7a0 100644
--- a/matlab/dsge_simulated_theoretical_conditional_variance_decomposition.m
+++ b/matlab/dsge_simulated_theoretical_conditional_variance_decomposition.m
@@ -16,7 +16,7 @@ function [nvar,vartan,NumberOfConditionalDecompFiles] = ...
 %   vartan                           [char]     array of characters (with nvar rows).
 %   NumberOfConditionalDecompFiles   [integer]  scalar, number of prior or posterior data files (for covariance).
 
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -54,7 +54,7 @@ if ~posterior
     end
     options_.varlist = options_.prior_analysis_endo_var_list;
 end
-[ivar,vartan ] = set_stationary_variables_list(options_, M_);
+[ivar,vartan ] = get_variables_list(options_, M_);
 if ~posterior
     if exist('temp','var')
         options_.varlist = temp;
diff --git a/matlab/dsge_simulated_theoretical_correlation.m b/matlab/dsge_simulated_theoretical_correlation.m
index d8a81a149c300da55ddfdbe04bba05219d2207a4..59ffa4e4ea8f0de648ffb19c055d5c145f4e6ce4 100644
--- a/matlab/dsge_simulated_theoretical_correlation.m
+++ b/matlab/dsge_simulated_theoretical_correlation.m
@@ -15,7 +15,7 @@ function [nvar,vartan,CorrFileNumber] = dsge_simulated_theoretical_correlation(S
 %   vartan         [char]
 %   CorrFileNumber [integer]
 
-% Copyright (C) 2007-2009 Dynare Team
+% Copyright (C) 2007-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -55,7 +55,7 @@ if ~posterior
     end
     options_.varlist = options_.prior_analysis_endo_var_list;
 end
-[ivar,vartan, options_] = set_stationary_variables_list(options_, M_);
+[ivar,vartan, options_] = get_variables_list(options_, M_);
 if ~posterior
     if exist('temp','var')
         options_.varlist = temp;
diff --git a/matlab/dsge_simulated_theoretical_covariance.m b/matlab/dsge_simulated_theoretical_covariance.m
index 1231b8b586adbbea8fd77067345dd9a6e8eaecdd..5d39e77fb72343d4f284b132223bcd187b6ea9f3 100644
--- a/matlab/dsge_simulated_theoretical_covariance.m
+++ b/matlab/dsge_simulated_theoretical_covariance.m
@@ -15,7 +15,7 @@ function [nvar,vartan,CovarFileNumber] = dsge_simulated_theoretical_covariance(S
 %   vartan            [char]     array of characters (with nvar rows).
 %   CovarFileNumber   [integer]  scalar, number of prior or posterior data files (for covariance).
 
-% Copyright (C) 2007-2009 Dynare Team
+% Copyright (C) 2007-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -55,7 +55,7 @@ if ~posterior
     end
     options_.varlist = options_.prior_analysis_endo_var_list;
 end
-[ivar,vartan] = set_stationary_variables_list(options_,M_);
+[ivar,vartan] = get_variables_list(options_,M_);
 if ~posterior
     if exist('temp','var')
         options_.varlist = temp;
diff --git a/matlab/dsge_simulated_theoretical_variance_decomposition.m b/matlab/dsge_simulated_theoretical_variance_decomposition.m
index a4008b31abc7552958e486ea375fbe11a6280510..ee6fdd28ca5536b524d26c5069b7a8ed47ebb425 100644
--- a/matlab/dsge_simulated_theoretical_variance_decomposition.m
+++ b/matlab/dsge_simulated_theoretical_variance_decomposition.m
@@ -16,7 +16,7 @@ function [nvar,vartan,NumberOfDecompFiles] = ...
 %   vartan            [char]     array of characters (with nvar rows).
 %   CovarFileNumber   [integer]  scalar, number of prior or posterior data files (for covariance).
 
-% Copyright (C) 2007-2009 Dynare Team
+% Copyright (C) 2007-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -56,7 +56,7 @@ if ~posterior
     end
     options_.varlist = options_.prior_analysis_endo_var_list;
 end
-[ivar,vartan,options_] = set_stationary_variables_list(options_,M_);
+[ivar,vartan,options_] = get_variables_list(options_,M_);
 if ~posterior
     if exist('temp','var')
         options_.varlist = temp;
diff --git a/matlab/dsgevar_posterior_density.m b/matlab/dsgevar_posterior_density.m
index bf90834e78e64aa592c7d3835eb0efb2b58ad361..9ff74e1451dbd6d99f343340b9c324d8e55aa7f2 100644
--- a/matlab/dsgevar_posterior_density.m
+++ b/matlab/dsgevar_posterior_density.m
@@ -16,7 +16,7 @@ function bvar = dsgevar_posterior_density(deep,DynareDataset,DynareOptions,Model
 %   none
 %
 
-% Copyright (C) 1996-2008 Dynare Team
+% Copyright (C) 1996-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/dyn_first_order_solver.m b/matlab/dyn_first_order_solver.m
index dee4e4c0be342c68c6c3f894f7f1910e3ffd0a85..8ad529c9e473a7b4f4e2190793af3d9576d6eb15 100644
--- a/matlab/dyn_first_order_solver.m
+++ b/matlab/dyn_first_order_solver.m
@@ -1,7 +1,7 @@
-function [dr,info] = dyn_first_order_solver(jacobia,M_,dr,options,task)
-    
+function [dr,info] = dyn_first_order_solver(jacobia,DynareModel,dr,DynareOptions,task)
+
 %@info:
-%! @deftypefn {Function File} {[@var{dr},@var{info}] =} dyn_first_order_solver (@var{jacobia},@var{M_},@var{dr},@var{options},@var{task})
+%! @deftypefn {Function File} {[@var{dr},@var{info}] =} dyn_first_order_solver (@var{jacobia},@var{DynareModel},@var{dr},@var{DynareOptions},@var{task})
 %! @anchor{dyn_first_order_solver}
 %! @sp 1
 %! Computes the first order reduced form of the DSGE model
@@ -11,7 +11,7 @@ function [dr,info] = dyn_first_order_solver(jacobia,M_,dr,options,task)
 %! @table @ @var
 %! @item jacobia
 %! Matrix containing the Jacobian of the model
-%! @item M_
+%! @item DynareModel
 %! Matlab's structure describing the model (initialized by @code{dynare}).
 %! @item dr
 %! Matlab's structure describing the reduced form solution of the model.
@@ -41,13 +41,13 @@ function [dr,info] = dyn_first_order_solver(jacobia,M_,dr,options,task)
 %! @item info==5
 %! Blanchard & Kahn conditions are not satisfied: indeterminacy due to rank failure.
 %! @item info==7
-%! One of the generalized eigenvalues is close to 0/0     
+%! One of the generalized eigenvalues is close to 0/0
 %! @end table
 %! @end table
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2001-2011 Dynare Team
+% Copyright (C) 2001-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -63,75 +63,159 @@ function [dr,info] = dyn_first_order_solver(jacobia,M_,dr,options,task)
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+persistent reorder_jacobian_columns innovations_idx index_s index_m index_c
+persistent index_p row_indx index_0m index_0p k1 k2 state_var
+persistent ndynamic nstatic nfwrd npred nboth nd nyf n_current index_d 
+persistent index_e index_d1 index_d2 index_e1 index_e2 row_indx_de_1 
+persistent row_indx_de_2 cols_b
+
+
+if ~nargin
+    if nargout
+        error('dyn_first_order_solver:: Initialization mode returns zero argument!')
+    end
+    reorder_jacobian_columns = [];
+    return
+end
+
+exo_nbr = DynareModel.exo_nbr;
+
+if isempty(reorder_jacobian_columns)
     
-    info = 0;
-    
-    dr.ghx = [];
-    dr.ghu = [];
-    
-    klen = M_.maximum_endo_lag+M_.maximum_endo_lead+1;
-    kstate = dr.kstate;
-    kad = dr.kad;
-    kae = dr.kae;
-    nstatic = dr.nstatic;
-    nfwrd = dr.nfwrd;
-    npred = dr.npred;
-    nboth = dr.nboth;
+    maximum_lag = DynareModel.maximum_endo_lag;
+    kstate   = dr.kstate;
+    nfwrd    = dr.nfwrd;
+    nboth    = dr.nboth;
+    npred    = dr.npred-nboth;
+    nstatic  = dr.nstatic;
+    ndynamic = npred+nfwrd+nboth;
+    nyf      = nfwrd + nboth;
+    n        = DynareModel.endo_nbr;
+
+    k1 = 1:(npred+nboth);
+    k2 = 1:(nfwrd+nboth);
+
     order_var = dr.order_var;
     nd = size(kstate,1);
-    lead_lag_incidence = M_.lead_lag_incidence;
+    lead_lag_incidence = DynareModel.lead_lag_incidence;
     nz = nnz(lead_lag_incidence);
 
-    sdyn = M_.endo_nbr - nstatic;
-
-    [junk,cols_b,cols_j] = find(lead_lag_incidence(M_.maximum_endo_lag+1,...
-                                                   order_var));
-    
-    if nstatic > 0
-        [Q,R] = qr(jacobia(:,cols_j(1:nstatic)));
-        aa = Q'*jacobia;
+    lead_id = find(lead_lag_incidence(maximum_lag+2,:));
+    lead_idx = lead_lag_incidence(maximum_lag+2,lead_id);
+    if maximum_lag
+        lag_id = find(lead_lag_incidence(1,:));
+        lag_idx = lead_lag_incidence(1,lag_id);
+        static_id = find((lead_lag_incidence(1,:) == 0) & ...
+                         (lead_lag_incidence(3,:) == 0));
     else
-        aa = jacobia;
+        lag_id = [];
+        lag_idx = [];
+        static_id = find(lead_lag_incidence(2,:)==0);
     end
-    k1 = find([1:klen] ~= M_.maximum_endo_lag+1);
-    a = aa(:,nonzeros(lead_lag_incidence(k1,:)'));
-    b(:,cols_b) = aa(:,cols_j);
-    b10 = b(1:nstatic,1:nstatic);
-    b11 = b(1:nstatic,nstatic+1:end);
-    b2 = b(nstatic+1:end,nstatic+1:end);
-    if any(isinf(a(:)))
-        info = 1;
-        return
+
+    both_id = intersect(lead_id,lag_id);
+    if maximum_lag
+        no_both_lag_id = setdiff(lag_id,both_id);
+    else
+        no_both_lag_id = [];
     end
+    innovations_idx = nz+(1:exo_nbr);
+    state_var  = [lag_id, both_id];
+
+    index_c  = nonzeros(lead_lag_incidence(maximum_lag+1,:));             % Index of all endogenous variables present at time=t
+    n_current = length(index_c);
+
+    index_s  = npred+nboth+(1:nstatic);     % Index of all static
+                                            % endogenous variables
+                                            % present at time=t
+    indexi_0 = npred+nboth;
+
+    npred0 = nnz(lead_lag_incidence(maximum_lag+1,no_both_lag_id));
+    index_0m = indexi_0+nstatic+(1:npred0);
+    nfwrd0 = nnz(lead_lag_incidence(2,lead_id));
+    index_0p = indexi_0+nstatic+npred0+(1:nfwrd0);
+    index_m  = 1:(npred+nboth);
+    index_p  = npred+nboth+n_current+(1:nfwrd+nboth);
+    row_indx_de_1 = 1:ndynamic;
+    row_indx_de_2 = ndynamic+(1:nboth);
+    row_indx = nstatic+row_indx_de_1;
+    index_d = [index_0m index_p];
+    llx = lead_lag_incidence(:,order_var);
+    index_d1 = [find(llx(maximum_lag+1,nstatic+(1:npred))), npred+nboth+(1:nyf) ];
+    index_d2 = npred+(1:nboth);
+
+    index_e = [index_m index_0p];
+    index_e1 = [1:npred+nboth, npred+nboth+find(llx(maximum_lag+1,nstatic+npred+(1: ...
+                                                      nyf)))];
+    index_e2 = npred+nboth+nfwrd+(1:nboth);
+    
+    [junk,cols_b] = find(lead_lag_incidence(maximum_lag+1, order_var));
+
+    reorder_jacobian_columns = [nonzeros(lead_lag_incidence(:,order_var)'); ...
+                        nz+(1:exo_nbr)'];
+end
+
+dr.ghx = [];
+dr.ghu = [];
+
+dr.state_var = state_var;
+
+jacobia = jacobia(:,reorder_jacobian_columns);
+
+if nstatic > 0
+    [Q, junk] = qr(jacobia(:,index_s));
+    aa = Q'*jacobia;
+else
+    aa = jacobia;
+end
 
-    % buildind D and E
-    d = zeros(nd,nd) ;
-    e = d ;
-
-    k = find(kstate(:,2) >= M_.maximum_endo_lag+2 & kstate(:,3));
-    d(1:sdyn,k) = a(nstatic+1:end,kstate(k,3)) ;
-    k1 = find(kstate(:,2) == M_.maximum_endo_lag+2);
-    e(1:sdyn,k1) =  -b2(:,kstate(k1,1)-nstatic);
-    k = find(kstate(:,2) <= M_.maximum_endo_lag+1 & kstate(:,4));
-    e(1:sdyn,k) = -a(nstatic+1:end,kstate(k,4)) ;
-    k2 = find(kstate(:,2) == M_.maximum_endo_lag+1);
-    k2 = k2(~ismember(kstate(k2,1),kstate(k1,1)));
-    d(1:sdyn,k2) = b2(:,kstate(k2,1)-nstatic);
-
-    if ~isempty(kad)
-        for j = 1:size(kad,1)
-            d(sdyn+j,kad(j)) = 1 ;
-            e(sdyn+j,kae(j)) = 1 ;
+A = aa(:,index_m);  % Jacobain matrix for lagged endogeneous variables
+B(:,cols_b) = aa(:,index_c);  % Jacobian matrix for contemporaneous endogeneous variables
+C = aa(:,index_p);  % Jacobain matrix for led endogeneous variables
+
+info = 0;
+if task ~= 1 && (DynareOptions.dr_cycle_reduction || DynareOptions.dr_logarithmic_reduction)
+    if n_current < DynareModel.endo_nbr
+        if DynareOptions.dr_cycle_reduction
+            error(['The cycle reduction algorithme can''t be used when the ' ...
+               'coefficient matrix for current variables isn''t invertible'])
+        elseif DynareOptions.dr_logarithmic_reduction
+            error(['The logarithmic reduction algorithme can''t be used when the ' ...
+                   'coefficient matrix for current variables isn''t invertible'])
         end
+    end  
+    if DynareOptions.gpu
+        gpuArray(A1);
+        gpuArray(B1);
+        gpuArray(C1);
     end
-
-    % 1) if mjdgges.dll (or .mexw32 or ....) doesn't exit, 
-    % matlab/qz is added to the path. There exists now qz/mjdgges.m that 
-    % contains the calls to the old Sims code 
-    % 2) In  global_initialization.m, if mjdgges.m is visible exist(...)==2, 
-    % this means that the DLL isn't avaiable and use_qzdiv is set to 1
+    A1 = [aa(row_indx,index_m ) zeros(ndynamic,nfwrd)];
+    B1 = [aa(row_indx,index_0m) aa(row_indx,index_0p) ];
+    C1 = [zeros(ndynamic,npred) aa(row_indx,index_p)];
+    if DynareOptions.dr_cycle_reduction == 1
+        [ghx, info] = cycle_reduction(A1, B1, C1, DynareOptions.dr_cycle_reduction_tol);
+    else
+        [ghx, info] = logarithmic_reduction(C1, B1, A1, DynareOptions.dr_logarithmic_reduction_tol, DynareOptions.dr_logarithmic_reduction_maxiter);
+    end
+    if info
+        % cycle_reduction or logarithmic redution failed and set info
+        return
+    end
+    ghx = ghx(:,index_m);
+    hx = ghx(1:npred+nboth,:);
+    gx = ghx(1+npred:end,:);
+else
+    D = zeros(ndynamic+nboth);
+    E = zeros(ndynamic+nboth);
+    D(row_indx_de_1,index_d1) = aa(row_indx,index_d);
+    D(row_indx_de_2,index_d2) = eye(nboth);
+    E(row_indx_de_1,index_e1) = -aa(row_indx,index_e);
+    E(row_indx_de_2,index_e2) = eye(nboth);
     
-    [err,ss,tt,w,sdim,dr.eigval,info1] = mjdgges(e,d,options.qz_criterium);
+    E = [-aa(row_indx,[index_m index_0p])  ; [zeros(nboth,nboth+npred) eye(nboth,nboth+nfwrd) ] ];
+
+    [err, ss, tt, w, sdim, dr.eigval, info1] = mjdgges(E,D,DynareOptions.qz_criterium);
     mexErrCheck('mjdgges', err);
 
     if info1
@@ -141,21 +225,19 @@ function [dr,info] = dyn_first_order_solver(jacobia,M_,dr,options,task)
         else
             info(1) = 2;
             info(2) = info1;
-            info(3) = size(e,2);
+            info(3) = size(E,2);
         end
         return
     end
 
     nba = nd-sdim;
 
-    nyf = sum(kstate(:,2) > M_.maximum_endo_lag+1);
-
     if task == 1
-        dr.rank = rank(w(1:nyf,nd-nyf+1:end));
+        dr.rank = rank(w(npred+nboth+1:end,npred+nboth+1:end));
         % Under Octave, eig(A,B) doesn't exist, and
         % lambda = qz(A,B) won't return infinite eigenvalues
         if ~exist('OCTAVE_VERSION')
-            dr.eigval = eig(e,d);
+            dr.eigval = eig(E,D);
         end
         return
     end
@@ -163,74 +245,89 @@ function [dr,info] = dyn_first_order_solver(jacobia,M_,dr,options,task)
     if nba ~= nyf
         temp = sort(abs(dr.eigval));
         if nba > nyf
-            temp = temp(nd-nba+1:nd-nyf)-1-options.qz_criterium;
+            temp = temp(nd-nba+1:nd-nyf)-1-DynareOptions.qz_criterium;
             info(1) = 3;
         elseif nba < nyf;
-            temp = temp(nd-nyf+1:nd-nba)-1-options.qz_criterium;
+            temp = temp(nd-nyf+1:nd-nba)-1-DynareOptions.qz_criterium;
             info(1) = 4;
         end
         info(2) = temp'*temp;
         return
     end
 
-    np = nd - nyf;
-    n2 = np + 1;
-    n3 = nyf;
-    n4 = n3 + 1;
-    % derivatives with respect to dynamic state variables
-    % forward variables
-    w1 =w(1:n3,n2:nd);
-    if ~isscalar(w1) && (condest(w1) > 1e9);
-        % condest() fails on a scalar under Octave
+    %First order approximation
+    indx_stable_root = 1: (nd - nyf);     %=> index of stable roots
+    indx_explosive_root = npred + nboth + 1:nd;  %=> index of explosive roots
+                                                 % derivatives with respect to dynamic state variables
+                                                 % forward variables
+    Z = w';
+    Z11 = Z(indx_stable_root,    indx_stable_root);
+    Z21  = Z(indx_explosive_root, indx_stable_root);
+    Z22  = Z(indx_explosive_root, indx_explosive_root);
+    [minus_gx,rc] = linsolve(Z22,Z21);
+    if rc < 1e-9
+        % Z22 is near singular
         info(1) = 5;
-        info(2) = condest(w1);
+        info(2) = -log(rc);
         return;
-    else
-        gx = -w1'\w(n4:nd,n2:nd)';
-    end  
-
-    % predetermined variables
-    hx = w(1:n3,1:np)'*gx+w(n4:nd,1:np)';
-    hx = (tt(1:np,1:np)*hx)\(ss(1:np,1:np)*hx);
-
-    k1 = find(kstate(n4:nd,2) == M_.maximum_endo_lag+1);
-    k2 = find(kstate(1:n3,2) == M_.maximum_endo_lag+2);
-    dr.gx = gx;
-    dr.ghx = [hx(k1,:); gx(k2(nboth+1:end),:)];
-
-    %lead variables actually present in the model
-    j3 = nonzeros(kstate(:,3));
-    j4  = find(kstate(:,3));
-    % derivatives with respect to exogenous variables
-    if M_.exo_nbr
-        fu = aa(:,nz+(1:M_.exo_nbr));
-        a1 = b;
-        aa1 = [];
-        if nstatic > 0
-            aa1 = a1(:,1:nstatic);
-        end
-        dr.ghu = -[aa1 a(:,j3)*gx(j4,1:npred)+a1(:,nstatic+1:nstatic+ ...
-                                                 npred) a1(:,nstatic+npred+1:end)]\fu;
-    else
-        dr.ghu = [];
     end
+    gx  = -minus_gx;
+    % predetermined variables
+    opts.UT = true;
+    opts.TRANSA = true;
+    hx1 = linsolve(tt(indx_stable_root, indx_stable_root),Z11,opts)';
+    hx2 = linsolve(Z11,ss(indx_stable_root, indx_stable_root)')';
+    hx =  hx1*hx2;
+    ghx = [hx(k1,:); gx(k2(nboth+1:end),:)];
+end
+
+dr.gx = gx;
+
+if nstatic > 0
+    B_static = B(:,1:nstatic);  % submatrix containing the derivatives w.r. to static variables
+else
+    B_static = [];
+end;
+%static variables, backward variable, mixed variables and forward variables
+B_pred = B(:,nstatic+1:nstatic+npred+nboth);
+B_fyd = B(:,nstatic+npred+nboth+1:end);
 
-    % static variables
+% static variables
+if nstatic > 0
+    temp = - C(1:nstatic,:)*gx*hx;
+    b(:,cols_b) = aa(:,index_c);
+    b10 = b(1:nstatic, 1:nstatic);
+    b11 = b(1:nstatic, nstatic+1:end);
+    temp(:,index_m) = temp(:,index_m)-A(1:nstatic,:);
+    temp = b10\(temp-b11*ghx);
+    ghx = [temp; ghx];
+    temp = [];
+end
+
+A_ = real([B_static C*gx+B_pred B_fyd]); % The state_variable of the block are located at [B_pred B_both]
+
+if exo_nbr
     if nstatic > 0
-        temp = -a(1:nstatic,j3)*gx(j4,:)*hx;
-        j5 = find(kstate(n4:nd,4));
-        temp(:,j5) = temp(:,j5)-a(1:nstatic,nonzeros(kstate(:,4)));
-        temp = b10\(temp-b11*dr.ghx);
-        dr.ghx = [temp; dr.ghx];
-        temp = [];
-    end
+        fu = Q' * jacobia(:,innovations_idx);
+    else
+        fu = jacobia(:,innovations_idx);
+    end;
 
-    if options.use_qzdiv
-        %% Necessary when using Sims' routines for QZ
-        gx = real(gx);
-        hx = real(hx);
-        dr.ghx = real(dr.ghx);
-        dr.ghu = real(dr.ghu);
-    end
+    ghu = - A_ \ fu;
+else
+    ghu = [];
+end;
+
+
+
+dr.ghx = ghx;
+dr.ghu = ghu;
+
+if DynareOptions.aim_solver ~= 1 && DynareOptions.use_qzdiv
+    % Necessary when using Sims' routines for QZ
+    dr.ghx = real(ghx);
+    dr.ghu = real(ghu);
+    hx = real(hx);
+end
 
-    dr.Gy = hx;
\ No newline at end of file
+dr.Gy = hx;
\ No newline at end of file
diff --git a/matlab/dyn_forecast.m b/matlab/dyn_forecast.m
index 4343e2c8fc6e6d1511220a261064f80891ec2501..812ab1ca4461a79788308304406286c55d65416e 100644
--- a/matlab/dyn_forecast.m
+++ b/matlab/dyn_forecast.m
@@ -16,7 +16,7 @@ function info = dyn_forecast(var_list,task)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2010 Dynare Team
+% Copyright (C) 2003-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/dyn_ramsey_static.m b/matlab/dyn_ramsey_static.m
index 32616923df802b3fc1746e9760cc3f38708cb218..349d7511face64687e865a20dabb200a9366a307 100644
--- a/matlab/dyn_ramsey_static.m
+++ b/matlab/dyn_ramsey_static.m
@@ -14,7 +14,7 @@ function [steady_state,params,check] = dyn_ramsey_static(x,M,options_,oo)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2010 Dynare Team
+% Copyright (C) 2003-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -131,9 +131,14 @@ Uyy = reshape(Uyy,endo_nbr,endo_nbr);
 
 % set multipliers and auxiliary variables that
 % depends on multipliers to 0 to compute residuals
-[res,fJ] = feval([fname '_static'],xx,[oo.exo_simul oo.exo_det_simul], ...
+if (options_.bytecode)
+   [chck, res, junk] = bytecode('static',xx,[oo.exo_simul oo.exo_det_simul], ...
+               M.params, 'evaluate'); 
+   fJ = junk.g1;
+else
+   [res,fJ] = feval([fname '_static'],xx,[oo.exo_simul oo.exo_det_simul], ...
                M.params);
-
+end
 % index of multipliers and corresponding equations
 % the auxiliary variables before the Lagrange multipliers are treated
 % as ordinary endogenous variables
diff --git a/matlab/dyn_risky_steadystate_solver.m b/matlab/dyn_risky_steadystate_solver.m
index 2700b928e7a18efa6862255e8b31ba56c5daec02..6067aa19ebdbab2ac72cac45cdce962a70caf050 100644
--- a/matlab/dyn_risky_steadystate_solver.m
+++ b/matlab/dyn_risky_steadystate_solver.m
@@ -62,7 +62,7 @@ function [dr,info] = dyn_risky_steadystate_solver(ys0,M, ...
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2001-2011 Dynare Team
+% Copyright (C) 2001-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -208,7 +208,7 @@ function [resid,dr] = risky_residuals(ys,M,dr,options,oo)
         d2a = d2(eq,ih1);
         
         M.endo_nbr = M.endo_nbr-n_tags;
-        dr = set_state_space(dr,M);
+        dr = set_state_space(dr,M,options);
     
         [junk,dr.i_fwrd_g] = find(lead_lag_incidence(3,dr.order_var));
         i_fwrd_f = nonzeros(lead_incidence(dr.order_var));
@@ -434,7 +434,7 @@ function [dr] = first_step_ds(x,M,dr,options,oo)
         d2a = d2(eq,ih1);
         
         M.endo_nbr = M.endo_nbr-n_tags;
-        dr = set_state_space(dr,M);
+        dr = set_state_space(dr,M,options);
     
         dr.i_fwrd_g = find(lead_lag_incidence(3,dr.order_var)');
     else
diff --git a/matlab/dyn_saveas.m b/matlab/dyn_saveas.m
index f9ade453e02be31a228071ec50194e6fb60f55b4..2a53cb703ceddbc22efd9b1e566d5ece6afcac54 100644
--- a/matlab/dyn_saveas.m
+++ b/matlab/dyn_saveas.m
@@ -30,19 +30,18 @@ function dyn_saveas(h,fname,DynareOptions)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-if find(strcmp('eps',DynareOptions.graph_format))
+if (strcmp('eps',DynareOptions.graph_format))
     eval(['print -depsc2 ' fname '.eps']);
 end
-if ~exist('OCTAVE_VERSION')
-    if find(strcmp('pdf',DynareOptions.graph_format))
-        eval(['print -dpdf ' fname]);
-    end
-    if find(strcmp('fig',DynareOptions.graph_format))
-        if DynareOptions.nodisplay
-            set(h, 'Visible','on');
-        end
-        saveas(h,[fname '.fig']);
+if (strcmp('pdf',DynareOptions.graph_format))
+    eval(['print -dpdf ' fname]);
+end
+if ~exist('OCTAVE_VERSION') ...
+   && (strcmp('fig',DynareOptions.graph_format))
+    if DynareOptions.nodisplay
+        set(h, 'Visible','on');
     end
+    saveas(h,[fname '.fig']);
 end
 if DynareOptions.nodisplay
     close(h);
diff --git a/matlab/dynare_config.m b/matlab/dynare_config.m
index ebddb4035bfadc0aea388f3ebdf43357af11718b..0644f8e7f7afefb437902c9eb232c1b8066bbe3e 100644
--- a/matlab/dynare_config.m
+++ b/matlab/dynare_config.m
@@ -93,6 +93,11 @@ if (exist('OCTAVE_VERSION') && ~user_has_octave_forge_package('statistics')) ...
     addpath([dynareroot '/missing/nanmean'])
 end
 
+% linsolve is missing in Octave
+if (exist('OCTAVE_VERSION'))
+    addpath([dynareroot '/missing/linsolve'])
+end
+
 % Add path to MEX files
 if exist('OCTAVE_VERSION')
     addpath([dynareroot '../mex/octave/']);
@@ -183,7 +188,7 @@ mex_status(4,2) = {'kronecker'};
 mex_status(4,3) = {'Sparse kronecker products'};
 mex_status(5,1) = {'local_state_space_iteration_2'};
 mex_status(5,2) = {'particle/local_state_space_iteration'};
-mex_status(5,3) = {'Local state space iteraton (second order)'};
+mex_status(5,3) = {'Local state space iteration (second order)'};
 number_of_mex_files = size(mex_status,1);
 %% Remove some directories from matlab's path. This is necessary if the user has
 %% added dynare_v4/matlab with the subfolders. Matlab has to ignore these
@@ -255,6 +260,16 @@ else
 end
 if verbose
     disp([ message 'Quasi Monte-Carlo sequence (Sobol).' ])
+end
+
+% Test if MS-SBVAR DLL is present
+if exist('ms_sbvar_command_line', 'file') == 3
+    message = '[mex] ';
+else
+    message = '[no]  ';
+end
+if verbose
+    disp([ message 'Markov Switching SBVAR.' ])
     disp(' ')
 end
 
diff --git a/matlab/dynare_estimation.m b/matlab/dynare_estimation.m
index 2ebac78a30694c29a1bcf1c88695761dea3527bf..12f9ebb911a2969bcdf1a534808d050850101300 100644
--- a/matlab/dynare_estimation.m
+++ b/matlab/dynare_estimation.m
@@ -11,7 +11,7 @@ function dynare_estimation(var_list,dname)
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2003-2011 Dynare Team
+% Copyright (C) 2003-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/dynare_estimation_1.m b/matlab/dynare_estimation_1.m
index e4e899392d7e27a2374b20557f11593885a2a7bb..8ac7a072c128828a699103c2007428c7fc2d157f 100644
--- a/matlab/dynare_estimation_1.m
+++ b/matlab/dynare_estimation_1.m
@@ -40,9 +40,7 @@ if options_.order > 1
     elseif options_.particle.status && options_.order>2
         error(['Non linear filter are not implemented with order ' int2str(options_.order) ' approximation of the model!'])
     elseif ~options_.particle.status && options_.order==2
-        disp('If you want to estimate the model with a second order approximation using a non linear filter, set options_.particle.status=1;')
-        disp('I set order=1!')
-        options_.order=1;
+        error('For estimating the model with a second order approximation using a non linear filter, one should have options_.particle.status=1;')
     else
         error(['Cannot estimate a model with an order ' int2str(options_.order) ' approximation!'])
     end
@@ -60,6 +58,25 @@ end
 
 [dataset_,xparam1, M_, options_, oo_, estim_params_,bayestopt_] = dynare_estimation_init(var_list_, dname, [], M_, options_, oo_, estim_params_, bayestopt_);
 
+% Set sigma_e_is_diagonal flag (needed if the shocks block is not declared in the mod file).
+M_.sigma_e_is_diagonal = 1;
+if estim_params_.ncx || ~isequal(nnz(M_.Sigma_e),length(M_.Sigma_e))
+    M_.sigma_e_is_diagonal = 0;
+end
+
+% Set the correlation matrix if necessary.
+if ~isequal(estim_params_.ncx,nnz(tril(M_.Sigma_e,-1)))
+    M_.Correlation_matrix = diag(1./sqrt(diag(M_.Sigma_e)))*M_.Sigma_e*diag(1./sqrt(diag(M_.Sigma_e)));
+    % Remove NaNs appearing because of variances calibrated to zero.
+    if any(isnan(M_.Correlation_matrix))
+        zero_variance_idx = find(~diag(M_.Sigma_e));
+        for i=1:length(zero_variance_idx)
+            M_.Correlation_matrix(zero_variance_idx(i),:) = 0;
+            M_.Correlation_matrix(:,zero_variance_idx(i)) = 0;
+        end
+    end
+end
+
 data = dataset_.data;
 rawdata = dataset_.rawdata;
 data_index = dataset_.missing.aindex;
@@ -169,7 +186,7 @@ if ~isequal(options_.mode_compute,0) && ~options_.mh_posterior_mode_estimation
             eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']);
         end
         if options_.analytic_derivation,
-            optim_options = optimset(optim_options,'GradObj','on');
+            optim_options = optimset(optim_options,'GradObj','on','TolX',1e-7);
         end
             [xparam1,fval,exitflag,output,lamdba,grad,hessian_fmincon] = ...
                 fmincon(objective_function,xparam1,[],[],[],[],lb,ub,[],optim_options,dataset_,options_,M_,estim_params_,bayestopt_,oo_);
@@ -204,22 +221,29 @@ if ~isequal(options_.mode_compute,0) && ~options_.mh_posterior_mode_estimation
         else
             flag = 1;
         end
-        if ~exist('igg','var'),  % by M. Ratto
-            hh=[];
-            gg=[];
-            igg=[];
-        end   % by M. Ratto
         if isfield(options_,'ftol')
             crit = options_.ftol;
         else
             crit = 1.e-5;
         end
+        if options_.analytic_derivation,
+            analytic_grad=1;
+            ana_deriv = options_.analytic_derivation;
+            options_.analytic_derivation = -1;
+            crit = 1.e-7;
+            flag = 0;
+        else
+            analytic_grad=0;
+        end
         if isfield(options_,'nit')
             nit = options_.nit;
         else
             nit=1000;
         end
-        [xparam1,hh,gg,fval,invhess] = newrat(objective_function,xparam1,hh,gg,igg,crit,nit,flag,dataset_,options_,M_,estim_params_,bayestopt_,oo_);
+        [xparam1,hh,gg,fval,invhess] = newrat(objective_function,xparam1,analytic_grad,crit,nit,flag,dataset_,options_,M_,estim_params_,bayestopt_,oo_);
+        if options_.analytic_derivation,
+            options_.analytic_derivation = ana_deriv;
+        end
         parameter_names = bayestopt_.name;
         save([M_.fname '_mode.mat'],'xparam1','hh','gg','fval','invhess','parameter_names');
       case 6
@@ -402,7 +426,10 @@ if ~options_.mh_posterior_mode_estimation && options_.cova_compute
 end
 
 if options_.mode_check == 1 && ~options_.mh_posterior_mode_estimation
+    ana_deriv = options_.analytic_derivation;
+    options_.analytic_derivation = 0;
     mode_check(objective_function,xparam1,hh,dataset_,options_,M_,estim_params_,bayestopt_,oo_);
+    options_.analytic_derivation = ana_deriv;
 end
 
 oo_.posterior.optimization.mode = xparam1;
@@ -881,10 +908,14 @@ if (any(bayestopt_.pshape  >0 ) && options_.mh_replic) || ...
             prior_posterior_statistics('posterior',dataset_);
         end
         xparam = get_posterior_parameters('mean');
-        set_all_parameters(xparam);
+        M_ = set_all_parameters(xparam,estim_params_,M_);
     end
 end
 
+if options_.particle.status
+    return
+end
+
 if (~((any(bayestopt_.pshape > 0) && options_.mh_replic) || (any(bayestopt_.pshape ...
                                                       > 0) && options_.load_mh_file)) ...
     || ~options_.smoother ) && options_.partial_information == 0  % to be fixed
diff --git a/matlab/dynare_estimation_init.m b/matlab/dynare_estimation_init.m
index 557e814d2d495966670867949c3e8919566ec27f..9810e0ec257c01c9dba94ccbb6eab7a597f9b264 100644
--- a/matlab/dynare_estimation_init.m
+++ b/matlab/dynare_estimation_init.m
@@ -18,7 +18,7 @@ function [dataset_,xparam1, M_, options_, oo_, estim_params_,bayestopt_, fake] =
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2003-2011 Dynare Team
+% Copyright (C) 2003-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -138,9 +138,12 @@ if ~isempty(estim_params_)
     % Test if initial values of the estimated parameters are all between
     % the prior lower and upper bounds.
     if any(xparam1 < bounds(:,1)) || any(xparam1 > bounds(:,2))
-        find(xparam1 < bounds(:,1))
-        find(xparam1 > bounds(:,2))
-        error('Initial parameter values are outside parameter bounds')
+        outside_bound_vars=bayestopt_.name([find(xparam1 < bounds(:,1)); find(xparam1 > bounds(:,2))],:);
+        disp_string=[outside_bound_vars{1,:}];
+        for ii=2:size(outside_bound_vars,1)
+            disp_string=[disp_string,', ',outside_bound_vars{ii,:}];
+        end
+        error(['Initial value(s) of ', disp_string ,' are outside parameter bounds. Potentially, you should set prior_trunc=0.'])
     end
     lb = bounds(:,1);
     ub = bounds(:,2);
@@ -191,7 +194,7 @@ end
 bayestopt_.penalty = 1e8;
 
 % Get informations about the variables of the model.
-dr = set_state_space(oo_.dr,M_);
+dr = set_state_space(oo_.dr,M_,options_);
 oo_.dr = dr;
 nstatic = dr.nstatic;          % Number of static variables.
 npred = dr.npred;              % Number of predetermined variables.
@@ -285,10 +288,29 @@ else
 end;
 
 if options_.analytic_derivation,
-    if ~(exist('sylvester3','file')==2),        
+    if ~(exist('sylvester3','file')==2),
         dynareroot = strrep(which('dynare'),'dynare.m','');
         addpath([dynareroot 'gensylv'])
     end
+    if estim_params_.np,
+        % check if steady state changes param values
+        M=M_;
+        M.params(estim_params_.param_vals(:,1)) = M.params(estim_params_.param_vals(:,1))*1.01;
+        if options_.diffuse_filter
+            steadystate_check_flag = 0;
+        else
+            steadystate_check_flag = 1;
+        end
+        [tmp1, params] = evaluate_steady_state(oo_.steady_state,M,options_,oo_,steadystate_check_flag);
+        change_flag=any(find(params-M.params));
+        if change_flag,
+            disp('The steadystate file changed the values for the following parameters: '),
+            disp(M.param_names(find(params-M.params),:))
+            disp('The derivatives of jacobian and steady-state will be computed numerically'),
+            disp('(re-set options_.analytic_derivation_mode= -2)'),
+            options_.analytic_derivation_mode= -2;
+        end
+    end
 end
 
 % Test if the data file is declared.
@@ -335,10 +357,10 @@ nvx = estim_params_.nvx;
 ncx = estim_params_.ncx;
 nvn = estim_params_.nvn;
 ncn = estim_params_.ncn;
-if isfield(estim_params_,'param_vals')
+if estim_params_.np,
   M.params(estim_params_.param_vals(:,1)) = xparam1(nvx+ncx+nvn+ncn+1:end);
 end;
-oo_.steady_state = evaluate_steady_state(oo_.steady_state,M,options_,oo_,steadystate_check_flag);
+[oo_.steady_state, params] = evaluate_steady_state(oo_.steady_state,M,options_,oo_,steadystate_check_flag);
 if all(abs(oo_.steady_state(bayestopt_.mfys))<1e-9)
     options_.noconstant = 1;
 else
diff --git a/matlab/dynare_gradient.m b/matlab/dynare_gradient.m
index 566286ed4d058881d067a9d1061fbbdbe990de9a..91b4140c15bbd6b969518712854447f0b73188e8 100644
--- a/matlab/dynare_gradient.m
+++ b/matlab/dynare_gradient.m
@@ -12,7 +12,7 @@ function [F,G] = dynare_gradient(fcn,x,epsilon,varargin)
 %
 % OUTPUTS
 % 
-% Copyright (C) 2010-2011 Dynare Team
+% Copyright (C) 2010-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/dynare_identification.m b/matlab/dynare_identification.m
index d75299382e93ec04aa85c7e2ef185c551035c5d8..f12a0a5e988d0ef79e02a39e21bfced30751f4be 100644
--- a/matlab/dynare_identification.m
+++ b/matlab/dynare_identification.m
@@ -19,7 +19,7 @@ function [pdraws, TAU, GAM, LRE, gp, H, JJ] = dynare_identification(options_iden
 
 % main 
 %
-% Copyright (C) 2010-2011 Dynare Team
+% Copyright (C) 2010-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -60,6 +60,7 @@ options_ident = set_default_option(options_ident,'replic',100);
 options_ident = set_default_option(options_ident,'advanced',0);
 options_ident = set_default_option(options_ident,'normalize_jacobians',1);
 options_ident = set_default_option(options_ident,'lik_init',1);
+options_ident = set_default_option(options_ident,'analytic_derivation',1);
 if options_ident.gsa_sample_file,
     GSAFolder = checkpath('gsa',M_.dname);
     if options_ident.gsa_sample_file==1,
@@ -117,16 +118,20 @@ options_ = set_default_option(options_,'datafile',[]);
 options_.mode_compute = 0;
 options_.plot_priors = 0;
 [dataset_,xparam1, M_, options_, oo_, estim_params_,bayestopt_]=dynare_estimation_init(M_.endo_names,fname_,1, M_, options_, oo_, estim_params_, bayestopt_);
+options_ident.analytic_derivation_mode = options_.analytic_derivation_mode;
 if isempty(dataset_),
     dataset_.info.ntobs = periods;
     dataset_.info.nvobs = rows(options_.varobs);
     dataset_.info.varobs = options_.varobs;
     dataset_.rawdata = [];
     dataset_.missing.state = 0;
-    dataset_.missing.aindex = [];
+    for jdata=1:periods,
+        temp1{jdata}=[1:dataset_.info.nvobs]';
+    end
+    dataset_.missing.aindex = temp1;
     dataset_.missing.vindex = [];
     dataset_.missing.number_of_observations = [];
-    dataset_.missing.no_more_missing_observations = [];
+    dataset_.missing.no_more_missing_observations = 1;
     dataset_.descriptive.mean = [];
     dataset_.data = [];
 
@@ -263,8 +268,10 @@ if iload <=0,
 %     normJ = max(abs(siJ)')';
 %     normLRE = max(abs(siLRE)')';
     save([IdentifDirectoryName '/' M_.fname '_identif.mat'], 'idehess_point', 'idemoments_point','idemodel_point', 'idelre_point','store_options_ident')
-    disp_identification(params, idemodel_point, idemoments_point, name);
-    plot_identification(params,idemoments_point,idehess_point,idemodel_point,idelre_point,advanced,parameters,name,IdentifDirectoryName);
+    disp_identification(params, idemodel_point, idemoments_point, name, advanced);
+    if ~options_.nograph,
+        plot_identification(params,idemoments_point,idehess_point,idemodel_point,idelre_point,advanced,parameters,name,IdentifDirectoryName);
+    end
 
     if SampleSize > 1,
         disp(' ')
@@ -289,7 +296,7 @@ if iload <=0,
         end
         [dum1, ideJ, ideH, ideGP, dum2 , info] = ...
             identification_analysis(params,indx,indexo,options_MC,dataset_, prior_exist, name_tex,0);
-        if iteration==0,
+        if iteration==0 && info(1)==0,
             MAX_tau   = min(SampleSize,ceil(MaxNumberOfBytes/(size(ideH.siH,1)*nparam)/8));
             stoH = zeros([size(ideH.siH,1),nparam,MAX_tau]);
             stoJJ = zeros([size(ideJ.siJ,1),nparam,MAX_tau]);
@@ -436,14 +443,18 @@ end
 
 if iload,
     disp(['Testing ',parameters])
-    disp_identification(idehess_point.params, idemodel_point, idemoments_point, name);
-    plot_identification(idehess_point.params,idemoments_point,idehess_point,idemodel_point,idelre_point,advanced,parameters,name,IdentifDirectoryName);
+    disp_identification(idehess_point.params, idemodel_point, idemoments_point, name,advanced);
+    if ~options_.nograph,
+        plot_identification(idehess_point.params,idemoments_point,idehess_point,idemodel_point,idelre_point,advanced,parameters,name,IdentifDirectoryName);
+    end
 end
 if SampleSize > 1,
     fprintf('\n')
     disp('Testing MC sample')
     disp_identification(pdraws, idemodel, idemoments, name);
-    plot_identification(pdraws,idemoments,idehess_point,idemodel,idelre,advanced,'MC sample - ',name, IdentifDirectoryName);
+    if ~options_.nograph,
+        plot_identification(pdraws,idemoments,idehess_point,idemodel,idelre,advanced,'MC sample - ',name, IdentifDirectoryName);
+    end
     if advanced,
         jcrit=find(idemoments.ino);
         if length(jcrit)<SampleSize,
@@ -458,9 +469,11 @@ if SampleSize > 1,
                         identification_analysis(pdraws(jmax,:),indx,indexo,options_ident,dataset_, prior_exist, name_tex,1);
                     save([IdentifDirectoryName '/' M_.fname '_identif.mat'], 'idehess_max', 'idemoments_max','idemodel_max', 'idelre_max', 'jmax', '-append');
                 end
-                disp_identification(pdraws(jmax,:), idemodel_max, idemoments_max, name);
+                disp_identification(pdraws(jmax,:), idemodel_max, idemoments_max, name,1);
                 close all,
-                plot_identification(pdraws(jmax,:),idemoments_max,idehess_max,idemodel_max,idelre_max,1,tittxt,name,IdentifDirectoryName);
+                if ~options_.nograph,
+                    plot_identification(pdraws(jmax,:),idemoments_max,idehess_max,idemodel_max,idelre_max,1,tittxt,name,IdentifDirectoryName);
+                end
                 [dum,jmin]=min(idemoments.cond);
                 fprintf('\n')
                 tittxt = 'Draw with SMALLEST condition number';
@@ -471,9 +484,11 @@ if SampleSize > 1,
                         identification_analysis(pdraws(jmin,:),indx,indexo,options_ident,dataset_, prior_exist, name_tex,1);
                     save([IdentifDirectoryName '/' M_.fname '_identif.mat'], 'idehess_min', 'idemoments_min','idemodel_min', 'idelre_min', 'jmin', '-append');
                 end
-                disp_identification(pdraws(jmin,:), idemodel_min, idemoments_min, name);
+                disp_identification(pdraws(jmin,:), idemodel_min, idemoments_min, name,1);
                 close all,
-                plot_identification(pdraws(jmin,:),idemoments_min,idehess_min,idemodel_min,idelre_min,1,tittxt,name,IdentifDirectoryName);
+                if ~options_.nograph,
+                    plot_identification(pdraws(jmin,:),idemoments_min,idehess_min,idemodel_min,idelre_min,1,tittxt,name,IdentifDirectoryName);
+                end
             else
                 for j=1:length(jcrit),
                     tittxt = ['Rank deficient draw n. ',int2str(j)];
@@ -483,9 +498,11 @@ if SampleSize > 1,
                         [idehess_(j), idemoments_(j), idemodel_(j), idelre_(j), derivatives_info_(j)] = ...
                             identification_analysis(pdraws(jcrit(j),:),indx,indexo,options_ident,dataset_, prior_exist, name_tex,1);
                     end
-                    disp_identification(pdraws(jcrit(j),:), idemodel_(j), idemoments_(j), name);
+                    disp_identification(pdraws(jcrit(j),:), idemodel_(j), idemoments_(j), name,1);
                     close all,
-                    plot_identification(pdraws(jcrit(j),:),idemoments_(j),idehess_(j),idemodel_(j),idelre_(j),1,tittxt,name,IdentifDirectoryName);
+                    if ~options_.nograph,
+                        plot_identification(pdraws(jcrit(j),:),idemoments_(j),idehess_(j),idemodel_(j),idelre_(j),1,tittxt,name,IdentifDirectoryName);
+                    end
                 end
                 if ~iload,
                     save([IdentifDirectoryName '/' M_.fname '_identif.mat'], 'idehess_', 'idemoments_','idemodel_', 'idelre_', 'jcrit', '-append');
diff --git a/matlab/dynare_sensitivity.m b/matlab/dynare_sensitivity.m
index a832a87afc9c77e1b1f90992154fd4622d140bf2..d688725fee93dac1b5d592b07977d1d58abdb26d 100644
--- a/matlab/dynare_sensitivity.m
+++ b/matlab/dynare_sensitivity.m
@@ -57,6 +57,9 @@ if ~isempty(options_gsa.datafile) || isempty(bayestopt_),
     if isfield(options_gsa,'loglinear'),
         options_.loglinear=options_gsa.loglinear;
     end
+    if isfield(options_gsa,'lik_init'),
+        options_.lik_init=options_gsa.lik_init;
+    end
     options_.mode_compute = 0;
     options_.filtered_vars = 1;
     options_.plot_priors = 0;
@@ -79,6 +82,11 @@ if options_gsa.identification,
     options_gsa = set_default_option(options_gsa,'ar',1);
     options_gsa = set_default_option(options_gsa,'useautocorr',0);
     options_.ar = options_gsa.ar;
+    if options_gsa.morris==0,
+        disp('The option morris = 0 is no longer supported (Type I errors)')
+        disp('This option is reset at morris = 2 (local identification analysis).')
+        options_gsa.morris=2;
+    end
     if options_gsa.morris==2,
         if isfield(options_,'options_ident'),
             options_.options_ident.load_ident_files = options_gsa.load_ident_files;
@@ -116,13 +124,35 @@ options_gsa = set_default_option(options_gsa,'ksstat',0.1);
 options_gsa = set_default_option(options_gsa,'pvalue_ks',0.001);
 options_gsa = set_default_option(options_gsa,'pvalue_corr',0.001);
 %options_gsa = set_default_option(options_gsa,'load_mh',0);
+% REDFORM mapping
+options_gsa = set_default_option(options_gsa,'logtrans_redform',0);
+options_gsa = set_default_option(options_gsa,'threshold_redform',[]);
+options_gsa = set_default_option(options_gsa,'ksstat_redform',0.001);
+options_gsa = set_default_option(options_gsa,'alpha2_redform',0);
+options_gsa = set_default_option(options_gsa,'namendo',[]);
+options_gsa = set_default_option(options_gsa,'namlagendo',[]);
+options_gsa = set_default_option(options_gsa,'namexo',[]);
+% RMSE mapping
+options_gsa = set_default_option(options_gsa,'rmse',0);
+options_gsa = set_default_option(options_gsa,'lik_only',0);
+options_gsa = set_default_option(options_gsa,'var_rmse',options_.varobs);
+options_gsa = set_default_option(options_gsa,'pfilt_rmse',0.1);
+options_gsa = set_default_option(options_gsa,'istart_rmse',options_.presample+1);
+options_gsa = set_default_option(options_gsa,'alpha_rmse',0.001);
+options_gsa = set_default_option(options_gsa,'alpha2_rmse',0);
 
-if options_gsa.redform,
+if options_gsa.redform && options_gsa.neighborhood_width==0 && isempty(options_gsa.threshold_redform),
     options_gsa.pprior=1;
     options_gsa.ppost=0;
 end
 
-if options_gsa.morris==1 || options_gsa.morris==3,
+if options_gsa.morris>2,
+    disp('The option morris = 3 is no longer supported')
+    disp('the option is reset at morris = 1 .')
+    options_gsa.morris=1;
+end
+   
+if options_gsa.morris==1,
     if ~options_gsa.identification,
         options_gsa.redform=1;
     end
@@ -134,17 +164,19 @@ if options_gsa.morris==1 || options_gsa.morris==3,
     options_gsa.load_rmse=0;
     options_gsa.alpha2_stab=1;
     options_gsa.ksstat=1;
-    if options_gsa.morris==3,
-        options_gsa = set_default_option(options_gsa,'Nsam',256);
-        OutputDirectoryName = CheckPath('gsa/identif',M_.dname);
-    else
+    options_gsa.pvalue_ks=0;
+    options_gsa.pvalue_corr=0;
+%     if options_gsa.morris==3,
+%         options_gsa = set_default_option(options_gsa,'Nsam',256);
+%         OutputDirectoryName = CheckPath('gsa/identif',M_.dname);
+%     else
         OutputDirectoryName = CheckPath('gsa/screen',M_.dname);
-    end
+%     end
 else
     OutputDirectoryName = CheckPath('gsa',M_.dname);
 end
 
-options_.opt_gsa = options_gsa;
+% options_.opt_gsa = options_gsa;
 
 if (options_gsa.load_stab || options_gsa.load_rmse || options_gsa.load_redform) ...
         && options_gsa.pprior,
@@ -176,22 +208,15 @@ if (options_gsa.load_stab || options_gsa.load_rmse || options_gsa.load_redform)
 end
 
 if options_gsa.stab && ~options_gsa.ppost,
-    x0 = stab_map_(OutputDirectoryName);
+    x0 = stab_map_(OutputDirectoryName,options_gsa);
 end
 
 % reduced form
 % redform_map(namendo, namlagendo, namexo, icomp, pprior, ilog, threshold)
-options_gsa = set_default_option(options_gsa,'logtrans_redform',0);
-options_gsa = set_default_option(options_gsa,'threshold_redform',[]);
-options_gsa = set_default_option(options_gsa,'ksstat_redform',0.1);
-options_gsa = set_default_option(options_gsa,'alpha2_redform',0.3);
-options_gsa = set_default_option(options_gsa,'namendo',[]);
-options_gsa = set_default_option(options_gsa,'namlagendo',[]);
-options_gsa = set_default_option(options_gsa,'namexo',[]);
 
 options_.opt_gsa = options_gsa;
 if options_gsa.identification,
-    map_ident_(OutputDirectoryName);
+    map_ident_(OutputDirectoryName,options_gsa);
 end
 
 if options_gsa.redform && ~isempty(options_gsa.namendo) ...
@@ -205,30 +230,24 @@ if options_gsa.redform && ~isempty(options_gsa.namendo) ...
     if strmatch(':',options_gsa.namlagendo,'exact'),
         options_gsa.namlagendo=M_.endo_names;
     end
-    options_.opt_gsa = options_gsa;
+%     options_.opt_gsa = options_gsa;
     if options_gsa.morris==1,
-        redform_screen(OutputDirectoryName);
+        redform_screen(OutputDirectoryName,options_gsa);
     else
         % check existence of the SS_ANOVA toolbox
-        if ~(exist('gsa_sdp','file')==6 || exist('gsa_sdp','file')==2),
+        if isempty(options_gsa.threshold_redform) && ...
+         ~(exist('gsa_sdp','file')==6 || exist('gsa_sdp','file')==2),
             disp('Download Mapping routines at:')
             disp('http://eemc.jrc.ec.europa.eu/softwareDYNARE-Dowload.htm')
             disp(' ' )
             error('Mapping routines missing!')
         end
 
-        redform_map(OutputDirectoryName);
+        redform_map(OutputDirectoryName,options_gsa);
     end
 end
 % RMSE mapping
 % function [rmse_MC, ixx] = filt_mc_(vvarvecm, loadSA, pfilt, alpha, alpha2)
-options_gsa = set_default_option(options_gsa,'rmse',0);
-options_gsa = set_default_option(options_gsa,'lik_only',0);
-options_gsa = set_default_option(options_gsa,'var_rmse',options_.varobs);
-options_gsa = set_default_option(options_gsa,'pfilt_rmse',0.1);
-options_gsa = set_default_option(options_gsa,'istart_rmse',options_.presample+1);
-options_gsa = set_default_option(options_gsa,'alpha_rmse',0.002);
-options_gsa = set_default_option(options_gsa,'alpha2_rmse',1);
 options_.opt_gsa = options_gsa;
 if options_gsa.rmse,
     if ~options_gsa.ppost
@@ -249,6 +268,12 @@ if options_gsa.rmse,
             end
         end
         if isempty(a),
+           if options_gsa.lik_only,
+               options_.smoother=0;
+               options_.filter_step_ahead=[];
+               options_.forecast=0;
+               options_.filtered_vars=0;               
+           end
 %             dynare_MC([],OutputDirectoryName,data,rawdata,data_info);
             prior_posterior_statistics('gsa',dataset_);
             if options_.bayesian_irf
@@ -273,8 +298,9 @@ if options_gsa.rmse,
     end
     clear a;
 %     filt_mc_(OutputDirectoryName,data_info);
-    filt_mc_(OutputDirectoryName);
+    filt_mc_(OutputDirectoryName,options_gsa);
 end
+options_.opt_gsa = options_gsa;
 
 
 if options_gsa.glue,
diff --git a/matlab/dynare_solve_block_or_bytecode.m b/matlab/dynare_solve_block_or_bytecode.m
index 31d4af22321f382c013cfefa083827fc1be79e37..0dd8074f6d5bc0e152fe8a87cdde255c32305fa4 100644
--- a/matlab/dynare_solve_block_or_bytecode.m
+++ b/matlab/dynare_solve_block_or_bytecode.m
@@ -1,5 +1,5 @@
 function [x,info] = dynare_solve_block_or_bytecode(y, exo, params, options, M)
-% Copyright (C) 2010-2011 Dynare Team
+% Copyright (C) 2010-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/dyntable.m b/matlab/dyntable.m
index 818abb108eeb8477916c9b05253e24c53c2d680a..6df882c81779095e9bd470c0fd54b8f172bbf630 100644
--- a/matlab/dyntable.m
+++ b/matlab/dyntable.m
@@ -1,7 +1,7 @@
 function dyntable(title,headers,labels,values,label_width,val_width, ...
                   val_precis)
 
-% Copyright (C) 2002-2010 Dynare Team
+% Copyright (C) 2002-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -30,7 +30,7 @@ label_width = max(size(deblank(char(headers(1,:),labels)),2))+2;
 
 label_fmt = sprintf('%%-%ds',label_width);
 
-values_length = max(ceil(max(max(log10(abs(values))))),1)+val_precis+1;
+values_length = max(ceil(max(max(log10(abs(values(isfinite(values))))))),1)+val_precis+1;
 if any(values) < 0
     values_length = values_length+1;
 end
diff --git a/matlab/ep/extended_path.m b/matlab/ep/extended_path.m
index 657356f774f390aaf03627ff96617e4d04e2b0f4..5633438605818a6a61773efe62436ad8ad09b062 100644
--- a/matlab/ep/extended_path.m
+++ b/matlab/ep/extended_path.m
@@ -14,7 +14,7 @@ function time_series = extended_path(initial_conditions,sample_size)
 %
 % SPECIAL REQUIREMENTS
 
-% Copyright (C) 2009, 2010, 2011 Dynare Team
+% Copyright (C) 2009-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/ep/extended_path_parfor.m b/matlab/ep/extended_path_parfor.m
index f3525cbda0849d7da9090fa385a86353d9fa7f37..da1a69d3b1948da8e1f7125d12e14eed9dfc4620 100644
--- a/matlab/ep/extended_path_parfor.m
+++ b/matlab/ep/extended_path_parfor.m
@@ -1,4 +1,4 @@
-function time_series = extended_path(initial_conditions,sample_size)
+function time_series = extended_path_parfor(initial_conditions,sample_size)
 % Stochastic simulation of a non linear DSGE model using the Extended Path method (Fair and Taylor 1983). A time
 % series of size T  is obtained by solving T perfect foresight models.
 %
@@ -14,7 +14,7 @@ function time_series = extended_path(initial_conditions,sample_size)
 %
 % SPECIAL REQUIREMENTS
 
-% Copyright (C) 2009, 2010, 2011 Dynare Team
+% Copyright (C) 2009-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/ep/homotopic_steps.m b/matlab/ep/homotopic_steps.m
index e8d37907ee0efe53fbc4b12ea11c2682241eef0a..80e455c664117c7ba355e4f7d9393ddd4ffcc612 100644
--- a/matlab/ep/homotopic_steps.m
+++ b/matlab/ep/homotopic_steps.m
@@ -1,4 +1,22 @@
 function [info,tmp] = homotopic_steps(endo_simul0,exo_simul0,initial_weight,step_length,pfm)
+
+% Copyright (C) 2012 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 options_ oo_
 
 %Set bytecode flag
diff --git a/matlab/evaluate_likelihood.m b/matlab/evaluate_likelihood.m
index b989934ad553fa1e14bff51e30f9c9ddb1b7cffe..76fe3b42713cfbbc094b51b170f45c744dd02858 100644
--- a/matlab/evaluate_likelihood.m
+++ b/matlab/evaluate_likelihood.m
@@ -18,7 +18,7 @@ function [llik,parameters] = evaluate_likelihood(parameters)
 % [2] This function use persistent variables for the dataset and the description of the missing observations. Consequently, if this function
 %     is called more than once (by changing the value of parameters) the sample *must not* change.
 
-% Copyright (C) 2009-2010 Dynare Team
+% Copyright (C) 2009-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -82,9 +82,7 @@ if isempty(dataset)
     dataset = initialize_dataset(options_.datafile,options_.varobs,options_.first_obs,options_.nobs,transformation,options_.prefilter,xls);
 end
 
-pshape_original   = bayestopt_.pshape;
-bayestopt_.pshape = Inf(size(bayestopt_.pshape));
-
 llik = -dsge_likelihood(parameters,dataset,options_,M_,estim_params_,bayestopt_,oo_);
+ldens = evaluate_prior(parameters);
+llik = llik - ldens;
 
-bayestopt_.pshape = pshape_original;
\ No newline at end of file
diff --git a/matlab/evaluate_planner_objective.m b/matlab/evaluate_planner_objective.m
index 855e16fe541d97b7e957f760aacd3579d9342bf2..ae90b08c0496d69783efff56a831e5830453c9fb 100644
--- a/matlab/evaluate_planner_objective.m
+++ b/matlab/evaluate_planner_objective.m
@@ -1,21 +1,17 @@
-function planner_objective_value = evaluate_planner_objective(M,oo,options)
+function planner_objective_value = evaluate_planner_objective(M,options,oo)
 
 %function oo1 = evaluate_planner_objective(dr,M,oo,options)
 %  computes value of planner objective function     
 % 
 % INPUTS
-%   dr:       (structure) decision rule
 %   M:        (structure) model description
-%   oo:       (structure) output results
 %   options:  (structure) options
+%   oo:       (structure) output results
 %    
-% OUTPUTS
-%   oo1:      (structure) updated output results
-%
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2007-2011 Dynare Team
+% Copyright (C) 2007-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -105,30 +101,47 @@ else
     Wyu = Uy*gyu+Uyygygu+beta*(Wy*Gyu+Wyygygu);
     Wss = (Uy*gss+beta*(Wuu*M.Sigma_e(:)+Wy*Gss))/(1-beta);
 end
+% initialize yhat1 at the steady state
+yhat1 = oo.steady_state;
 if options.ramsey_policy
-    yhat = zeros(M.endo_nbr,1);
-    yhat(1:M.orig_endo_nbr) = oo.steady_state(1:M.orig_endo_nbr);
-else
-    yhat = oo.endo_simul;
+    % initialize le Lagrange multipliers to 0 in yhat2
+    yhat2 = zeros(M.endo_nbr,1);
+    yhat2(1:M.orig_endo_nbr) = oo.steady_state(1:M.orig_endo_nbr);
+end
+if ~isempty(M.endo_histval)
+    % initialize endogenous state variable to histval if necessary
+    yhat1(1:M.orig_endo_nbr) = M.endo_histval(1:M.orig_endo_nbr);
+    if options.ramsey_policy
+        yhat2(1:M.orig_endo_nbr) = M.endo_histval(1:M.orig_endo_nbr);
+    end
 end
-yhat = yhat(dr.order_var(nstatic+(1:npred)),1)-dr.ys(dr.order_var(nstatic+(1:npred)));
+yhat1 = yhat1(dr.order_var(nstatic+(1:npred)),1)-dr.ys(dr.order_var(nstatic+(1:npred)));
+yhat2 = yhat2(dr.order_var(nstatic+(1:npred)),1)-dr.ys(dr.order_var(nstatic+(1:npred)));
 u = oo.exo_simul(1,:)';
 
-[Wyyyhatyhat, err] = A_times_B_kronecker_C(Wyy,yhat,yhat,options.threads.kronecker.A_times_B_kronecker_C);
+[Wyyyhatyhat1, err] = A_times_B_kronecker_C(Wyy,yhat1,yhat1,options.threads.kronecker.A_times_B_kronecker_C);
 mexErrCheck('A_times_B_kronecker_C', err);
 [Wuuuu, err] = A_times_B_kronecker_C(Wuu,u,u,options.threads.kronecker.A_times_B_kronecker_C);
 mexErrCheck('A_times_B_kronecker_C', err);
-[Wyuyhatu, err] = A_times_B_kronecker_C(Wyu,yhat,u,options.threads.kronecker.A_times_B_kronecker_C);
+[Wyuyhatu1, err] = A_times_B_kronecker_C(Wyu,yhat1,u,options.threads.kronecker.A_times_B_kronecker_C);
 mexErrCheck('A_times_B_kronecker_C', err);
-planner_objective_value(1) = Wbar+Wy*yhat+Wu*u+Wyuyhatu ...
-    + 0.5*(Wyyyhatyhat + Wuuuu+Wss);
-planner_objective_value(2) = Wbar + 0.5*Wss;
+planner_objective_value(1) = Wbar+Wy*yhat1+Wu*u+Wyuyhatu1 ...
+    + 0.5*(Wyyyhatyhat1 + Wuuuu+Wss);
+if options.ramsey_policy
+    [Wyyyhatyhat2, err] = A_times_B_kronecker_C(Wyy,yhat2,yhat2,options.threads.kronecker.A_times_B_kronecker_C);
+    mexErrCheck('A_times_B_kronecker_C', err);
+    [Wyuyhatu2, err] = A_times_B_kronecker_C(Wyu,yhat2,u,options.threads.kronecker.A_times_B_kronecker_C);
+    mexErrCheck('A_times_B_kronecker_C', err);
+    planner_objective_value(2) = Wbar+Wy*yhat2+Wu*u+Wyuyhatu2 ...
+        + 0.5*(Wyyyhatyhat2 + Wuuuu+Wss);
+end
+
 if ~options.noprint
     disp(' ')
     disp('Approximated value of planner objective function')
     disp(['    - with initial Lagrange multipliers set to 0: ' ...
-          num2str(planner_objective_value(1)) ])
-    disp(['    - with initial Lagrange multipliers set to steady state: ' ...
           num2str(planner_objective_value(2)) ])
+    disp(['    - with initial Lagrange multipliers set to steady state: ' ...
+          num2str(planner_objective_value(1)) ])
     disp(' ')
 end
\ No newline at end of file
diff --git a/matlab/evaluate_prior.m b/matlab/evaluate_prior.m
index db24e28ac286866e411b77d3a81156b71555303a..b8b2f7b0baeed35d10efde8038bf9263c61e07d5 100644
--- a/matlab/evaluate_prior.m
+++ b/matlab/evaluate_prior.m
@@ -16,7 +16,7 @@ function [ldens,parameters] = evaluate_prior(parameters)
 % REMARKS
 % [1] This function cannot evaluate the prior density of a dsge-var model...
 
-% Copyright (C) 2009 Dynare Team
+% Copyright (C) 2009-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -61,5 +61,5 @@ if ischar(parameters)
         error
     end
 end
-clear('priordens');
+
 ldens = priordens(parameters, bayestopt_.pshape, bayestopt_.p6, bayestopt_.p7, bayestopt_.p3, bayestopt_.p4);
\ No newline at end of file
diff --git a/matlab/evaluate_smoother.m b/matlab/evaluate_smoother.m
index 5344cf8349a8dcdc65898628f2ae74fbfb4dc7e0..d923027a2a59ade05d80930337a303dfdedb1dbb 100644
--- a/matlab/evaluate_smoother.m
+++ b/matlab/evaluate_smoother.m
@@ -24,7 +24,7 @@ function oo = evaluate_smoother(parameters)
 % [1] This function use persistent variables for the dataset and the description of the missing observations. Consequently, if this function
 %     is called more than once (by changing the value of parameters) the sample *must not* change.
 
-% Copyright (C) 2010-2011 Dynare Team
+% Copyright (C) 2010-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -43,8 +43,7 @@ function oo = evaluate_smoother(parameters)
 
 global options_ M_ bayestopt_ oo_
 
-persistent load_data
-persistent gend  data  data_index  number_of_observations  no_more_missing_observations
+persistent dataset_
 
 if nargin==0
     parameters = 'posterior_mode';
@@ -79,43 +78,22 @@ if ischar(parameters)
     end
 end
 
-if isempty(load_data)
-    % Get the data.
-    n_varobs = size(options_.varobs,1);
-    rawdata = read_variables(options_.datafile,options_.varobs,[],options_.xls_sheet,options_.xls_range);
-    options_ = set_default_option(options_,'nobs',size(rawdata,1)-options_.first_obs+1);
-    gend = options_.nobs;
-    rawdata = rawdata(options_.first_obs:options_.first_obs+gend-1,:);
-    % Transform the data.
-    if options_.loglinear
-        if ~options_.logdata
-            rawdata = log(rawdata);
-        end
-    end
-    % Test if the data set is real.
-    if ~isreal(rawdata)
-        error('There are complex values in the data! Probably  a wrong transformation')
+if isempty(dataset_)
+    % Load and transform data.
+    transformation = [];
+    if options_.loglinear && ~options_.logdata
+        transformation = @log;
     end
-    % Detrend the data.
-    options_.missing_data = any(any(isnan(rawdata)));
-    if options_.prefilter == 1
-        if options_.missing_data
-            bayestopt_.mean_varobs = zeros(n_varobs,1);
-            for variable=1:n_varobs
-                rdx = find(~isnan(rawdata(:,variable)));
-                m = mean(rawdata(rdx,variable));
-                rawdata(rdx,variable) = rawdata(rdx,variable)-m;
-                bayestopt_.mean_varobs(variable) = m;
-            end
-        else
-            bayestopt_.mean_varobs = mean(rawdata,1)';
-            rawdata = rawdata-repmat(bayestopt_.mean_varobs',gend,1);
-        end
+    xls.sheet = options_.xls_sheet;
+    xls.range = options_.xls_range;
+
+    if ~isfield(options_,'nobs')
+        options_.nobs = [];
     end
-    data = transpose(rawdata);
-    % Handle the missing observations.
-    [data_index,number_of_observations,no_more_missing_observations] = describe_missing_data(data,gend,n_varobs);
-    missing_value = ~(number_of_observations == gend*n_varobs);
+
+    dataset_ = initialize_dataset(options_.datafile,options_.varobs,options_.first_obs,options_.nobs,transformation,options_.prefilter,xls);
+    options_.nobs = dataset_.info.ntobs;
+
     % Determine if a constant is needed.
     if options_.steadystate_flag% if the *_steadystate.m file is provided.
         [ys,tchek] = feval([M_.fname '_steadystate'],...
@@ -143,15 +121,15 @@ if isempty(load_data)
     else
         options_.noconstant = 0;
     end
-    load_data = 1;
 end
 
 pshape_original   = bayestopt_.pshape;
 bayestopt_.pshape = Inf(size(bayestopt_.pshape));
-clear('priordens')%
+clear('priordens')
+
+[atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,T,R,P,PK,decomp] = ...
+    DsgeSmoother(parameters,dataset_.info.ntobs,dataset_.data,dataset_.missing.aindex,dataset_.missing.state);
 
-[atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,T,R,P,PK,decomp] ...
-    = DsgeSmoother(parameters,gend,data,data_index,missing_value);
 oo.Smoother.SteadyState = ys;
 oo.Smoother.TrendCoeffs = trend_coeff;
 if options_.filter_covariance
diff --git a/matlab/evaluate_static_model.m b/matlab/evaluate_static_model.m
index 52709a003e7ca1ac3fbd52bebaf9330a368ad4eb..e9c8ba3f1c275cfbdf499e62516e2b7551b7e57d 100644
--- a/matlab/evaluate_static_model.m
+++ b/matlab/evaluate_static_model.m
@@ -20,7 +20,7 @@ function [residuals,check1,jacob] = evaluate_static_model(ys,exo_ss,params,M,opt
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2001-2011 Dynare Team
+% Copyright (C) 2001-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/evaluate_steady_state.m b/matlab/evaluate_steady_state.m
index ee8f260545c561343f8f3d1321f6e4731decd36c..23936aaca5058f5b0942b8a01b3ea95c5ac9ba62 100644
--- a/matlab/evaluate_steady_state.m
+++ b/matlab/evaluate_steady_state.m
@@ -22,7 +22,7 @@ function [ys,params,info] = evaluate_steady_state(ys_init,M,options,oo,steadysta
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2001-2011 Dynare Team
+% Copyright (C) 2001-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/evaluate_steady_state_file.m b/matlab/evaluate_steady_state_file.m
index 8a218e743298a3667c6112367e43a94668a2b475..e97689c8bc99660e499f568aaf7aae2d93df1c72 100644
--- a/matlab/evaluate_steady_state_file.m
+++ b/matlab/evaluate_steady_state_file.m
@@ -61,15 +61,18 @@ function [ys,params,info] = evaluate_steady_state_file(ys_init,exo_ss,M,options)
     
     updated_params_flag = max(abs(params1-params)) > 1e-12 || ~isequal(isnan(params1),isnan(params)); %checks whether numbers or NaN changed
 
+    h_set_auxiliary_variables = str2func([M.fname '_set_auxiliary_variables']);
     if  isnan(updated_params_flag) || (updated_params_flag  && any(isnan(params(~isnan(params))-params1(~isnan(params))))) %checks if new NaNs were added
         info(1) = 24;
         info(2) = NaN;
+        ys = h_set_auxiliary_variables(ys,exo_ss,params);
         return
     end
 
     if updated_params_flag && ~isreal(params1)
         info(1) = 23;
         info(2) = sum(imag(params).^2);
+        ys = h_set_auxiliary_variables(ys,exo_ss,params);
         return
     end
     
@@ -79,7 +82,6 @@ function [ys,params,info] = evaluate_steady_state_file(ys_init,exo_ss,M,options)
 
     % adding values for auxiliary variables
     if length(M.aux_vars) > 0 && ~options.ramsey_policy
-        h_set_auxiliary_variables = str2func([M.fname '_set_auxiliary_variables']);
         ys = h_set_auxiliary_variables(ys,exo_ss,params);
     end
 
diff --git a/matlab/fastgensylv.m b/matlab/fastgensylv.m
new file mode 100644
index 0000000000000000000000000000000000000000..40166673b506ad097a5db8809ddb43f8de4062da
--- /dev/null
+++ b/matlab/fastgensylv.m
@@ -0,0 +1,129 @@
+function X = fastgensylv(A, B, C, D, tol,maxit,X0)
+
+%@info:
+%! @deftypefn {Function File} {[@var{X1}, @var{info}] =} fastgensylv (@var{A},@var{B},@var{C},@var{tol},@var{maxit},@var{X0})
+%! @anchor{fastgensylv}
+%! @sp 1
+%! Solves the Sylvester equation A * X + B * X * C + D = 0 for X.
+%! @sp 2
+%! @strong{Inputs}
+%! @sp 1
+%! @table @ @var
+%! @item A
+%! Square matrix of doubles, n*n.
+%! @item B
+%! Square matrix of doubles, n*n.
+%! @item C
+%! Square matrix of doubles, n*n.
+%! @item tol
+%! Scalar double, tolerance parameter.
+%! @item maxit
+%! Integer scalar, maximum number of iterations.
+%! @item X0
+%! Square matrix of doubles, n*n, initial condition.
+%! @end table
+%! @sp 1
+%! @strong{Outputs}
+%! @sp 1
+%! @table @ @var
+%! @item X
+%! Square matrix of doubles, n*n, solution of the matrix equation.
+%! @item info
+%! Scalar integer, if nonzero the algorithm failed in finding the solution of the matrix equation.
+%! @end table
+%! @sp 2
+%! @strong{This function is called by:}
+%! @sp 2
+%! @strong{This function calls:}
+%! @sp 2
+%! @end deftypefn
+%@eod:
+
+% Copyright (C) 2012 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 size(A,1)~=size(D,1) || size(A,1)~=size(B,1) || size(C,2)~=size(D,2)
+    error('fastgensylv:: Dimension error!')
+end
+
+if nargin<7 || isempty(X0)
+    X = zeros(size(A,2),size(C,1));
+elseif nargin==7 && ~isempty(X0)
+    X = X0;
+end
+
+kk = 0;
+cc = 1+tol;
+
+iA = inv(A);
+Z = - (B * X * C + D);
+
+while kk<=maxit && cc>tol
+    X = iA * Z;
+    Z_old = Z;
+    Z = - (B * X * C + D);
+    cc = max(sum(abs(Z-Z_old)));
+    kk = kk + 1;
+end
+
+if kk==maxit && cc>tol
+    error(['fastgensylv:: Convergence not achieved in fixed point solution of Sylvester equation after ' int2str(maxit) ' iterations']);
+end
+
+
+
+
+% function X = fastgensylv(A, B, C, D)
+% Solve the Sylvester equation:
+% A * X + B * X * C + D = 0
+% INPUTS
+%   A
+%   B
+%   C
+%   D
+%   block : block number (for storage purpose) 
+%   tol : convergence criteria
+% OUTPUTS
+%   X solution
+%    
+% ALGORITHM
+%   fixed point method
+%   MARLLINY MONSALVE (2008): "Block linear method for large scale
+%   Sylvester equations", Computational & Applied Mathematics, Vol 27, n°1,
+%   p47-59
+%   ||A^-1||.||B||.||C|| < 1 is a suffisant condition:
+%    - to get a unique solution for the Sylvester equation
+%    - to get a convergent fixed-point algorithm
+%
+% SPECIAL REQUIREMENTS
+%   none.  
+% Copyright (C) 1996-2012 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/>.
diff --git a/matlab/forecast_graphs.m b/matlab/forecast_graphs.m
index 7c63a38f8326df8389c544057bd0ba2d91c0502c..d058ee5888b3c656d9140aa71a9f73302f86e075 100644
--- a/matlab/forecast_graphs.m
+++ b/matlab/forecast_graphs.m
@@ -1,6 +1,6 @@
 function forecast_graphs(var_list)
 
-% Copyright (C) 2008-2010 Dynare Team
+% Copyright (C) 2008-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/gensylv/gensylv.m b/matlab/gensylv/gensylv.m
index 3b8693cc53c7acf2960393a8f7c35837bd0524af..26624fea741d87645c77f2398edb56a5b44cd04a 100644
--- a/matlab/gensylv/gensylv.m
+++ b/matlab/gensylv/gensylv.m
@@ -19,7 +19,7 @@ function [err, E] = gensylv(kron_prod,A,B,C0,D)
 % SPECIAL REQUIREMENTS
 %   none.  
 
-% Copyright (C) 1996-2010 Dynare Team
+% Copyright (C) 1996-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/gensylv/sylvester3.m b/matlab/gensylv/sylvester3.m
index f50b9bae2acee5ed737a102e6e7aa718420fd780..38465d6c4cb39c491ad36ddfaf8edcf66925bc93 100644
--- a/matlab/gensylv/sylvester3.m
+++ b/matlab/gensylv/sylvester3.m
@@ -1,7 +1,7 @@
 function x=sylvester3(a,b,c,d)
 % solves a*x+b*x*c=d where d is [n x m x p]
 
-% Copyright (C) 2005-2009 Dynare Team
+% Copyright (C) 2005-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/gensylv_fp.m b/matlab/gensylv_fp.m
index 6b2c5fe4844330d7b826ec659ca7f195d9f9e6d5..2e5c167b5ecf2e4fd9d876be43fc6e2b02612c5b 100644
--- a/matlab/gensylv_fp.m
+++ b/matlab/gensylv_fp.m
@@ -23,7 +23,7 @@ function X = gensylv_fp(A, B, C, D, block, tol)
 %
 % SPECIAL REQUIREMENTS
 %   none.  
-% Copyright (C) 1996-2010 Dynare Team
+% Copyright (C) 1996-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/getH.m b/matlab/getH.m
index 71a0124373b25a5d9acf1510c841ae0549a49232..825d25138298869f2515cdfd8d79ed5f6fef9cd4 100644
--- a/matlab/getH.m
+++ b/matlab/getH.m
@@ -1,8 +1,8 @@
-function [H, dA, dOm, Hss, gp, d2A, d2Om, H2ss] = getH(A, B, M_,oo_,kronflag,indx,indexo)
+function [H, dA, dOm, Hss, gp, d2A, d2Om, H2ss] = getH(A, B, M_,oo_,options_,kronflag,indx,indexo)
 
 % computes derivative of reduced form linear model w.r.t. deep params
 %
-% Copyright (C) 2010-2011 Dynare Team
+% Copyright (C) 2010-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -20,47 +20,73 @@ function [H, dA, dOm, Hss, gp, d2A, d2Om, H2ss] = getH(A, B, M_,oo_,kronflag,ind
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 if nargin<3 || isempty(kronflag), kronflag = 0; end
-if nargin<4 || isempty(indx), indx = [1:M_.param_nbr];, end,
-if nargin<5 || isempty(indexo), indexo = [];, end,
-
+if nargin<4 || isempty(indx), indx = [1:M_.param_nbr]; end,
+if nargin<5 || isempty(indexo), indexo = []; end,
 
 [I,J]=find(M_.lead_lag_incidence');
 yy0=oo_.dr.ys(I);
+param_nbr = length(indx);
+if nargout>5,
+    param_nbr_2 = param_nbr*(param_nbr+1)/2;
+end
+
+m = size(A,1);
+n = size(B,2);
+
+if kronflag==-2,
+    if nargout>5,
+        [residual, g1, g2 ] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', ...
+            M_.params, oo_.dr.ys, 1);
+        g22 = hessian('thet2tau',[M_.params(indx)],options_.gstep,M_, oo_, indx,[],-1);
+        H2ss=g22(1:M_.endo_nbr,:);
+        H2ss = reshape(H2ss,[M_.endo_nbr param_nbr param_nbr]);
+        g22=g22(M_.endo_nbr+1:end,:);
+        g22 = reshape(g22,[size(g1) param_nbr param_nbr]);
+    else
+        [residual, g1 ] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', ...
+            M_.params, oo_.dr.ys, 1);        
+    end
+    gp = fjaco('thet2tau',[M_.params(indx)],M_, oo_, indx,[],-1);
+    Hss=gp(1:M_.endo_nbr,:);
+    gp=gp(M_.endo_nbr+1:end,:);
+    gp = reshape(gp,[size(g1) param_nbr]);
+else
+
 % yy0=[];
 % for j=1:size(M_.lead_lag_incidence,1);
 %     yy0 = [ yy0; oo_.dr.ys(find(M_.lead_lag_incidence(j,:)))];
 % end
 dyssdtheta=zeros(length(oo_.dr.ys),M_.param_nbr);
+d2yssdtheta=zeros(length(oo_.dr.ys),M_.param_nbr,M_.param_nbr);
 if nargout>5,
     [residual, gg1, gg2] = feval([M_.fname,'_static'],oo_.dr.ys, oo_.exo_steady_state', M_.params);
     [df, gp, d2f] = feval([M_.fname,'_params_derivs'],yy0, oo_.exo_steady_state', ...
-        M_.params, oo_.dr.ys, 1, dyssdtheta);
+        M_.params, oo_.dr.ys, 1, dyssdtheta, d2yssdtheta);
     d2f = get_all_resid_2nd_derivs(d2f,length(oo_.dr.ys),M_.param_nbr);
     d2f = d2f(:,indx,indx);
     if isempty(find(gg2)),
         for j=1:length(indx),
-        d2yssdtheta(:,:,j) = -gg1\d2f(:,:,j);
+        d2yssdtheta(:,indx,j) = -gg1\d2f(:,:,j);
         end
     else
         gam = d2f*0;
         for j=1:length(indx),
-        d2yssdtheta(:,:,j) = -gg1\(d2f(:,:,j)+gam(:,:,j));
+        d2yssdtheta(:,indx,j) = -gg1\(d2f(:,:,j)+gam(:,:,j));
         end
     end
 else
     [residual, gg1] = feval([M_.fname,'_static'],oo_.dr.ys, oo_.exo_steady_state', M_.params);
     df = feval([M_.fname,'_params_derivs'],yy0, oo_.exo_steady_state', ...
-        M_.params, oo_.dr.ys, 1, dyssdtheta);
+        M_.params, oo_.dr.ys, 1, dyssdtheta, d2yssdtheta);
 end
 dyssdtheta = -gg1\df;
 
 if any(any(isnan(dyssdtheta))),    
     [U,T] = schur(gg1);
-    global options_
     qz_criterium=options_.qz_criterium;
     e1 = abs(ordeig(T)) < qz_criterium-1;
     k = sum(e1);       % Number non stationary variables.
-    n = length(e1)-k;  % Number of stationary variables.
+%     n = length(e1)-k;  % Number of stationary variables.
     [U,T] = ordschur(U,T,e1);
     T = T(k+1:end,k+1:end);
     dyssdtheta = -U(:,k+1:end)*(T\U(:,k+1:end)')*df;
@@ -71,22 +97,24 @@ if any(any(isnan(dyssdtheta))),
     end
 end
 if nargout>5,
-[df, gp, d2f, gpp] = feval([M_.fname,'_params_derivs'],yy0, oo_.exo_steady_state', ...
-           M_.params, oo_.dr.ys, 1, dyssdtheta);
-H2ss = d2yssdtheta(oo_.dr.order_var,:,:);
-[residual, g1, g2, g3] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', ...
-                            M_.params, oo_.dr.ys, 1);
+    [df, gp, d2f, gpp] = feval([M_.fname,'_params_derivs'],yy0, oo_.exo_steady_state', ...
+        M_.params, oo_.dr.ys, 1, dyssdtheta, d2yssdtheta);
+    H2ss = d2yssdtheta(oo_.dr.order_var,:,:);
+    [residual, g1, g2, g3] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', ...
+        M_.params, oo_.dr.ys, 1);
+    nelem=size(g1,2);
+    g22 = get_all_2nd_derivs(gpp,m,nelem,M_.param_nbr);
+    g22 = g22(:,:,indx,indx);
 else
-[df, gp] = feval([M_.fname,'_params_derivs'],yy0, oo_.exo_steady_state', ...
-           M_.params, oo_.dr.ys, 1, dyssdtheta);
-[residual, g1, g2 ] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', ...
-                            M_.params, oo_.dr.ys, 1);
+    [df, gp] = feval([M_.fname,'_params_derivs'],yy0, oo_.exo_steady_state', ...
+        M_.params, oo_.dr.ys, 1, dyssdtheta,d2yssdtheta);
+    [residual, g1, g2 ] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', ...
+        M_.params, oo_.dr.ys, 1);
 end
 
 Hss = dyssdtheta(oo_.dr.order_var,indx);
 dyssdtheta = dyssdtheta(I,:);
 [nr, nc]=size(g2);
-[m, nelem]=size(g1);
 nc = sqrt(nc);
 ns = max(max(M_.lead_lag_incidence));
 gp2 = gp*0;
@@ -105,14 +133,8 @@ end
 
 gp = gp+gp2;
 gp = gp(:,:,indx);
-param_nbr = length(indx);
-if nargout>5,
-    param_nbr_2 = param_nbr*(param_nbr+1)/2;
 end
 
-m = size(A,1);
-n = size(B,2);
-
 
 
 klen = M_.maximum_endo_lag + M_.maximum_endo_lead + 1;
@@ -120,9 +142,6 @@ k11 = M_.lead_lag_incidence(find([1:klen] ~= M_.maximum_endo_lag+1),:);
 a = g1(:,nonzeros(k11'));
 da = gp(:,nonzeros(k11'),:);
 if nargout > 5,
-    nelem = size(g1,2);
-    g22 = get_all_2nd_derivs(gpp,m,nelem,M_.param_nbr);
-    g22 = g22(:,:,indx,indx);
     d2a = g22(:,nonzeros(k11'),:,:);
 end
 kstate = oo_.dr.kstate;
@@ -250,8 +269,8 @@ end
 % B0=B;
 % B = Bx; clear Bx B1;
 
-m = size(A,1);
-n = size(B,2);
+% m = size(A,1);
+% n = size(B,2);
 
 % Dg1 = zeros(m,m,param_nbr);
 % Dg1(:, nf, :) = -gp(:,M_.lead_lag_incidence(3,nf),:);
@@ -338,7 +357,7 @@ if kronflag==1, % kronecker products
 elseif kronflag==-1, % perturbation
     fun = 'thet2tau';
     params0 = M_.params;
-    H = fjaco(fun,[sqrt(diag(M_.Sigma_e(indexo,indexo))); M_.params(indx)],indx,indexo);
+    H = fjaco(fun,[sqrt(diag(M_.Sigma_e(indexo,indexo))); M_.params(indx)], M_, oo_, indx, indexo);
     assignin('base','M_', M_);
     assignin('base','oo_', oo_);
 
@@ -499,7 +518,7 @@ is=find(gpp(:,3)==i);
 is=is(find(gpp(is,4)==j));
 
 if ~isempty(is),
-    g22(gpp(is,1),gpp(is,2))=gpp(is,5);
+    g22(sub2ind([m,n],gpp(is,1),gpp(is,2)))=gpp(is,5)';
 end
 return
 
diff --git a/matlab/getJJ.m b/matlab/getJJ.m
index b6e6805a9d0db38555fe0cd5d66dd72e9361c9dc..b717858a59689cca6104d713648f66ea73f71835 100644
--- a/matlab/getJJ.m
+++ b/matlab/getJJ.m
@@ -28,15 +28,26 @@ warning('off','MATLAB:divideByZero')
 if kronflag == -1,
     fun = 'thet2tau';
     params0 = M_.params;
-    JJ = fjaco(fun,[sqrt(diag(M_.Sigma_e(indexo,indexo))); M_.params(indx)],indx,indexo,1,mf,nlags,useautocorr);
+    JJ = fjaco(fun,[sqrt(diag(M_.Sigma_e(indexo,indexo))); M_.params(indx)],M_, oo_, indx,indexo,1,mf,nlags,useautocorr);
     M_.params = params0;
     params0 = M_.params;
-    H = fjaco(fun,[sqrt(diag(M_.Sigma_e(indexo,indexo))); M_.params(indx)],indx,indexo,0,mf,nlags,useautocorr);
+    H = fjaco(fun,[sqrt(diag(M_.Sigma_e(indexo,indexo))); M_.params(indx)],M_, oo_, indx,indexo,0,mf,nlags,useautocorr);
     M_.params = params0;
+    params0 = M_.params;
+    gp = fjaco(fun,[sqrt(diag(M_.Sigma_e(indexo,indexo))); M_.params(indx)],M_, oo_, indx,indexo,-1);
+    M_.params = params0;
+    offset = length(indexo);
+    gp = gp(1:M_.endo_nbr,offset+1:end);
+    dYss = H(1:M_.endo_nbr,offset+1:end);
+    dA = reshape(H(M_.orig_endo_nbr+[1:numel(A)],:),[size(A),size(H,2)]);
+    dOm = dA*0;
+    for j=1:size(H,2),
+        dOm(:,:,j) = dyn_unvech(H(M_.orig_endo_nbr+numel(A)+1:end,j));
+    end
     assignin('base','M_', M_);
     assignin('base','oo_', oo_);
 else
-    [H, dA, dOm, dYss, gp] = getH(A, B, M_,oo_,kronflag,indx,indexo);
+    [H, dA, dOm, dYss, gp] = getH(A, B, M_,oo_,options_,kronflag,indx,indexo);
     gp = reshape(gp,size(gp,1)*size(gp,2),size(gp,3));
     gp = [dYss; gp];
     %   if isempty(H),
diff --git a/matlab/getPowerDeriv.m b/matlab/getPowerDeriv.m
index ab8d6220e8aaea033e53c6cf340e2c410d0dcca2..8d1a1b022f1479b682c495a42e19fbb4daeafb80 100644
--- a/matlab/getPowerDeriv.m
+++ b/matlab/getPowerDeriv.m
@@ -13,7 +13,7 @@ function dxp=getPowerDeriv(x,p,k)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/get_moments_size.m b/matlab/get_moments_size.m
index 4f0237bfa7fa9ce1fa0026eefb109034ddc65f58..aa8087c025500e342c8bfa5848765113ef9cf146 100644
--- a/matlab/get_moments_size.m
+++ b/matlab/get_moments_size.m
@@ -11,7 +11,7 @@ function s=get_moments_size(options)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2008-2009 Dynare Team
+% Copyright (C) 2008-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/get_name_of_the_last_mh_file.m b/matlab/get_name_of_the_last_mh_file.m
index c3f39e6a6477d506e01bfe810947c142bac10fc9..cd198f8169c65a522d216018a269b3bb50a4279b 100644
--- a/matlab/get_name_of_the_last_mh_file.m
+++ b/matlab/get_name_of_the_last_mh_file.m
@@ -11,7 +11,7 @@ function [mhname,info] = get_name_of_the_last_mh_file(M_)
 %                          file. Otherwise info is equal to zero (a likely reason for this is 
 %                          that the mcmc simulations were not completed).      
 
-% Copyright (C) 2008-2010 Dynare Team
+% Copyright (C) 2008-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/get_prior_info.m b/matlab/get_prior_info.m
index 7c209503a3e6bc7e3cbb0e3a5a2debab783fb5aa..3c9154a2442102ac451f8202d0ac5baed872b3ac 100644
--- a/matlab/get_prior_info.m
+++ b/matlab/get_prior_info.m
@@ -10,7 +10,7 @@ function get_prior_info(info,plt_flag)
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2009 Dynare Team
+% Copyright (C) 2009-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -108,7 +108,7 @@ end
 M_.dname = M_.fname;
 
 if info==1% Prior simulations (BK).
-    results = prior_sampler(0,M_,bayestopt_,options_,oo_);
+    results = prior_sampler(0,M_,bayestopt_,options_,oo_,estim_params_);
     % Display prior mass info
     disp(['Prior mass = ' num2str(results.prior.mass)])
     disp(['BK indeterminacy share                = ' num2str(results.bk.indeterminacy_share)])
diff --git a/matlab/set_stationary_variables_list.m b/matlab/get_variables_list.m
similarity index 83%
rename from matlab/set_stationary_variables_list.m
rename to matlab/get_variables_list.m
index 33b44724282b6d134ea439a2e371a22ea012621c..853b1169f905bba2345468587a02ac32e3903d5a 100644
--- a/matlab/set_stationary_variables_list.m
+++ b/matlab/get_variables_list.m
@@ -1,13 +1,12 @@
-function [ivar,vartan,options_] = set_stationary_variables_list(options_,M_)
-% This function builds a vector of indices targeting to the stationary
-% variables in varlist.
+function [ivar,vartan,options_] = get_variables_list(options_,M_)
+% This function builds a vector of indices in varlist or varobs.
 % 
 % INPUTS 
 %   o options_   [structure]  Describes global options. 
 %   o M_         [structure]  Describes the model.
 % OUTPUTS 
 %   o ivar       [integer]    nvar*1 vector of indices (nvar is the number
-%                             of stationary variables).
+%                             of variables).
 %   o vartan     [char]       array of characters (with nvar rows).
 %   o options_   [structure]  Describes global options.
 % 
@@ -17,7 +16,7 @@ function [ivar,vartan,options_] = set_stationary_variables_list(options_,M_)
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2007-2011 Dynare Team
+% Copyright (C) 2007-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/global_initialization.m b/matlab/global_initialization.m
index e8c679ae5091133e518f0affeb9f93ac5ad21b4c..fdb7af901301ed7ef7b935bc8eeabc958884aaec 100644
--- a/matlab/global_initialization.m
+++ b/matlab/global_initialization.m
@@ -28,8 +28,7 @@ function global_initialization()
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-global oo_ M_ options_ estim_params_ bayestopt_ estimation_info ex0_ ys0_ ...
-    ex_det0_
+global oo_ M_ options_ estim_params_ bayestopt_ estimation_info ex0_ ys0_  ex_det0_
 
 estim_params_ = [];
 bayestopt_ = [];
@@ -238,6 +237,7 @@ options_.pruning = 0;
 options_.solve_algo = 2;
 options_.linear = 0;
 options_.replic = 50;
+options_.simul_replic = 1;
 options_.drop = 100;
 % if mjdgges.dll (or .mexw32 or ....) doesn't exist, matlab/qz is added to the path.
 % There exists now qz/mjdgges.m that contains the calls to the old Sims code
@@ -314,6 +314,7 @@ options_.MaxNumberOfBytes = 1e6;
 options_.MaximumNumberOfMegaBytes = 111;
 options_.PosteriorSampleSize = 1000;
 options_.analytic_derivation = 0;
+options_.analytic_derivation_mode = 0;
 options_.bayesian_irf = 0;
 options_.bayesian_th_moments = 0;
 options_.diffuse_filter = 0;
@@ -392,6 +393,7 @@ oo_.exo_det_simul = [];
 
 M_.params = [];
 M_.endo_histval = [];
+M_.Correlation_matrix = [];
 
 % homotopy
 options_.homotopy_mode = 0;
@@ -434,13 +436,28 @@ options_.sylvester_fixed_point_tol = 1e-12;
 options_.lyapunov_fp = 0;
 % if 1 use a doubling algorithm to solve Lyapunov equation (for large scale models)
 options_.lyapunov_db = 0;
-% if 1 use a squre root solver to solve Lyapunov equation (for large scale models)
+% if 1 use a square root solver to solve Lyapunov equation (for large scale models)
 options_.lyapunov_srs = 0;
 
 % convergence criterion for iteratives methods to solve lyapunov equations
 options_.lyapunov_fixed_point_tol = 1e-10;
 options_.lyapunov_doubling_tol = 1e-16;
 
+% if equal to 1 use a cycle reduction method to compute the decision rule (for large scale models)
+options_.dr_cycle_reduction = 0;
+
+% convergence criterion for iteratives methods to solve the decision rule
+options_.dr_cycle_reduction_tol = 1e-7;
+
+% if equal to 1 use a logarithmic reduction method to compute the decision rule (for large scale models)
+options_.dr_logarithmic_reduction = 0;
+
+% convergence criterion for iteratives methods to solve the decision rule
+options_.dr_logarithmic_reduction_tol = 1e-12;
+
+% convergence criterion for iteratives methods to solve the decision rule
+options_.dr_logarithmic_reduction_maxiter = 100;
+
 % dates for historical time series
 options_.initial_date.freq = 1;
 options_.initial_date.period = 1;
@@ -504,10 +521,16 @@ options_.graph_save_formats.eps = 1;
 options_.graph_save_formats.pdf = 0;
 options_.graph_save_formats.fig = 0;
 
+% risky steady state
 options_.risky_steadystate = 0;
 
+% use GPU
+options_.gpu = 0;
+
 % initialize persistent variables in priordens()
 priordens([],[],[],[],[],[],1);
+% initialize persistent variables in dyn_first_order_solver()
+dyn_first_order_solver();
 
 % Set dynare random generator and seed.
 set_dynare_seed('default');
@@ -517,11 +540,7 @@ set_dynare_seed('default');
 [junk,junk]=mkdir([M_.fname '/Output']);
 
 % Load user configuration file.
-if isunix
-    origin = pwd;
-    cd('~/')
-    if exist('dynare_configuration.m')
-        dynare_configuration;
-    end
-    cd(origin)
-end
\ No newline at end of file
+if isfield(options_, 'global_init_file')
+    run(options_.global_init_file);
+end
+
diff --git a/matlab/graph_decomp.m b/matlab/graph_decomp.m
index 8a99bac9845a9e1b4881cddef234ed508698f446..948b351e50afd41e19972d6e68a15f71eef77b7b 100644
--- a/matlab/graph_decomp.m
+++ b/matlab/graph_decomp.m
@@ -1,7 +1,7 @@
 function []=graph_decomp(z,shock_names,endo_names,i_var,initial_date)
 %function []=graph_decomp(z,varlist,initial_period,freq)
 
-% Copyright (C) 2010 Dynare Team
+% Copyright (C) 2010-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/gsa/filt_mc_.m b/matlab/gsa/filt_mc_.m
index 2b0c5cca33e2ddfaf69519ed8cba80f2102510a2..2009299c38b29ee598a43fc14bbf37c611609d32 100644
--- a/matlab/gsa/filt_mc_.m
+++ b/matlab/gsa/filt_mc_.m
@@ -1,4 +1,4 @@
-function [rmse_MC, ixx] = filt_mc_(OutDir,data_info)
+function [rmse_MC, ixx] = filt_mc_(OutDir,options_gsa_)
 % function [rmse_MC, ixx] = filt_mc_(OutDir)
 % inputs (from opt_gsa structure)
 % vvarvecm = options_gsa_.var_rmse;
@@ -35,13 +35,14 @@ function [rmse_MC, ixx] = filt_mc_(OutDir,data_info)
 
 global bayestopt_ estim_params_ M_ options_ oo_
 
-options_gsa_=options_.opt_gsa;
+% options_gsa_=options_.opt_gsa;
 vvarvecm = options_gsa_.var_rmse;
 loadSA   = options_gsa_.load_rmse;
 pfilt    = options_gsa_.pfilt_rmse;
 alpha    = options_gsa_.alpha_rmse;
-alpha2   = options_gsa_.alpha2_rmse;
-pvalue   = options_gsa_.pvalue_corr;
+% alpha2   = options_gsa_.alpha2_rmse;
+alpha2 = 0;
+pvalue   = options_gsa_.alpha2_rmse;
 istart   = options_gsa_.istart_rmse;
 alphaPC  = 0.5;
 
@@ -112,12 +113,12 @@ else
 end
 if ~loadSA,
     if exist('xparam1','var')
-        set_all_parameters(xparam1);
+        M_ = set_all_parameters(xparam1,estim_params_,M_);
         steady_(M_,options_,oo_);
         ys_mode=oo_.steady_state;
     end
     if exist('xparam1_mean','var')
-        set_all_parameters(xparam1_mean);
+        M_ = set_all_parameters(xparam1_mean,estim_params_,M_);
         steady_(M_,options_,oo_);
         ys_mean=oo_.steady_state;
     end
@@ -210,9 +211,9 @@ if ~loadSA,
         save([OutDir,filesep,fnamtmp,'.mat'], 'x', 'logpo2', 'likelihood', 'rmse_MC', 'rmse_mode','rmse_pmean')
     else
         if options_.opt_gsa.lik_only
-            save([OutDir,filesep,fnamtmp, '.mat'], 'likelihood', '-append')
+            save([OutDir,filesep,fnamtmp, '.mat'], 'x', 'logpo2','likelihood', '-append')
         else
-            save([OutDir,filesep,fnamtmp, '.mat'], 'likelihood', 'rmse_MC','-append')
+            save([OutDir,filesep,fnamtmp, '.mat'], 'x', 'logpo2','likelihood', 'rmse_MC','-append')
             if exist('xparam1_mean','var')
                 save([OutDir,filesep,fnamtmp, '.mat'], 'rmse_pmean','-append')
             end
@@ -222,7 +223,7 @@ if ~loadSA,
         end
     end
 else
-    if options_.opt_gsa.lik_only & options_.opt_gsa.ppost==0
+    if options_.opt_gsa.lik_only && options_.opt_gsa.ppost==0
         load([OutDir,filesep,fnamtmp, '.mat'],'x','logpo2','likelihood');
     else
         load([OutDir,filesep,fnamtmp, '.mat'],'x','logpo2','likelihood','rmse_MC','rmse_mode','rmse_pmean');
@@ -238,21 +239,21 @@ if ~options_.opt_gsa.ppost
     [dum, ipost]=sort(-logpo2);
     [dum, ilik]=sort(-likelihood);
 end
-if ~options_.opt_gsa.ppost & options_.opt_gsa.lik_only
+if ~options_.opt_gsa.ppost && options_.opt_gsa.lik_only
     if options_.opt_gsa.pprior
         anam='rmse_prior_post';
     else
         anam='rmse_mc_post';
     end
     stab_map_1(x, ipost(1:nfilt), ipost(nfilt+1:end), anam, 1,[],OutDir);
-    stab_map_2(x(ipost(1:nfilt),:),alpha2,anam, OutDir);
+    stab_map_2(x(ipost(1:nfilt),:),alpha2,pvalue,anam, OutDir);
     if options_.opt_gsa.pprior
         anam='rmse_prior_lik';
     else
         anam='rmse_mc_lik';
     end
     stab_map_1(x, ilik(1:nfilt), ilik(nfilt+1:end), anam, 1,[],OutDir);
-    stab_map_2(x(ilik(1:nfilt),:),alpha2,anam, OutDir);
+    stab_map_2(x(ilik(1:nfilt),:),alpha2,pvalue,anam, OutDir);
 else
     for i=1:size(vvarvecm,1),
         [dum, ixx(:,i)]=sort(rmse_MC(:,i));
@@ -260,7 +261,7 @@ else
             %nfilt0(i)=length(find(rmse_MC(:,i)<rmse_pmean(i)));
             rmse_txt=rmse_pmean;
         else
-            if options_.opt_gsa.pprior | ~exist('rmse_pmean'),
+            if options_.opt_gsa.pprior || ~exist('rmse_pmean'),
                 if exist('rmse_mode'),
                     rmse_txt=rmse_mode;
                 else
@@ -285,6 +286,7 @@ else
             PP(j,i)=P;
         end
     end
+    if ~options_.nograph,
     ifig=0;
     for i=1:size(vvarvecm,1),
         if mod(i,9)==1,
@@ -298,7 +300,7 @@ else
         h=cumplot(lnprior(ixx(nfilt0(i)+1:end,i)));
         set(h,'color','green')
         title(vvarvecm(i,:),'interpreter','none')
-        if mod(i,9)==0 | i==size(vvarvecm,1)
+        if mod(i,9)==0 || i==size(vvarvecm,1)
             if options_.opt_gsa.ppost
                 dyn_saveas(hh,[OutDir '/' fname_ '_rmse_post_lnprior',int2str(ifig)],options_);
             else
@@ -329,7 +331,7 @@ else
         if options_.opt_gsa.ppost==0,
             set(gca,'xlim',[min( likelihood(ixx(1:nfilt0(i),i)) ) max( likelihood(ixx(1:nfilt0(i),i)) )])
         end
-        if mod(i,9)==0 | i==size(vvarvecm,1)
+        if mod(i,9)==0 || i==size(vvarvecm,1)
             if options_.opt_gsa.ppost
                 dyn_saveas(hh,[OutDir '/' fname_ '_rmse_post_lnlik',int2str(ifig) ],options_);
             else
@@ -360,7 +362,7 @@ else
         if options_.opt_gsa.ppost==0,
             set(gca,'xlim',[min( logpo2(ixx(1:nfilt0(i),i)) ) max( logpo2(ixx(1:nfilt0(i),i)) )])
         end
-        if mod(i,9)==0 | i==size(vvarvecm,1)
+        if mod(i,9)==0 || i==size(vvarvecm,1)
             if options_.opt_gsa.ppost
                 dyn_saveas(hh,[OutDir '/' fname_ '_rmse_post_lnpost',int2str(ifig) ],options_);
             else
@@ -375,6 +377,7 @@ else
             end
         end
     end
+    end
     
     param_names='';
     for j=1:npar+nshock,
@@ -402,7 +405,7 @@ else
     rmse_MC=rmse_MC(:,ivar);
     
     disp(' ')
-    % if options_.opt_gsa.ppost==0 & options_.opt_gsa.pprior,
+    % if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior,
     disp(['Sample filtered the ',num2str(pfilt*100),'% best RMSE''s for each observed series ...' ])
     % else
     %   disp(['Sample filtered the best RMSE''s smaller than RMSE at the posterior mean ...' ])
@@ -414,7 +417,7 @@ else
     disp(' ')
     disp(' ')
     disp('RMSE ranges after filtering:')
-    if options_.opt_gsa.ppost==0 & options_.opt_gsa.pprior,
+    if options_.opt_gsa.ppost==0 && options_.opt_gsa.pprior,
         disp(['             best ',num2str(pfilt*100),'% filtered             remaining 90%'])
         disp(['             min            max            min            max            posterior mode'])
     else
@@ -469,6 +472,7 @@ else
     pnam=bayestopt_.name;
     
     % plot trade-offs
+    if ~options_.nograph
     a00=jet(size(vvarvecm,1));
     for ix=1:ceil(length(nsnam)/5),
         hh = dyn_figure(options_);
@@ -478,13 +482,18 @@ else
             h0=cumplot(x(:,nsnam(j)));
             set(h0,'color',[0 0 0])
             hold on,
-            np=find(SP(nsnam(j),:));
+            npx=find(SP(nsnam(j),:)==0);
             %a0=jet(nsp(nsnam(j)));
-            a0=a00(np,:);
-            for i=1:nsp(nsnam(j)), %size(vvarvecm,1),
+%             a0=a00(np,:);
+            for i=1:size(vvarvecm,1),
                 %h0=cumplot(x(ixx(1:nfilt,np(i)),nsnam(j)+nshock));
-                h0=cumplot(x(ixx(1:nfilt0(np(i)),np(i)),nsnam(j)));
-                set(h0,'color',a0(i,:))
+%                 h0=cumplot(x(ixx(1:nfilt0(np(i)),np(i)),nsnam(j)));
+                if any(npx==i),
+                    h0=cumplot(x(ixx(1:nfilt0(i),i),nsnam(j))*NaN);
+                else
+                    h0=cumplot(x(ixx(1:nfilt0(i),i),nsnam(j)));
+            end
+                set(h0,'color',a00(i,:))
             end
             ydum=get(gca,'ylim');
             %xdum=xparam1(nshock+nsnam(j));
@@ -498,9 +507,9 @@ else
         end
         %subplot(3,2,6)
         if exist('OCTAVE_VERSION'),
-            legend(char('base',vvarvecm(np,:)),'location','eastoutside');
+            legend(char('base',vvarvecm),'location','eastoutside');
         else
-            h0=legend(char('base',vvarvecm(np,:)),0);
+            h0=legend(char('base',vvarvecm),0);
             set(h0,'fontsize',6,'position',[0.7 0.1 0.2 0.3],'interpreter','none');
         end
         %h0=legend({'base',vnam{np}}',0);
@@ -516,109 +525,12 @@ else
         end
     end
     close all
+    end
     
     for j=1:size(SP,2),
         nsx(j)=length(find(SP(:,j)));
     end
     
-    number_of_grid_points = 2^9;      % 2^9 = 512 !... Must be a power of two.
-    bandwidth = 0;                    % Rule of thumb optimal bandwidth parameter.
-    kernel_function = 'gaussian';     % Gaussian kernel for Fast Fourrier Transform approximaton.
-    %kernel_function = 'uniform';     % Gaussian kernel for Fast Fourrier Transform approximaton.
-    
-    for ix=1:ceil(length(nsnam)/5),
-        hh = dyn_figure(options_);
-        for j=1+5*(ix-1):min(size(snam2,1),5*ix),
-            subplot(2,3,j-5*(ix-1))
-            optimal_bandwidth = mh_optimal_bandwidth(x(:,nsnam(j)),size(x,1),bandwidth,kernel_function);
-            [x1,f1] = kernel_density_estimate(x(:,nsnam(j)),number_of_grid_points,...
-                size(x,1),optimal_bandwidth,kernel_function);
-            h0 = plot(x1, f1,'k');
-            hold on,
-            np=find(SP(nsnam(j),:));
-            %a0=jet(nsp(nsnam(j)));
-            a0=a00(np,:);
-            for i=1:nsp(nsnam(j)), %size(vvarvecm,1),
-                optimal_bandwidth = mh_optimal_bandwidth(x(ixx(1:nfilt0(np(i)),np(i)),nsnam(j)),nfilt,bandwidth,kernel_function);
-                [x1,f1] = kernel_density_estimate(x(ixx(1:nfilt0(np(i)),np(i)),nsnam(j)),number_of_grid_points,...
-                    nfilt, optimal_bandwidth,kernel_function);
-                h0 = plot(x1, f1);
-                set(h0,'color',a0(i,:))
-            end
-            ydum=get(gca,'ylim');
-            set(gca,'ylim',[0 ydum(2)]);
-            if exist('xparam1')
-                %xdum=xparam1(nshock+nsnam(j));
-                xdum=xparam1(nsnam(j));
-                h1=plot([xdum xdum],[0 ydum(2)]);
-                set(h1,'color',[0.85 0.85 0.85],'linewidth',2)
-            end
-            xlabel('')
-            title([pnam{nsnam(j)}],'interpreter','none')
-        end
-        if exist('OCTAVE_VERSION'),
-            legend(char('base',vvarvecm(np,:)),'location','eastoutside');
-        else
-            h0=legend(char('base',vvarvecm(np,:)),0);
-            set(h0,'fontsize',6,'position',[0.7 0.1 0.2 0.3],'interpreter','none')
-        end
-        %h0=legend({'base',vnam{np}}',0);
-        %set(findobj(get(h0,'children'),'type','text'),'interpreter','none')
-        if options_.opt_gsa.ppost
-            dyn_saveas(hh,[ OutDir '/' fname_ '_rmse_post_dens_' int2str(ix) ],options_);
-        else
-            if options_.opt_gsa.pprior
-                dyn_saveas(hh,[OutDir '/' fname_ '_rmse_prior_dens_' int2str(ix)],options_);
-            else
-                dyn_saveas(hh,[OutDir '/' fname_ '_rmse_mc_dens_' int2str(ix) ],options_);
-            end
-        end
-    end
-    close all
-    % for j=1:size(SP,2),
-    %     nfig=0;
-    %     np=find(SP(:,j));
-    %     for i=1:nsx(j), %size(vvarvecm,1),
-    %         if mod(i,12)==1,
-    %             nfig=nfig+1;
-    %             %figure('name',['Sensitivity of fit of ',vnam{j}]),
-    %             figure('name',['Sensitivity of fit of ',deblank(vvarvecm(j,:)),' ',num2str(nfig)]),
-    %         end
-    %
-    %         subplot(3,4,i-12*(nfig-1))
-    %         optimal_bandwidth = mh_optimal_bandwidth(x(ixx(1:nfilt,j),np(i)),nfilt,bandwidth,kernel_function);
-    %         [x1,f1] = kernel_density_estimate(x(ixx(1:nfilt,j),np(i)),number_of_grid_points,...
-    %             nfilt, optimal_bandwidth,kernel_function);
-    %         plot(x1, f1,':k','linewidth',2)
-    %         optimal_bandwidth = mh_optimal_bandwidth(x(ixx(nfilt+1:end,j),np(i)),nruns-nfilt,bandwidth,kernel_function);
-    %         [x1,f1] = kernel_density_estimate(x(ixx(nfilt+1:end,j),np(i)),number_of_grid_points,...
-    %             nruns-nfilt,optimal_bandwidth,kernel_function);
-    %         hold on, plot(x1, f1,'k','linewidth',2)
-    %         ydum=get(gca,'ylim');
-    %         %xdum=xparam1(nshock+np(i));
-    %         xdum=xparam1(np(i));
-    %         h1=plot([xdum xdum],ydum);
-    %         set(h1,'color',[0.85 0.85 0.85],'linewidth',2)
-    %         %xdum1=mean(x(ixx(1:nfilt,j),np(i)+nshock));
-    %         xdum1=mean(x(ixx(1:nfilt,j),np(i)));
-    %         h2=plot([xdum1 xdum1],ydum);
-    %         set(h2,'color',[0 1 0],'linewidth',2)
-    %         %         h0=cumplot(x(nfilt+1:end,np(i)+nshock));
-    %         %         set(h0,'color',[1 1 1])
-    %         %         hold on,
-    %         %         h0=cumplot(x(ixx(1:nfilt,j),np(i)+nshock));
-    %         %         set(h0,'linestyle',':','color',[1 1 1])
-    %         %title([pnam{np(i)}])
-    %         title([pnam{np(i)},'. K-S prob ', num2str(PP(np(i),j))],'interpreter','none')
-    %         xlabel('')
-    %         if mod(i,12)==0 | i==nsx(j),
-    %             saveas(gcf,[fname_,'_rmse_',deblank(vvarvecm(j,:)),'_',int2str(nfig)])
-    %             close(gcf)
-    %         end
-    %     end
-    % end
-    
-    
     disp(' ')
     disp(' ')
     disp('Sensitivity table (significance and direction):')
diff --git a/matlab/gsa/map_ident_.m b/matlab/gsa/map_ident_.m
index 9cc1db953c2038f0698caae7ff287617614152c0..452d091d7e8f67c508b72e0306d7792aae6aa2bd 100644
--- a/matlab/gsa/map_ident_.m
+++ b/matlab/gsa/map_ident_.m
@@ -1,4 +1,4 @@
-function map_ident_(OutputDirectoryName)
+function map_ident_(OutputDirectoryName,opt_gsa)
 
 % Copyright (C) 2012 Dynare Team
 %
@@ -19,7 +19,7 @@ function map_ident_(OutputDirectoryName)
 
 global bayestopt_ M_ options_ estim_params_ oo_
 
-opt_gsa = options_.opt_gsa;
+% opt_gsa = options_.opt_gsa;
 fname_ = M_.fname;
 nliv   = opt_gsa.morris_nliv;
 ntra   = opt_gsa.morris_ntra;
@@ -768,6 +768,8 @@ if opt_gsa.morris==1,
   %     eval(['print -dpdf ' OutputDirectoryName '/' fname_ '_morris_redform']);
 
 elseif opt_gsa.morris==3,
+    return
+    
   np=estim_params_.np;
   na=(4*np+1)*opt_gsa.Nsam;
   for j=1:j0,
diff --git a/matlab/gsa/read_data.m b/matlab/gsa/read_data.m
index a6f4054357121bb1529897ca6a2826c005f3371a..c5851c0be93cc56817777ea444a8ef6580b705ab 100644
--- a/matlab/gsa/read_data.m
+++ b/matlab/gsa/read_data.m
@@ -1,4 +1,4 @@
-function [gend, data] = read_data
+function [gend, data] = read_data()
 % Written by Marco Ratto
 % Joint Research Centre, The European Commission,
 % (http://eemc.jrc.ec.europa.eu/),
diff --git a/matlab/gsa/redform_map.m b/matlab/gsa/redform_map.m
index 2c49e940f2e0206e611f1fb6d358c4c2ca95ea53..ffeb7062a9daae89eaa8e4146548108ec945747e 100644
--- a/matlab/gsa/redform_map.m
+++ b/matlab/gsa/redform_map.m
@@ -1,4 +1,4 @@
-function redform_map(dirname)
+function redform_map(dirname,options_gsa_)
 %function redform_map(dirname)
 % inputs (from opt_gsa structure
 % anamendo    = options_gsa_.namendo;
@@ -14,7 +14,7 @@ function redform_map(dirname)
 % Written by Marco Ratto
 % Joint Research Centre, The European Commission,
 % (http://eemc.jrc.ec.europa.eu/),
-% marco.ratto@jrc.it 
+% marco.ratto@jrc.it
 %
 % Reference:
 % M. Ratto, Global Sensitivity Analysis for Macroeconomic models, MIMEO, 2006.
@@ -39,7 +39,7 @@ function redform_map(dirname)
 
 global M_ oo_ estim_params_ options_ bayestopt_
 
-options_gsa_ = options_.opt_gsa;
+% options_gsa_ = options_.opt_gsa;
 
 anamendo = options_gsa_.namendo;
 anamlagendo = options_gsa_.namlagendo;
@@ -48,310 +48,387 @@ iload = options_gsa_.load_redform;
 pprior = options_gsa_.pprior;
 ilog = options_gsa_.logtrans_redform;
 threshold = options_gsa_.threshold_redform;
-ksstat = options_gsa_.ksstat_redform;
+% ksstat = options_gsa_.ksstat_redform;
 alpha2 = options_gsa_.alpha2_redform;
+alpha2=0;
+pvalue_ks = options_gsa_.ksstat_redform;
+pvalue_corr = options_gsa_.alpha2_redform;
 
 pnames = M_.param_names(estim_params_.param_vals(:,1),:);
 if nargin==0,
-  dirname='';
+    dirname='';
 end
 
 if pprior
-  load([dirname,'/',M_.fname,'_prior']);
-  adir=[dirname '/redform_stab'];
+    load([dirname,'/',M_.fname,'_prior'],'lpmat', 'lpmat0', 'istable','T');
+    adir=[dirname '/redform_stab'];
 else
-  load([dirname,'/',M_.fname,'_mc']);
-  adir=[dirname '/redform_mc'];
+    load([dirname,'/',M_.fname,'_mc'],'lpmat', 'lpmat0', 'istable','T');
+    adir=[dirname '/redform_mc'];
 end
 if ~exist('T')
-  stab_map_(dirname);
-if pprior
-  load([dirname,'/',M_.fname,'_prior'],'T');
-else
-  load([dirname,'/',M_.fname,'_mc'],'T');
-end
+    stab_map_(dirname,options_gsa_);
+    if pprior
+        load([dirname,'/',M_.fname,'_prior'],'T');
+    else
+        load([dirname,'/',M_.fname,'_mc'],'T');
+    end
 end
 if isempty(dir(adir))
-  mkdir(adir)
+    mkdir(adir)
 end
 adir0=pwd;
 %cd(adir)
 
 nspred=size(T,2)-M_.exo_nbr;
 x0=lpmat(istable,:);
+xx0=lpmat0(istable,:);
 [kn, np]=size(x0);
 offset = length(bayestopt_.pshape)-np;
 if options_gsa_.prior_range,
-  pshape=5*(ones(np,1));
-  pd =  [NaN(np,1) NaN(np,1) bayestopt_.lb(offset+1:end) bayestopt_.ub(offset+1:end)];
+    pshape=5*(ones(np,1));
+    pd =  [NaN(np,1) NaN(np,1) bayestopt_.lb(offset+1:end) bayestopt_.ub(offset+1:end)];
 else
-  pshape = bayestopt_.pshape(offset+1:end);
-  pd =  [bayestopt_.p6(offset+1:end) bayestopt_.p7(offset+1:end) bayestopt_.p3(offset+1:end) bayestopt_.p4(offset+1:end)];
+    pshape = bayestopt_.pshape(offset+1:end);
+    pd =  [bayestopt_.p6(offset+1:end) bayestopt_.p7(offset+1:end) bayestopt_.p3(offset+1:end) bayestopt_.p4(offset+1:end)];
 end
 
 nsok = length(find(M_.lead_lag_incidence(M_.maximum_lag,:)));
-clear lpmat lpmat0 egg iunstable yys
+clear lpmat lpmat0
 js=0;
 for j=1:size(anamendo,1)
-  namendo=deblank(anamendo(j,:));
-  iendo=strmatch(namendo,M_.endo_names(oo_.dr.order_var,:),'exact');
-  ifig=0;
-  iplo=0;
-  for jx=1:size(anamexo,1)
-    namexo=deblank(anamexo(jx,:));
-    iexo=strmatch(namexo,M_.exo_names,'exact');
+    namendo=deblank(anamendo(j,:));
+    iendo=strmatch(namendo,M_.endo_names(oo_.dr.order_var,:),'exact');
+    ifig=0;
+    iplo=0;
+    for jx=1:size(anamexo,1)
+        namexo=deblank(anamexo(jx,:));
+        iexo=strmatch(namexo,M_.exo_names,'exact');
+        disp(' ')
+        disp(['[', namendo,' vs. ',namexo,']'])
 
-    if ~isempty(iexo),
-      %y0=squeeze(T(iendo,iexo+nspred,istable));
-      y0=squeeze(T(iendo,iexo+nspred,:));
-      if (max(y0)-min(y0))>1.e-10,
-        if mod(iplo,9)==0,
-          ifig=ifig+1;
-          hfig = dyn_figure(options_,'name',[namendo,' vs. shocks ',int2str(ifig)]);
-          iplo=0;
-        end
-        iplo=iplo+1;
-        js=js+1;
-        xdir0 = [adir,'/',namendo,'_vs_', namexo];
-        if ilog==0,
-          if isempty(threshold)
-            si(:,js) = redform_private(x0, y0, pshape, pd, iload, pnames, namendo, namexo, xdir0);
-          else
-            iy=find( (y0>threshold(1)) & (y0<threshold(2)));
-            iyc=find( (y0<=threshold(1)) | (y0>=threshold(2)));
-            xdir = [xdir0,'_cut'];
-            if ~isempty(iy),
-              si(:,js) = redform_private(x0(iy,:), y0(iy), pshape, pd, iload, pnames, namendo, namexo, xdir);
-            end
-            if ~isempty(iy) & ~isempty(iyc)
-            delete([xdir, '/*cut*.*'])
-            [proba, dproba] = stab_map_1(x0, iy, iyc, 'cut',0);
-            indsmirnov = find(dproba>ksstat);
-            stab_map_1(x0, iy, iyc, 'cut',1,indsmirnov,xdir);
-            stab_map_2(x0(iy,:),alpha2,'cut',xdir)
-            stab_map_2(x0(iyc,:),alpha2,'trim',xdir)
+        
+        if ~isempty(iexo),
+            %y0=squeeze(T(iendo,iexo+nspred,istable));
+            y0=squeeze(T(iendo,iexo+nspred,:));
+            if (max(y0)-min(y0))>1.e-10,
+                if mod(iplo,9)==0 && isempty(threshold) && ~options_.nograph,
+                    ifig=ifig+1;
+                    hfig = dyn_figure(options_,'name',[namendo,' vs. shocks ',int2str(ifig)]);
+                    iplo=0;
+                end
+                iplo=iplo+1;
+                js=js+1;
+                xdir0 = [adir,'/',namendo,'_vs_', namexo];
+                if ilog==0,
+                    if isempty(threshold)
+                        if isempty(dir(xdir0))
+                            mkdir(xdir0)
+                        end
+                        si(:,js) = redform_private(x0, y0, pshape, pd, iload, pnames, namendo, namexo, xdir0, options_gsa_);
+                    else
+                        iy=find( (y0>threshold(1)) & (y0<threshold(2)));
+                        iyc=find( (y0<=threshold(1)) | (y0>=threshold(2)));
+                        xdir = [xdir0,'_cut'];
+                        if isempty(dir(xdir))
+                            mkdir(xdir)
+                        end
+                        if ~options_.nograph,
+                            hf=dyn_figure(options_); hist(y0,30), title([namendo,' vs. ', namexo])
+                            dyn_saveas(hf,[xdir,'/', namendo,'_vs_', namexo],options_);
+                            if ~options_.nodisplay
+                                close(hf);
+                            end
+                        end
+                        %             if ~isempty(iy),
+                        %               si(:,js) = redform_private(x0(iy,:), y0(iy), pshape, pd, iload, pnames, namendo, namexo, xdir, options_gsa_);
+                        %             else
+                        si(:,js) = NaN(np,1);
+                        %             end
+                        if ~isempty(iy) && ~isempty(iyc)
+                            delete([xdir, '/*cut*.*'])
+                            [proba, dproba] = stab_map_1(x0, iy, iyc, 'cut',0);
+                            %             indsmirnov = find(dproba>ksstat);
+                            indsmirnov = find(proba<pvalue_ks);
+                            for jp=1:length(indsmirnov),
+                                disp([M_.param_names(estim_params_.param_vals(indsmirnov(jp),1),:),'   d-stat = ', num2str(dproba(indsmirnov(jp)),'%1.3f'),'   p-value = ', num2str(proba(indsmirnov(jp)),'%1.3f')])
+                            end
+                            disp(' ');
+                            stab_map_1(x0, iy, iyc, 'cut',1,indsmirnov,xdir);
+                            stab_map_2(x0(iy,:),alpha2,pvalue_corr,'cut',xdir)
+                            stab_map_2(x0(iyc,:),alpha2,pvalue_corr,'trim',xdir)
+                            lpmat=x0(iy,:);
+                            lpmat0=xx0(iy,:);
+                            istable=[1:length(iy)];
+                            save([xdir,filesep,'threshold.mat'],'lpmat','lpmat0','istable')
+                            clear lpmat lpmat0 istable
+                        end
+                    end
+                else
+                    [yy, xdir] = log_trans_(y0,xdir0);
+                    if isempty(dir(xdir))
+                        mkdir(xdir)
+                    end
+                    silog(:,js) = redform_private(x0, yy, pshape, pd, iload, pnames, namendo, namexo, xdir, options_gsa_);
+                end
+                
+                if isempty(threshold) && ~options_.nograph,
+                    figure(hfig)
+                    subplot(3,3,iplo),
+                    if ilog,
+                        [saso, iso] = sort(-silog(:,js));
+                        bar([silog(iso(1:min(np,10)),js)])
+                        logflag='log';
+                    else
+                        [saso, iso] = sort(-si(:,js));
+                        bar(si(iso(1:min(np,10)),js))
+                        logflag='';
+                    end
+                    %set(gca,'xticklabel',pnames(iso(1:min(np,10)),:),'fontsize',8)
+                    set(gca,'xticklabel',' ','fontsize',10)
+                    set(gca,'xlim',[0.5 10.5])
+                    for ip=1:min(np,10),
+                        text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+                    end
+                    title([logflag,' ',namendo,' vs. ',namexo],'interpreter','none')
+                    if iplo==9,
+                        dyn_saveas(hfig,[dirname,'/',M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],options_);
+                        if ~options_.nodisplay
+                            close(hfig);
+                        end
+                    end
+                end
+                
             end
-          end
-        else
-          [yy, xdir] = log_trans_(y0,xdir0);
-          silog(:,js) = redform_private(x0, yy, pshape, pd, iload, pnames, namendo, namexo, xdir);
         end
-
-        figure(hfig)
-        subplot(3,3,iplo),
-        if ilog,
-          [saso, iso] = sort(-silog(:,js));
-          bar([silog(iso(1:min(np,10)),js)])
-          logflag='log';
-        else
-          [saso, iso] = sort(-si(:,js));
-          bar(si(iso(1:min(np,10)),js))
-          logflag='';
-        end
-        %set(gca,'xticklabel',pnames(iso(1:min(np,10)),:),'fontsize',8)
-        set(gca,'xticklabel',' ','fontsize',10)
-        set(gca,'xlim',[0.5 10.5])
-        for ip=1:min(np,10),
-          text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-        end
-        title([logflag,' ',namendo,' vs. ',namexo],'interpreter','none')
-        if iplo==9,
-          dyn_saveas(hfig,[dirname,'/',M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],options_);  
-          if ~options_.nodisplay
+    end
+    if iplo<9 && iplo>0 && ifig && ~options_.nograph,
+        dyn_saveas(hfig,[dirname,'/',M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],options_);
+        if ~options_.nodisplay
             close(hfig);
-          end
         end
-      
-      end
     end
-  end
-  if iplo<9 & iplo>0 & ifig,
-    dyn_saveas(hfig,[dirname,'/',M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],options_);
-    if ~options_.nodisplay
-        close(hfig);
-    end
-  end
-  ifig=0;
-  iplo=0;
-  for je=1:size(anamlagendo,1)
-    namlagendo=deblank(anamlagendo(je,:));
-    ilagendo=strmatch(namlagendo,M_.endo_names(oo_.dr.order_var(oo_.dr.nstatic+1:oo_.dr.nstatic+nsok),:),'exact');
-
-    if ~isempty(ilagendo),
-      %y0=squeeze(T(iendo,ilagendo,istable));
-      y0=squeeze(T(iendo,ilagendo,:));
-      if (max(y0)-min(y0))>1.e-10,
-        if mod(iplo,9)==0,
-          ifig=ifig+1;
-          hfig = dyn_figure(options_,'name',[namendo,' vs. lags ',int2str(ifig)]);
-          iplo=0;
-        end
-        iplo=iplo+1;
-        js=js+1;
-        xdir0 = [adir,'/',namendo,'_vs_', namlagendo];
-        if ilog==0,
-        if isempty(threshold)
-          si(:,js) = redform_private(x0, y0, pshape, pd, iload, pnames, namendo, namlagendo, xdir0);
-        else
-          iy=find( (y0>threshold(1)) & (y0<threshold(2)));
-          iyc=find( (y0<=threshold(1)) | (y0>=threshold(2)));
-          xdir = [xdir0,'_cut'];
-          if ~isempty(iy)
-          si(:,js) = redform_private(x0(iy,:), y0(iy), pshape, pd, iload, pnames, namendo, namlagendo, xdir);
-          end
-          if ~isempty(iy) & ~isempty(iyc),
-          delete([xdir, '/*cut*.*'])
-          [proba, dproba] = stab_map_1(x0, iy, iyc, 'cut',0);
-          indsmirnov = find(dproba>ksstat);
-          stab_map_1(x0, iy, iyc, 'cut',1,indsmirnov,xdir);
-          stab_map_2(x0(iy,:),alpha2,'cut',xdir)
-          stab_map_2(x0(iyc,:),alpha2,'trim',xdir)
-          end
-        end
-        else
-          [yy, xdir] = log_trans_(y0,xdir0);
-          silog(:,js) = redform_private(x0, yy, pshape, pd, iload, pnames, namendo, namlagendo, xdir);
-        end
-
-        figure(hfig),
-        subplot(3,3,iplo),
-        if ilog,
-          [saso, iso] = sort(-silog(:,js));
-          bar([silog(iso(1:min(np,10)),js)])
-          logflag='log';
-        else
-          [saso, iso] = sort(-si(:,js));
-          bar(si(iso(1:min(np,10)),js))
-          logflag='';
-        end
-        %set(gca,'xticklabel',pnames(iso(1:min(np,10)),:),'fontsize',8)
-        set(gca,'xticklabel',' ','fontsize',10)
-        set(gca,'xlim',[0.5 10.5])
-        for ip=1:min(np,10),
-          text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
-        end
-        title([logflag,' ',namendo,' vs. ',namlagendo,'(-1)'],'interpreter','none')
-        if iplo==9,
-          dyn_saveas(hfig,[dirname,'/',M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],options_);  
-            if ~options_.nodisplay
-                close(hfig);
+    ifig=0;
+    iplo=0;
+    for je=1:size(anamlagendo,1)
+        namlagendo=deblank(anamlagendo(je,:));
+        ilagendo=strmatch(namlagendo,M_.endo_names(oo_.dr.order_var(oo_.dr.nstatic+1:oo_.dr.nstatic+nsok),:),'exact');
+        disp(' ')
+        disp(['[', namendo,' vs. lagged ',namlagendo,']'])
+        
+        if ~isempty(ilagendo),
+            %y0=squeeze(T(iendo,ilagendo,istable));
+            y0=squeeze(T(iendo,ilagendo,:));
+            if (max(y0)-min(y0))>1.e-10,
+                if mod(iplo,9)==0 && isempty(threshold) && ~options_.nograph,
+                    ifig=ifig+1;
+                    hfig = dyn_figure(options_,'name',[namendo,' vs. lags ',int2str(ifig)]);
+                    iplo=0;
+                end
+                iplo=iplo+1;
+                js=js+1;
+                xdir0 = [adir,'/',namendo,'_vs_', namlagendo];
+                if ilog==0,
+                    if isempty(threshold)
+                        if isempty(dir(xdir0))
+                            mkdir(xdir0)
+                        end
+                        si(:,js) = redform_private(x0, y0, pshape, pd, iload, pnames, namendo, namlagendo, xdir0, options_gsa_);
+                    else
+                        iy=find( (y0>threshold(1)) & (y0<threshold(2)));
+                        iyc=find( (y0<=threshold(1)) | (y0>=threshold(2)));
+                        xdir = [xdir0,'_cut'];
+                        if isempty(dir(xdir))
+                            mkdir(xdir)
+                        end
+                        %           if ~isempty(iy)
+                        %           si(:,js) = redform_private(x0(iy,:), y0(iy), pshape, pd, iload, pnames, namendo, namlagendo, xdir, options_gsa_);
+                        %           end
+                        if ~options_.nograph,
+                            hf=dyn_figure(options_); hist(y0,30), title([namendo,' vs. ', namlagendo])
+                            dyn_saveas(hf,[xdir,'/', namendo,'_vs_', namlagendo],options_);
+                            if ~options_.nodisplay
+                                close(hf);
+                            end
+                        end
+                        if ~isempty(iy) && ~isempty(iyc),
+                            delete([xdir, '/*cut*.*'])
+                            [proba, dproba] = stab_map_1(x0, iy, iyc, 'cut',0);
+                            %           indsmirnov = find(dproba>ksstat);
+                            indsmirnov = find(proba<pvalue_ks);
+                            for jp=1:length(indsmirnov),
+                                disp([M_.param_names(estim_params_.param_vals(indsmirnov(jp),1),:),'   d-stat = ', num2str(dproba(indsmirnov(jp)),'%1.3f'),'   p-value = ', num2str(proba(indsmirnov(jp)),'%1.3f')])
+                            end
+                            disp(' ');
+                            stab_map_1(x0, iy, iyc, 'cut',1,indsmirnov,xdir);
+                            stab_map_2(x0(iy,:),alpha2,pvalue_corr,'cut',xdir)
+                            stab_map_2(x0(iyc,:),alpha2,pvalue_corr,'trim',xdir)
+                            lpmat=x0(iy,:);
+                            lpmat0=xx0(iy,:);
+                            istable=[1:length(iy)];
+                            save([xdir,filesep,'threshold.mat'],'lpmat','lpmat0','istable')
+                            clear lpmat lpmat0 istable
+                            
+                        end
+                    end
+                else
+                    [yy, xdir] = log_trans_(y0,xdir0);
+                    if isempty(dir(xdir))
+                        mkdir(xdir)
+                    end
+                    silog(:,js) = redform_private(x0, yy, pshape, pd, iload, pnames, namendo, namlagendo, xdir, options_gsa_);
+                end
+                
+                if isempty(threshold) && ~options_.nograph
+                    figure(hfig),
+                    subplot(3,3,iplo),
+                    if ilog,
+                        [saso, iso] = sort(-silog(:,js));
+                        bar([silog(iso(1:min(np,10)),js)])
+                        logflag='log';
+                    else
+                        [saso, iso] = sort(-si(:,js));
+                        bar(si(iso(1:min(np,10)),js))
+                        logflag='';
+                    end
+                    %set(gca,'xticklabel',pnames(iso(1:min(np,10)),:),'fontsize',8)
+                    set(gca,'xticklabel',' ','fontsize',10)
+                    set(gca,'xlim',[0.5 10.5])
+                    for ip=1:min(np,10),
+                        text(ip,-0.02,deblank(pnames(iso(ip),:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+                    end
+                    title([logflag,' ',namendo,' vs. ',namlagendo,'(-1)'],'interpreter','none')
+                    if iplo==9,
+                        dyn_saveas(hfig,[dirname,'/',M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],options_);
+                        if ~options_.nodisplay
+                            close(hfig);
+                        end
+                    end
+                end
+                
             end
         end
-      
-      end
     end
-  end
-  if iplo<9 & iplo>0 & ifig,
-    dyn_saveas(hfig,[dirname,'/',M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],options_);  
-    if ~options_.nodisplay
-      close(hfig);
+    if iplo<9 && iplo>0 && ifig && ~options_.nograph,
+        dyn_saveas(hfig,[dirname,'/',M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],options_);
+        if ~options_.nodisplay
+            close(hfig);
+        end
     end
-  end
-end
-
-if ilog==0,
-hfig=dyn_figure(options_); %bar(si)
-% boxplot(si','whis',10,'symbol','r.')
-myboxplot(si',[],'.',[],10)
-xlabel(' ')
-set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-set(gca,'xlim',[0.5 np+0.5])
-set(gca,'ylim',[0 1])
-set(gca,'position',[0.13 0.2 0.775 0.7])
-for ip=1:np,
-  text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
 end
-title('Reduced form GSA')
-dyn_saveas(hfig,[dirname,'/',M_.fname,'_redform_gsa'],options_);
 
-else
-hfig=dyn_figure(options_); %bar(silog)
-% boxplot(silog','whis',10,'symbol','r.')
-myboxplot(silog',[],'.',[],10)
-set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
-xlabel(' ')
-set(gca,'xlim',[0.5 np+0.5])
-set(gca,'ylim',[0 1])
-set(gca,'position',[0.13 0.2 0.775 0.7])
-for ip=1:np,
-  text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+if isempty(threshold) && ~options_.nograph,
+    if ilog==0,
+        hfig=dyn_figure(options_); %bar(si)
+        % boxplot(si','whis',10,'symbol','r.')
+        myboxplot(si',[],'.',[],10)
+        xlabel(' ')
+        set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+        set(gca,'xlim',[0.5 np+0.5])
+        set(gca,'ylim',[0 1])
+        set(gca,'position',[0.13 0.2 0.775 0.7])
+        for ip=1:np,
+            text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+        end
+        title('Reduced form GSA')
+        dyn_saveas(hfig,[dirname,'/',M_.fname,'_redform_gsa'],options_);
+        
+    else
+        hfig=dyn_figure(options_); %bar(silog)
+        % boxplot(silog','whis',10,'symbol','r.')
+        myboxplot(silog',[],'.',[],10)
+        set(gca,'xticklabel',' ','fontsize',10,'xtick',[1:np])
+        xlabel(' ')
+        set(gca,'xlim',[0.5 np+0.5])
+        set(gca,'ylim',[0 1])
+        set(gca,'position',[0.13 0.2 0.775 0.7])
+        for ip=1:np,
+            text(ip,-0.02,deblank(pnames(ip,:)),'rotation',90,'HorizontalAlignment','right','interpreter','none')
+        end
+        title('Reduced form GSA - Log-transformed elements')
+        dyn_saveas(hfig,[dirname,'/',M_.fname,'_redform_gsa_log'],options_);
+        
+    end
 end
-title('Reduced form GSA - Log-transformed elements')
-dyn_saveas(hfig,[dirname,'/',M_.fname,'_redform_gsa_log'],options_);
 
-end
-function si  = redform_private(x0, y0, pshape, pd, iload, pnames, namy, namx, xdir)
+function si  = redform_private(x0, y0, pshape, pd, iload, pnames, namy, namx, xdir, opt_gsa)
 global bayestopt_ options_
 
-opt_gsa=options_.opt_gsa;
+% opt_gsa=options_.opt_gsa;
 np=size(x0,2);
 x00=x0;
-  if opt_gsa.prior_range,
+if opt_gsa.prior_range,
     for j=1:np,
-      x0(:,j)=(x0(:,j)-pd(j,3))./(pd(j,4)-pd(j,3));
+        x0(:,j)=(x0(:,j)-pd(j,3))./(pd(j,4)-pd(j,3));
     end
-  else
+else
     x0=priorcdf(x0,pshape, pd(:,1), pd(:,2), pd(:,3), pd(:,4));
-  end
+end
 
 fname=[xdir,'/map'];
 if iload==0,
-  hfig=dyn_figure(options_); hist(y0,30), title([namy,' vs. ', namx])
-  if isempty(dir(xdir))
-    mkdir(xdir)
-  end
-  dyn_saveas(hfig,[xdir,'/', namy,'_vs_', namx],options_);
-  if ~options_.nodisplay
-    close(hfig);
-  end
-%   gsa_ = gsa_sdp_dyn(y0, x0, -2, [],[],[],1,fname, pnames);
-  nrun=length(y0);
-  nest=min(250,nrun);
-  nfit=min(1000,nrun);
-%   dotheplots = (nfit<=nest);
-  gsa_ = gsa_sdp(y0(1:nest), x0(1:nest,:), 2, [],[-1 -1 -1 -1 -1 0],[],0,[fname,'_est'], pnames);
-  if nfit>nest,
-    gsa_ = gsa_sdp(y0(1:nfit), x0(1:nfit,:), -2, gsa_.nvr*nest^3/nfit^3,[-1 -1 -1 -1 -1 0],[],0,fname, pnames);
-  end
-  save([fname,'.mat'],'gsa_')
-  [sidum, iii]=sort(-gsa_.si);
-  gsa_.x0=x00(1:nfit,:);
-  hfig=gsa_sdp_plot(gsa_,fname,pnames,iii(1:min(12,np)));
-  close(hfig);
-  gsa_.x0=x0(1:nfit,:);
-  if ~options_.nodisplay
-    close(hfig);
-  end
-%   copyfile([fname,'_est.mat'],[fname,'.mat'])
-  hfig=dyn_figure(options_); 
-  plot(y0(1:nfit),[gsa_.fit y0(1:nfit)],'.'), 
-  title([namy,' vs. ', namx,' fit'])
-  dyn_saveas(hfig,[xdir,'/', namy,'_vs_', namx,'_fit'],options_);
-  if ~options_.nodisplay
-   close(hfig);
-  end
-  if nfit<nrun,
-    npred=[nfit+1:nrun];
-  yf = ss_anova_fcast(x0(npred,:), gsa_);
-  hfig=dyn_figure(options_); 
-  plot(y0(npred),[yf y0(npred)],'.'), 
-  title([namy,' vs. ', namx,' pred'])
-  dyn_saveas(hfig,[xdir,'/', namy,'_vs_', namx,'_pred'],options_);
-  if ~options_.nodisplay
-    close(hfig);
-  end
-  end
+    if isempty(dir(xdir))
+        mkdir(xdir)
+    end
+    if ~options_.nograph,
+        hfig=dyn_figure(options_); hist(y0,30), title([namy,' vs. ', namx])
+        dyn_saveas(hfig,[xdir,'/', namy,'_vs_', namx],options_);
+        if ~options_.nodisplay
+            close(hfig);
+        end
+    end
+    %   gsa_ = gsa_sdp_dyn(y0, x0, -2, [],[],[],1,fname, pnames);
+    nrun=length(y0);
+    nest=min(250,nrun);
+    nfit=min(1000,nrun);
+    %   dotheplots = (nfit<=nest);
+    gsa_ = gsa_sdp(y0(1:nest), x0(1:nest,:), 2, [],[-1 -1 -1 -1 -1 0],[],0,[fname,'_est'], pnames);
+    if nfit>nest,
+        gsa_ = gsa_sdp(y0(1:nfit), x0(1:nfit,:), -2, gsa_.nvr*nest^3/nfit^3,[-1 -1 -1 -1 -1 0],[],0,fname, pnames);
+    end
+    save([fname,'.mat'],'gsa_')
+    [sidum, iii]=sort(-gsa_.si);
+    gsa_.x0=x00(1:nfit,:);
+    if ~options_.nograph,
+        hfig=gsa_sdp_plot(gsa_,fname,pnames,iii(1:min(12,np)));
+        close(hfig);
+    end
+    gsa_.x0=x0(1:nfit,:);
+    %   copyfile([fname,'_est.mat'],[fname,'.mat'])
+    if ~options_.nograph,
+        hfig=dyn_figure(options_);
+        plot(y0(1:nfit),[gsa_.fit y0(1:nfit)],'.'),
+        title([namy,' vs. ', namx,' fit'])
+        dyn_saveas(hfig,[xdir,'/', namy,'_vs_', namx,'_fit'],options_);
+        if ~options_.nodisplay
+            close(hfig);
+        end
+        if nfit<nrun,
+            npred=[nfit+1:nrun];
+            yf = ss_anova_fcast(x0(npred,:), gsa_);
+            hfig=dyn_figure(options_);
+            plot(y0(npred),[yf y0(npred)],'.'),
+            title([namy,' vs. ', namx,' pred'])
+            dyn_saveas(hfig,[xdir,'/', namy,'_vs_', namx,'_pred'],options_);
+            if ~options_.nodisplay
+                close(hfig);
+            end
+        end
+        
+    end
 else
-%   gsa_ = gsa_sdp_dyn(y0, x0, 0, [],[],[],0,fname, pnames);
-  gsa_ = gsa_sdp(y0, x0, 0, [],[],[],0,fname, pnames);
-  yf = ss_anova_fcast(x0, gsa_);
-  hfig=dyn_figure(options_); 
-  plot(y0,[yf y0],'.'), 
-  title([namy,' vs. ', namx,' pred'])
-  dyn_saveas(hfig,[xdir,'/', namy,'_vs_', namx,'_pred'],options_);  
-  if ~options_.nodisplay
-    close(hfig);
-  end
+    %   gsa_ = gsa_sdp_dyn(y0, x0, 0, [],[],[],0,fname, pnames);
+    gsa_ = gsa_sdp(y0, x0, 0, [],[],[],0,fname, pnames);
+    if ~options_.nograph,
+        yf = ss_anova_fcast(x0, gsa_);
+        hfig=dyn_figure(options_);
+        plot(y0,[yf y0],'.'),
+        title([namy,' vs. ', namx,' pred'])
+        dyn_saveas(hfig,[xdir,'/', namy,'_vs_', namx,'_pred'],options_);
+        if ~options_.nodisplay
+            close(hfig);
+        end
+    end
 end
 % si = gsa_.multivariate.si;
 si = gsa_.si;
diff --git a/matlab/gsa/redform_screen.m b/matlab/gsa/redform_screen.m
index 5be8a871eb70bc97140364f03c413c5bbe3dec45..d907c244408b39c4ef79f861c9588f4a151a30d4 100644
--- a/matlab/gsa/redform_screen.m
+++ b/matlab/gsa/redform_screen.m
@@ -1,5 +1,5 @@
-function redform_screen(dirname)
-%function redform_map(dirname)
+function redform_screen(dirname, options_gsa_)
+%function redform_map(dirname, options_gsa_)
 % inputs (from opt_gsa structure
 % anamendo    = options_gsa_.namendo;
 % anamlagendo = options_gsa_.namlagendo;
@@ -33,7 +33,7 @@ function redform_screen(dirname)
 
 global M_ oo_ estim_params_ options_ bayestopt_
 
-options_gsa_ = options_.opt_gsa;
+% options_gsa_ = options_.opt_gsa;
 
 anamendo = options_gsa_.namendo;
 anamlagendo = options_gsa_.namlagendo;
@@ -99,7 +99,7 @@ for j=1:size(anamendo,1),
       end
     end
   end
-  if iplo<9 & iplo>0 & ifig,
+  if iplo<9 && iplo>0 && ifig,
     dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_shocks_',num2str(ifig)],options_);
     if ~options_.nodisplay
       close(hh);
@@ -117,7 +117,7 @@ for j=1:size(anamendo,1),
       if ~isempty(y0),
         if mod(iplo,9)==0,
           ifig=ifig+1;
-          figure('name',[namendo,' vs. lagged endogenous ',int2str(ifig)]),
+          hh=dyn_figure(options_,'name',[namendo,' vs. lagged endogenous ',int2str(ifig)]);
           iplo=0;
         end
         iplo=iplo+1;
@@ -145,7 +145,7 @@ for j=1:size(anamendo,1),
       end
     end
   end
-  if iplo<9 & iplo>0 & ifig,
+  if iplo<9 && iplo>0 && ifig,
     dyn_saveas(hh,[dirname,'/',M_.fname,'_', namendo,'_vs_lags_',num2str(ifig)],options_);      
   end
 end
diff --git a/matlab/gsa/stab_map_.m b/matlab/gsa/stab_map_.m
index 70afc9bc1243569c0431bd1acb85f9ab104be7cf..18bb437554aeb1313eaa8b1e4d62ee22f5c0f965 100644
--- a/matlab/gsa/stab_map_.m
+++ b/matlab/gsa/stab_map_.m
@@ -1,4 +1,4 @@
-function x0 = stab_map_(OutputDirectoryName)
+function x0 = stab_map_(OutputDirectoryName,opt_gsa)
 %
 % function x0 = stab_map_(OutputDirectoryName)
 %
@@ -58,7 +58,7 @@ function x0 = stab_map_(OutputDirectoryName)
 %global bayestopt_ estim_params_ dr_ options_ ys_ fname_
 global bayestopt_ estim_params_ options_ oo_ M_
 
-opt_gsa=options_.opt_gsa;
+% opt_gsa=options_.opt_gsa;
 
 Nsam   = opt_gsa.Nsam;
 fload  = opt_gsa.load_stab;
@@ -122,13 +122,13 @@ if fload==0,
         Nsam=size(lpmat,1);
         lpmat0 = lpmat(:,1:nshock);
         lpmat = lpmat(:,nshock+1:end);
-    elseif opt_gsa.morris==3,
-        lpmat = prep_ide(Nsam,np,5);
-        Nsam=size(lpmat,1);
+%     elseif opt_gsa.morris==3,
+%         lpmat = prep_ide(Nsam,np,5);
+%         Nsam=size(lpmat,1);
     else
-        if np<52 & ilptau>0,
-            [lpmat] = qmc_sequence(np, int64(0), 0, Nsam)';
-            if np>30 | ilptau==2, % scrambled lptau
+        if np<52 && ilptau>0,
+            [lpmat] = qmc_sequence(np, int64(1), 0, Nsam)';
+            if np>30 || ilptau==2, % scrambled lptau
                 for j=1:np,
                     lpmat(:,j)=lpmat(randperm(Nsam),j);
                 end
@@ -302,7 +302,7 @@ if fload==0,
                     if any(isnan(egg(1:nspred,j)))
                         iwrong(j)=j;
                     else
-                        if (nboth | nfwrd) & abs(egg(nspred+1,j))<=options_.qz_criterium,
+                        if (nboth || nfwrd) && abs(egg(nspred+1,j))<=options_.qz_criterium,
                             iindeterm(j)=j;
                         end
                     end
@@ -402,7 +402,7 @@ else
     end
 
 
-    if prepSA & isempty(strmatch('T',who('-file', filetoload),'exact')),
+    if prepSA && isempty(strmatch('T',who('-file', filetoload),'exact')),
         h = dyn_waitbar(0,'Please wait...');
         options_.periods=0;
         options_.nomoments=1;
@@ -463,7 +463,7 @@ delete([OutputDirectoryName,'/',fname_,'_',auname,'_corr_*.*']);
 delete([OutputDirectoryName,'/',fname_,'_',aunstname,'_corr_*.*']);
 delete([OutputDirectoryName,'/',fname_,'_',aindname,'_corr_*.*']);
 
-if length(iunstable)>0 & length(iunstable)<Nsam,
+if length(iunstable)>0 && length(iunstable)<Nsam,
     fprintf(['%4.1f%% of the prior support is stable.\n'],length(istable)/Nsam*100)
     fprintf(['%4.1f%% of the prior support is unstable.\n'],(length(iunstable)-length(iwrong)-length(iindeterm) )/Nsam*100)
     if ~isempty(iindeterm),
@@ -568,6 +568,8 @@ else
 
 end
 
+xparam1=x0;
+save prior_ok xparam1;
 
 options_.periods=opt.periods;
 if isfield(opt,'nomoments'),
diff --git a/matlab/gsa/stab_map_1.m b/matlab/gsa/stab_map_1.m
index 3c354cc994f6469266e0040ee44290e830ee1f10..85df2d838b603da9c5e6c4786453eab6418adf90 100644
--- a/matlab/gsa/stab_map_1.m
+++ b/matlab/gsa/stab_map_1.m
@@ -77,7 +77,7 @@ if isempty(ipar),
     ipar=find(proba<pcrit);
 end
 nparplot=length(ipar);
-if iplot
+if iplot && ~options_.nograph
   lpmat=lpmat(:,ipar);
   ftit=bayestopt_.name(ipar+nshock*(1-ishock));
   
diff --git a/matlab/gsa/stab_map_2.m b/matlab/gsa/stab_map_2.m
index a1a72c790760bb06dd6f3551bac32010faf26eef..594fe91fa8e7d248f0c87ce079241a189481938d 100644
--- a/matlab/gsa/stab_map_2.m
+++ b/matlab/gsa/stab_map_2.m
@@ -1,5 +1,5 @@
 function stab_map_2(x,alpha2, pvalue, fnam, dirname,xparam1)
-% function stab_map_2(x, alpha2, pvalue, fnam, dirname)
+% function stab_map_2(x, alpha2, pvalue, fnam, dirname,xparam1)
 %
 % Written by Marco Ratto
 % Joint Research Centre, The European Commission,
@@ -64,54 +64,70 @@ if ishock==0
 else
   npar=estim_params_.np+nshock;
 end
+disp([' '])
+disp(['Correlation analysis for ',fnam])
+
 for j=1:npar,
-  i2=find(abs(c00(:,j))>alpha2);
-  if length(i2)>0,
-    for jx=1:length(i2),
-          tval  = abs(c00(i2(jx),j)*sqrt( (nsam-2)/(1-c00(i2(jx),j)^2) ));
-          tcr = tcrit(nsam-2,pvalue);
-          if tval>tcr,
-      j2=j2+1;
-      if mod(j2,12)==1,
-        ifig=ifig+1;
-        hh=dyn_figure(options_,'name',['Correlations in the ',fnam,' sample ', num2str(ifig)]);
-      end
-      subplot(3,4,j2-(ifig-1)*12)
-      %             bar(c0(i2,j)), 
-      %             set(gca,'xticklabel',bayestopt_.name(i2)), 
-      %             set(gca,'xtick',[1:length(i2)])
-      %plot(stock_par(ixx(nfilt+1:end,i),j),stock_par(ixx(nfilt+1:end,i),i2(jx)),'.k')
-      %hold on, 
-      plot(x(:,j),x(:,i2(jx)),'.')
-      if ~isempty(xparam1)
-          hold on, plot(xparam1(j),xparam1(i2(jx)),'ro')
-      end
-      %             xlabel(deblank(estim_params_.param_names(j,:)),'interpreter','none'), 
-      %             ylabel(deblank(estim_params_.param_names(i2(jx),:)),'interpreter','none'), 
-      if ishock,
-        xlabel(bayestopt_.name{j},'interpreter','none'), 
-        ylabel(bayestopt_.name{i2(jx)},'interpreter','none'), 
-      else
-        xlabel(bayestopt_.name{j+nshock},'interpreter','none'), 
-        ylabel(bayestopt_.name{i2(jx)+nshock},'interpreter','none'), 
-      end
-      title(['cc = ',num2str(c0(i2(jx),j))])
-      if (mod(j2,12)==0) && j2>0,
+    i2=find(abs(c00(:,j))>alpha2);
+    if length(i2)>0,
+        for jx=1:length(i2),
+            tval  = abs(c00(i2(jx),j)*sqrt( (nsam-2)/(1-c00(i2(jx),j)^2) ));
+            tcr = tcrit(nsam-2,pvalue);
+            if tval>tcr,
+                j2=j2+1;
+                if ishock,
+                    tmp_name = (['[',bayestopt_.name{j},',',bayestopt_.name{i2(jx)},']']);
+                else
+                    tmp_name = (['[',bayestopt_.name{j+nshock},',',bayestopt_.name{i2(jx)+nshock},']']);
+                end
+                fprintf(1,'%20s: corrcoef = %7.3f\n',tmp_name,c0(i2(jx),j));
+                    
+                if ~options_.nograph,
+                    
+                if mod(j2,12)==1,
+                    ifig=ifig+1;
+                    hh=dyn_figure(options_,'name',['Correlations in the ',fnam,' sample ', num2str(ifig)]);
+                end
+                subplot(3,4,j2-(ifig-1)*12)
+                %             bar(c0(i2,j)),
+                %             set(gca,'xticklabel',bayestopt_.name(i2)),
+                %             set(gca,'xtick',[1:length(i2)])
+                %plot(stock_par(ixx(nfilt+1:end,i),j),stock_par(ixx(nfilt+1:end,i),i2(jx)),'.k')
+                %hold on,
+                plot(x(:,j),x(:,i2(jx)),'.')
+                if ~isempty(xparam1)
+                    hold on, plot(xparam1(j),xparam1(i2(jx)),'ro')
+                end
+                %             xlabel(deblank(estim_params_.param_names(j,:)),'interpreter','none'),
+                %             ylabel(deblank(estim_params_.param_names(i2(jx),:)),'interpreter','none'),
+                if ishock,
+                    xlabel(bayestopt_.name{j},'interpreter','none'),
+                    ylabel(bayestopt_.name{i2(jx)},'interpreter','none'),
+                else
+                    xlabel(bayestopt_.name{j+nshock},'interpreter','none'),
+                    ylabel(bayestopt_.name{i2(jx)+nshock},'interpreter','none'),
+                end
+                title(['cc = ',num2str(c0(i2(jx),j))])
+                if (mod(j2,12)==0) && j2>0,
+                    dyn_saveas(hh,[dirname,'/',fig_nam_,int2str(ifig)],options_);
+                    if ~options_.nodisplay
+                        close(hh);
+                    end
+                end
+                end
+            end
+            
+        end
+    end
+    if ~options_.nograph && (j==(npar)) && j2>0 && (mod(j2,12)~=0),
         dyn_saveas(hh,[dirname,'/',fig_nam_,int2str(ifig)],options_);
         if ~options_.nodisplay
-          close(hh);
+            close(hh);
         end
-      end
-          end
-          
     end
-  end
-  if (j==(npar)) && j2>0,
-    dyn_saveas(hh,[dirname,'/',fig_nam_,int2str(ifig)],options_);
-  end
-  
+    
 end
-if ifig==0,
-  disp(['No correlation term >', num2str(alpha2),' found for ',fnam])
+if j2==0,
+    disp(['No correlation term with pvalue <', num2str(pvalue),' found for ',fnam])
 end
 %close all
diff --git a/matlab/gsa/tcrit.m b/matlab/gsa/tcrit.m
index f401ecabe60d47bc0900f0c733efc322ab703a07..2efd947e646d58c355952ba05f46dc9bfd8c33f5 100644
--- a/matlab/gsa/tcrit.m
+++ b/matlab/gsa/tcrit.m
@@ -30,6 +30,14 @@ function t_crit = tcrit(n,pval0)
 if nargin==1 || isempty(pval0),
     pval0=0.05;
 end
+if pval0==1,
+    t_crit=0;
+    return,
+end
+if pval0==0,
+    t_crit=inf;
+    return,
+end
 pval = [  0.10    0.05   0.025    0.01   0.005   0.001];
 pval0=max(pval0,min(pval));
 ncol=min(find(pval<=pval0))+1;
diff --git a/matlab/gsa/thet2tau.m b/matlab/gsa/thet2tau.m
deleted file mode 100644
index 7ebdd1a89fe96e093f8f5c154c13ed1c22e07822..0000000000000000000000000000000000000000
--- a/matlab/gsa/thet2tau.m
+++ /dev/null
@@ -1,62 +0,0 @@
-function tau = thet2tau(params, indx, indexo, flagmoments,mf,nlags,useautocorr)
-
-% Copyright (C) 2012 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_ oo_ options_
-
-if nargin==1,
-    indx = [1:M_.param_nbr];
-    indexo = [];
-end
-
-if nargin<4,
-  flagmoments=0;
-end
-if nargin<7 | isempty(useautocorr),
-  useautocorr=0;
-end
-
-M_.params(indx) = params(length(indexo)+1:end);
-if ~isempty(indexo)
-  M_.Sigma_e(indexo,indexo) = diag(params(1:length(indexo)).^2);
-end
-[A,B,plouf,plouf,M_,options_,oo_] = dynare_resolve(M_,options_,oo_);
-if flagmoments==0,
-tau = [oo_.dr.ys(oo_.dr.order_var); A(:); dyn_vech(B*M_.Sigma_e*B')];
-else
-GAM =  lyapunov_symm(A,B*M_.Sigma_e*B',options_.qz_criterium,options_.lyapunov_complex_threshold);
-k = find(abs(GAM) < 1e-12);
-GAM(k) = 0;
-if useautocorr,
-  sy = sqrt(diag(GAM));
-  sy = sy*sy';
-  sy0 = sy-diag(diag(sy))+eye(length(sy));
-  dum = GAM./sy0;
-  tau = dyn_vech(dum(mf,mf));
-else
-  tau = dyn_vech(GAM(mf,mf));
-end
-for ii = 1:nlags
-  dum = A^(ii)*GAM;
-  if useautocorr,
-    dum = dum./sy;
-  end
-  tau = [tau;vec(dum(mf,mf))];
-end
-tau = [ oo_.dr.ys(oo_.dr.order_var(mf)); tau];
-end
\ No newline at end of file
diff --git a/matlab/hessian.m b/matlab/hessian.m
index 9e1825cd54b92857250867eaadd3076a186fe16b..d536c27a3b0ec17b75f718a2e5cb47d89e31e7c3 100644
--- a/matlab/hessian.m
+++ b/matlab/hessian.m
@@ -18,7 +18,7 @@ function hessian_mat = hessian(func,x,gstep,varargin)
 %    none
 %  
 
-% Copyright (C) 2001-2009 Dynare Team
+% Copyright (C) 2001-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/homotopy1.m b/matlab/homotopy1.m
index 1d5d203ca9b380be22ed6149e82aa58b4a34b139..e7de1f16a73e6682703a2f2731ecbd045d8f4479 100644
--- a/matlab/homotopy1.m
+++ b/matlab/homotopy1.m
@@ -30,7 +30,7 @@ function [M,oo,info,ip,ix,ixd] = homotopy1(values, step_nbr, M, options, oo)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2008-2011 Dynare Team
+% Copyright (C) 2008-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/homotopy2.m b/matlab/homotopy2.m
index 726a8aac09e6491d8309fe91f450316ba143b97b..8e1318a86b38c568501d2a5eff01de59a31b1214 100644
--- a/matlab/homotopy2.m
+++ b/matlab/homotopy2.m
@@ -25,7 +25,7 @@ function homotopy2(values, step_nbr)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2008-2009 Dynare Team
+% Copyright (C) 2008-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/homotopy3.m b/matlab/homotopy3.m
index f1ee8ac1f4523695890a787bd0fa2feba0c3a054..a506bb6b66bc0f566893abdda58342b025a88e5e 100644
--- a/matlab/homotopy3.m
+++ b/matlab/homotopy3.m
@@ -33,7 +33,7 @@ function [M,oo,info,ip,ix,ixd]=homotopy3(values, step_nbr, M, options, oo)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2008-2009 Dynare Team
+% Copyright (C) 2008-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/ident_bruteforce.m b/matlab/ident_bruteforce.m
index 93b7a5c58f5f6a997e621ef5691eff29bf564708..592ffcd07c119c17cdb57814ec1217a3bebc4b91 100644
--- a/matlab/ident_bruteforce.m
+++ b/matlab/ident_bruteforce.m
@@ -1,102 +1,103 @@
-function [pars, cosnJ] = ident_bruteforce(J,n,TeX, pnames_TeX)
-% function [pars, cosnJ] = ident_bruteforce(J,n,TeX, pnames_TeX)
-%
-% given the Jacobian matrix J of moment derivatives w.r.t. parameters
-% computes, for  each column of  J, the groups of columns from 1 to n that
-% can repliate at best the derivatives of that column
-%
-% OUTPUTS
-%  pars  : cell array with groupf of params for each column of J for 1 to n
-%  cosnJ : the cosn of each column with the selected group of columns
-
-% Copyright (C) 2009 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/licen
-global M_ options_
-
-OutputDirectoryName = CheckPath('Identification',M_.dname);
-
-k = size(J,2); % number of parameters
-
-if nargin<2 || isempty(n)
-    n = 4; % max n-tuple
-end
-if nargin<3 || isempty(TeX)
-    TeX = 0; % max n-tuple
-end
-
-cosnJ=zeros(k,n);
-pars{k,n}=[];
-for ll = 1:n,
-    h = dyn_waitbar(0,['Brute force collinearity for ' int2str(ll) ' parameters.']);
-    for ii = 1:k
-        tmp = find([1:k]~=ii);
-        tmp2  = nchoosek(tmp,ll);
-        cosnJ2=zeros(size(tmp2,1),1);
-        b=[];
-        for jj = 1:size(tmp2,1)
-            [cosnJ2(jj,1), b(:,jj)] = cosn([J(:,ii),J(:,tmp2(jj,:))]);
-        end
-        cosnJ(ii,ll) = max(cosnJ2(:,1));
-        if cosnJ(ii,ll)>1.e-8,
-            if ll>1 && ((cosnJ(ii,ll)-cosnJ(ii,ll-1))<1.e-8),
-                pars{ii,ll} = [pars{ii,ll-1} NaN];
-                cosnJ(ii,ll) = cosnJ(ii,ll-1);
-            else
-                pars{ii,ll} = tmp2(find(cosnJ2(:,1)==max(cosnJ2(:,1))),:);
-            end
-        else
-            pars{ii,ll} = NaN(1,ll);
-        end
-        dyn_waitbar(ii/k,h)
-    end
-    dyn_waitbar_close(h);
-    if TeX
-        filename = [OutputDirectoryName '/' M_.fname '_collinearity_patterns' int2str(ll) '.TeX'];
-        fidTeX = fopen(filename,'w');
-        fprintf(fidTeX,'%% TeX-table generated by ident_bruteforce (Dynare).\n');
-        fprintf(fidTeX,['%% Collinearity patterns with ',int2str(ll),' parameter(s)\n']);
-        fprintf(fidTeX,['%% ' datestr(now,0)]);
-        fprintf(fidTeX,' \n');
-        fprintf(fidTeX,' \n');
-        fprintf(fidTeX,'{\\tiny \n');
-        fprintf(fidTeX,'\\begin{table}\n');
-        fprintf(fidTeX,'\\centering\n');
-        fprintf(fidTeX,'\\begin{tabular}{l|lc} \n');
-        fprintf(fidTeX,'\\hline\\hline \\\\ \n');
-        fprintf(fidTeX,'  Parameter & Explanatory & cosn \\\\ \n');
-        fprintf(fidTeX,'            & parameter(s)   &  \\\\ \n');
-        fprintf(fidTeX,'\\hline \\\\ \n');
-        for i=1:k,
-            plist='';
-            for ii=1:ll,
-                plist = [plist ' $' pnames_TeX(pars{i,ll}(ii),:) '$ '];
-            end
-            fprintf(fidTeX,'$%s$ & [%s] & %7.3f \\\\ \n',...
-                pnames_TeX(i,:),...
-                plist,...
-                cosnJ(i,ll));
-        end
-        fprintf(fidTeX,'\\hline\\hline \n');
-        fprintf(fidTeX,'\\end{tabular}\n ');
-        fprintf(fidTeX,['\\caption{Collinearity patterns with ',int2str(ll),' parameter(s)}\n ']);
-        fprintf(fidTeX,['\\label{Table:CollinearityPatterns:',int2str(ll),'}\n']);
-        fprintf(fidTeX,'\\end{table}\n');
-        fprintf(fidTeX,'} \n');
-        fprintf(fidTeX,'%% End of TeX file.\n');
-        fclose(fidTeX);
-    end
+function [pars, cosnJ] = ident_bruteforce(J,n,TeX, pnames_TeX)
+% function [pars, cosnJ] = ident_bruteforce(J,n,TeX, pnames_TeX)
+%
+% given the Jacobian matrix J of moment derivatives w.r.t. parameters
+% computes, for  each column of  J, the groups of columns from 1 to n that
+% can repliate at best the derivatives of that column
+%
+% OUTPUTS
+%  pars  : cell array with groupf of params for each column of J for 1 to n
+%  cosnJ : the cosn of each column with the selected group of columns
+
+% Copyright (C) 2009-2011 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/licen
+global M_ options_
+
+OutputDirectoryName = CheckPath('Identification',M_.dname);
+
+k = size(J,2); % number of parameters
+
+if nargin<2 || isempty(n)
+    n = 4; % max n-tuple
+end
+if nargin<3 || isempty(TeX)
+    TeX = 0; % max n-tuple
+end
+
+cosnJ=zeros(k,n);
+pars{k,n}=[];
+for ll = 1:n,
+    h = dyn_waitbar(0,['Brute force collinearity for ' int2str(ll) ' parameters.']);
+    for ii = 1:k
+        tmp = find([1:k]~=ii);
+        tmp2  = nchoosek(tmp,ll);
+        cosnJ2=zeros(size(tmp2,1),1);
+        b=[];
+        for jj = 1:size(tmp2,1)
+            [cosnJ2(jj,1), b(:,jj)] = cosn([J(:,ii),J(:,tmp2(jj,:))]);
+        end
+        cosnJ(ii,ll) = max(cosnJ2(:,1));
+        if cosnJ(ii,ll)>1.e-8,
+            if ll>1 && ((cosnJ(ii,ll)-cosnJ(ii,ll-1))<1.e-8),
+                pars{ii,ll} = [pars{ii,ll-1} NaN];
+                cosnJ(ii,ll) = cosnJ(ii,ll-1);
+            else
+                tmp3 = tmp2(find(cosnJ2(:,1)==max(cosnJ2(:,1))),:);
+                pars{ii,ll} = tmp3(1,:);
+            end
+        else
+            pars{ii,ll} = NaN(1,ll);
+        end
+        dyn_waitbar(ii/k,h)
+    end
+    dyn_waitbar_close(h);
+    if TeX
+        filename = [OutputDirectoryName '/' M_.fname '_collinearity_patterns' int2str(ll) '.TeX'];
+        fidTeX = fopen(filename,'w');
+        fprintf(fidTeX,'%% TeX-table generated by ident_bruteforce (Dynare).\n');
+        fprintf(fidTeX,['%% Collinearity patterns with ',int2str(ll),' parameter(s)\n']);
+        fprintf(fidTeX,['%% ' datestr(now,0)]);
+        fprintf(fidTeX,' \n');
+        fprintf(fidTeX,' \n');
+        fprintf(fidTeX,'{\\tiny \n');
+        fprintf(fidTeX,'\\begin{table}\n');
+        fprintf(fidTeX,'\\centering\n');
+        fprintf(fidTeX,'\\begin{tabular}{l|lc} \n');
+        fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+        fprintf(fidTeX,'  Parameter & Explanatory & cosn \\\\ \n');
+        fprintf(fidTeX,'            & parameter(s)   &  \\\\ \n');
+        fprintf(fidTeX,'\\hline \\\\ \n');
+        for i=1:k,
+            plist='';
+            for ii=1:ll,
+                plist = [plist ' $' pnames_TeX(pars{i,ll}(ii),:) '$ '];
+            end
+            fprintf(fidTeX,'$%s$ & [%s] & %7.3f \\\\ \n',...
+                pnames_TeX(i,:),...
+                plist,...
+                cosnJ(i,ll));
+        end
+        fprintf(fidTeX,'\\hline\\hline \n');
+        fprintf(fidTeX,'\\end{tabular}\n ');
+        fprintf(fidTeX,['\\caption{Collinearity patterns with ',int2str(ll),' parameter(s)}\n ']);
+        fprintf(fidTeX,['\\label{Table:CollinearityPatterns:',int2str(ll),'}\n']);
+        fprintf(fidTeX,'\\end{table}\n');
+        fprintf(fidTeX,'} \n');
+        fprintf(fidTeX,'%% End of TeX file.\n');
+        fclose(fidTeX);
+    end
 end
\ No newline at end of file
diff --git a/matlab/identification_analysis.m b/matlab/identification_analysis.m
index a75293cd1c71ec74185427d4de5643fb8531d42f..2c0b701f68688c32dfd6987a63f023de7bc75e74 100644
--- a/matlab/identification_analysis.m
+++ b/matlab/identification_analysis.m
@@ -7,7 +7,7 @@ function [ide_hess, ide_moments, ide_model, ide_lre, derivatives_info, info] = i
 %    o indx               [array] index of estimated parameters
 %    o indexo             [array] index of estimated shocks
 %    o options_ident      [structure] identification options
-%    o data_info          [structure] data info for Kalmna Filter
+%    o data_info          [structure] data info for Kalman Filter
 %    o prior_exist        [integer] 
 %                           =1 when prior exists and indentification is checked only for estimated params and shocks
 %                           =0 when prior is not defined and indentification is checked for all params and shocks
@@ -25,7 +25,7 @@ function [ide_hess, ide_moments, ide_model, ide_lre, derivatives_info, info] = i
 % SPECIAL REQUIREMENTS
 %    None
 
-% Copyright (C) 2008-2011 Dynare Team
+% Copyright (C) 2008-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -48,7 +48,7 @@ persistent indH indJJ indLRE
 nparam=length(params);
 np=length(indx);
 offset=nparam-np;
-set_all_parameters(params);
+M_ = set_all_parameters(params,estim_params_,M_);
 
 nlags = options_ident.ar;
 useautocorr = options_ident.useautocorr;
@@ -57,6 +57,8 @@ replic = options_ident.replic;
 periods = options_ident.periods;
 max_dim_cova_group = options_ident.max_dim_cova_group;
 normalize_jacobians = options_ident.normalize_jacobians;
+kron_flag = options_ident.analytic_derivation_mode;
+    
 [I,J]=find(M_.lead_lag_incidence');
 
 ide_hess = struct();
@@ -75,7 +77,7 @@ if info(1)==0,
         oo_.dr.ys, 1);
     vg1 = [oo_.dr.ys(oo_.dr.order_var); vec(g1)];
 
-    [JJ, H, gam, gp, dA, dOm, dYss] = getJJ(A, B, M_,oo0,options_,0,indx,indexo,bayestopt_.mf2,nlags,useautocorr);
+    [JJ, H, gam, gp, dA, dOm, dYss] = getJJ(A, B, M_,oo0,options_,kron_flag,indx,indexo,bayestopt_.mf2,nlags,useautocorr);
     derivatives_info.DT=dA;
     derivatives_info.DOm=dOm;
     derivatives_info.DYss=dYss;
@@ -85,7 +87,7 @@ if info(1)==0,
             disp('The number of moments with non-zero derivative is smaller than the number of parameters')
             disp(['Try increasing ar = ', int2str(nlags+1)])           
             nlags=nlags+1;
-            [JJ, H, gam, gp, dA, dOm, dYss] = getJJ(A, B, M_,oo0,options_,0,indx,indexo,bayestopt_.mf2,nlags,useautocorr);
+            [JJ, H, gam, gp, dA, dOm, dYss] = getJJ(A, B, M_,oo0,options_,kron_flag,indx,indexo,bayestopt_.mf2,nlags,useautocorr);
             derivatives_info.DT=dA;
             derivatives_info.DOm=dOm;
             derivatives_info.DYss=dYss;
@@ -130,7 +132,10 @@ if info(1)==0,
             options_.noprint = 1;
             options_.order = 1;
             options_.periods = data_info.info.ntobs+100;
-            options_.kalman_algo = 1;
+            if options_.kalman_algo > 2,
+                options_.kalman_algo = 1;
+            end
+            analytic_derivation = options_.analytic_derivation;
             options_.analytic_derivation = -2;
             info = stoch_simul(options_.varobs);
             data_info.data=oo_.endo_simul(options_.varobs_id,100+1:end);
@@ -138,6 +143,7 @@ if info(1)==0,
             derivatives_info.no_DLIK=1;
             [fval,DLIK,AHess,cost_flag,ys,trend_coeff,info,M_,options_,bayestopt_,oo_] = dsge_likelihood(params',data_info,options_,M_,estim_params_,bayestopt_,oo_,derivatives_info);
 %                 fval = DsgeLikelihood(xparam1,data_info,options_,M_,estim_params_,bayestopt_,oo_);
+            options_.analytic_derivation = analytic_derivation;
             AHess=-AHess;
             if min(eig(AHess))<0,
                 error('Analytic Hessian is not positive semi-definite!')
@@ -282,6 +288,7 @@ if info(1)==0,
     normJ=1;
     [U, S, V]=svd(JJ(indJJ,:)./normJ,0);
     S=diag(S);
+    S=[S;zeros(size(JJ,2)-length(indJJ),1)];
     if nparam>8
         ide_moments.S = S([1:4, end-3:end]);
         ide_moments.V = V(:,[1:4, end-3:end]);
diff --git a/matlab/imcforecast.m b/matlab/imcforecast.m
index d5b62e81682ad35cad6e83cdfbfa402e9403e04b..51d4c19dec2afd1779654ae43feb344810e9e551 100644
--- a/matlab/imcforecast.m
+++ b/matlab/imcforecast.m
@@ -26,7 +26,7 @@ function imcforecast(constrained_paths, constrained_vars, options_cond_fcst)
 %  [1] Results are stored in a structure which is saved in a mat file called conditional_forecasts.mat.
 %  [2] Use the function plot_icforecast to plot the results. 
 
-% Copyright (C) 2006-2010 Dynare Team
+% Copyright (C) 2006-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/initial_estimation_checks.m b/matlab/initial_estimation_checks.m
index 0d6463f1937c50dca09c9aef770bc63cd3fd1cb0..08926fae872b8ae29bd4239b0bacaaf183ea4800 100644
--- a/matlab/initial_estimation_checks.m
+++ b/matlab/initial_estimation_checks.m
@@ -13,7 +13,7 @@ function DynareResults = initial_estimation_checks(objective_function,xparam1,Dy
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2011 Dynare Team
+% Copyright (C) 2003-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -31,7 +31,11 @@ function DynareResults = initial_estimation_checks(objective_function,xparam1,Dy
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 if DynareDataset.info.nvobs>Model.exo_nbr+EstimatedParameters.nvn
-    error(['initial_estimation_checks:: Estimation can''t take place because there are less shocks than observed variables!'])
+    error(['initial_estimation_checks:: Estimation can''t take place because there are less declared shocks than observed variables!'])
+end
+
+if DynareDataset.info.nvobs>find(diag(Model.Sigma_e))+EstimatedParameters.nvn
+    error(['initial_estimation_checks:: Estimation can''t take place because too many shocks have been calibrated with a zero variance!'])
 end
 
 % check if steady state solves static model (except if diffuse_filter == 1)
@@ -46,10 +50,15 @@ else
     info = d;
 end
 
-if DynareOptions.mode_compute==5
-    if ~strcmp(func2str(objective_function),'dsge_likelihood')
-        error('Options mode_compute=5 is not compatible with non linear filters or Dsge-VAR models!')
-    end
+% if DynareOptions.mode_compute==5
+%     if ~strcmp(func2str(objective_function),'dsge_likelihood')
+%         error('Options mode_compute=5 is not compatible with non linear filters or Dsge-VAR models!')
+%     end
+% end
+if isnan(fval)
+    error('The initial value of the likelihood is NaN')
+elseif imag(fval)
+    error('The initial value of the likelihood is complex')
 end
 
 if info(1) > 0
diff --git a/matlab/issquare.m b/matlab/issquare.m
new file mode 100644
index 0000000000000000000000000000000000000000..71233cbf6a4d93fc1b6190efebbf585ebfdfec07
--- /dev/null
+++ b/matlab/issquare.m
@@ -0,0 +1,48 @@
+function i = issquare(A)
+
+%@info:
+%! @deftypefn {Function File} {@var{i} =} issquare (@var{A})
+%! @anchor{issquare}
+%! @sp 1
+%! Returns 1 if @var{A} is a square matrix, 0 otherwise.
+%! @sp 2
+%! @strong{Inputs}
+%! @sp 1
+%! @table @ @var
+%! @item A
+%! Matrix.
+%! @end table
+%! @sp 1
+%! @strong{Outputs}
+%! @sp 1
+%! @table @ @var
+%! @item i
+%! Integer scalar (0 or 1).
+%! @end table
+%! @sp 2
+%! @strong{This function is called by:}
+%! @sp 2
+%! @strong{This function calls:}
+%! @sp 2
+%! @end deftypefn
+%@eod:
+
+% Copyright (C) 2012 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/>.
+
+d = size(A);
+i = (length(d)==2) && (d(1)==d(2));
\ No newline at end of file
diff --git a/matlab/k_order_pert.m b/matlab/k_order_pert.m
index 09eeb955b9cdaa87e1740f2b29be86bdb5da7e3e..0fb2355ecf4c44cf4f0c9a8651fa1745a7f21568 100644
--- a/matlab/k_order_pert.m
+++ b/matlab/k_order_pert.m
@@ -23,6 +23,9 @@ info = 0;
 M.var_order_endo_names = M.endo_names(dr.order_var,:);
 
 order = options.order;
+endo_nbr = M.endo_nbr;
+exo_nbr = M.exo_nbr;
+npred = dr.npred;
 
 switch(order)
   case 1
@@ -36,7 +39,25 @@ switch(order)
     dr.g_1 = g_1;
     dr.g_2 = g_2;
   case 3
-    [err, g_0, g_1, g_2, g_3] = k_order_perturbation(dr,M,options);
+    if options.pruning
+        [err, g_0, g_1, g_2, g_3, derivs] = k_order_perturbation(dr, ...
+                                                          M,options);
+        dr.ghx = derivs.gy;
+        dr.ghu = derivs.gu;
+        dr.ghxx = unfold2(derivs.gyy,npred);
+        dr.ghxu = derivs.gyu;
+        dr.ghuu = unfold2(derivs.guu,exo_nbr);
+        dr.ghs2 = derivs.gss;
+        dr.ghxxx = unfold3(derivs.gyyy,npred);
+        dr.ghxxu = unfold21(derivs.gyyu,npred,exo_nbr);
+        dr.ghxuu = unfold12(derivs.gyuu,npred,exo_nbr);
+        dr.ghuuu = unfold3(derivs.guuu,exo_nbr);
+        dr.ghxss = derivs.gyss;
+        dr.ghuss = derivs.guss;
+    else
+        [err, g_0, g_1, g_2, g_3] = k_order_perturbation(dr, ...
+                                                         M,options);
+    end
     mexErrCheck('k_order_perturbation', err);
     dr.g_0 = g_0;
     dr.g_1 = g_1;
@@ -46,10 +67,14 @@ switch(order)
     error('order > 3 isn''t implemented')
 end
 
+if options.pruning
+    return
+end
+
 npred = dr.npred;
 
-dr.ghx = g_1(:,1:npred);
-dr.ghu = g_1(:,npred+1:end);
+dr.ghx = dr.g_1(:,1:npred);
+dr.ghu = dr.g_1(:,npred+1:end);
 
 if options.loglinear == 1
     k = find(dr.kstate(:,2) <= M.maximum_endo_lag+1);
@@ -63,8 +88,6 @@ end
 
 if order > 1
     dr.ghs2 = 2*g_0;
-    endo_nbr = M.endo_nbr;
-    exo_nbr = M.exo_nbr;
     s0 = 0;
     s1 = 0;
     ghxx=zeros(endo_nbr, npred^2);
@@ -97,3 +120,66 @@ if order > 1
     dr.ghuu = ghuu;
 end
 
+function y = unfold2(x,n)
+y=zeros(size(x,1),n*n);
+m = 1;
+for i=1:n
+    for j=i:n
+        y(:,(i-1)*n+j)=x(:,m);
+        if j ~= i
+            y(:,(j-1)*n+i)=x(:,m);
+        end
+        m = m+1;
+    end
+end
+
+function y = unfold3(x,n)
+y = zeros(size(x,1),n*n*n);
+m = 1;
+for i=1:n
+    for j=i:n
+        for k=j:n
+            xx = x(:,m);
+            y(:,(i-1)*n*n+(j-1)*n+k) = xx;
+            y(:,(i-1)*n*n+(k-1)*n+j) = xx;
+            y(:,(j-1)*n*n+(k-1)*n+i) = xx;
+            y(:,(i-1)*n*n+(k-1)*n+j) = xx;
+            y(:,(k-1)*n*n+(i-1)*n+j) = xx;
+            y(:,(k-1)*n*n+(j-1)*n+i) = xx;
+        end
+    end
+end
+
+function y = unfold21(x,n1,n2)
+y = zeros(size(x,1),n1*n1*n2);
+m = 1;
+for i=1:n1
+    for j=i:n1
+        for k=1:n2
+            xx = x(:,m);
+            y(:,(i-1)*n1*n2+(j-1)*n2+k) = xx;
+            if j ~= i
+                y(:,(j-1)*n1*n2+(i-1)*n2+k) = xx;
+            end
+        end
+    end
+end
+
+function y = unfold12(x,n1,n2)
+y = zeros(size(x,1),n1*n2*n2);
+m = 1;
+for i=1:n1
+    for j=1:n2
+        for k=j:n2
+            xx = x(:,m);
+            y(:,(i-1)*n2*n2+(j-1)*n2+k) = xx;
+            if k ~= j
+                y(:,(i-1)*n2*n2+(k-1)*n2+j) = xx;
+            end
+        end
+    end
+end
+
+
+            
+            
\ No newline at end of file
diff --git a/matlab/k_order_perturbation.m b/matlab/k_order_perturbation.m
new file mode 100644
index 0000000000000000000000000000000000000000..566a281175b3960fb38cc038425cb6a7c4e7befb
--- /dev/null
+++ b/matlab/k_order_perturbation.m
@@ -0,0 +1,53 @@
+% [err, g_0, g_1, g_2, g_3, derivs] = k_order_perturbation(dr,DynareModel,DynareOptions)
+% computes a k_order_petrubation solution for k=1,2,3
+%
+% INPUTS
+% dr:            struct   describing the reduced form solution of the model.
+% DynareModel:   struct   jobs's parameters
+% DynareOptions: struct   job's options
+%
+% OUTPUTS
+% err:           double   err code (currently unused)
+% g_0:           vector   dynare++ output. Constant effect of future volatility (in
+%                         dr.order_var order) on the decision rule
+%                         (=ghs2/2). Contains zero when order of
+%                         approximation is 1.
+% g_1:           matrix   dynare++ output. First order Taylor coefficients
+%                         of decision rule. When order of approximation
+%                         is 3, the. Contains both the effect of
+%                         state endogenous variable and shocks. The rows
+%                         are in dr.order_var order. The columns are in
+%                         dr.order_var order of state endogenous
+%                         variables and shocks
+% g_2:           matrix   dynare++ output. Second order Taylor coefficients of decision
+%                         rule. Contains both the effect of state endogenous
+%                         variable and shocks. The rows are in dr.order_var
+%                         order. Each row corresponds to the vectorized
+%                         version of the lower triangle of the Hessian
+%                         matrix. The Taylor coefficient (1/2) is
+%                         included. The columns of the Hessian matrix are in
+%                         dr.order_var order of state endogenous variables
+%                         and shocks
+% g_3:           matrix   dynare++ output. Third order Taylor coefficients of decision
+%                         rule. Contains both the effect of state endogenous
+%                         variable and shocks. The rows are in dr.order_var
+%                         order. Each row corresponds to the vectorized
+%                         version of the 3rd order derivatives tensor where each
+%                         combination of variables appears only once.
+%                         The Taylor coefficient (1/6) is
+%                         included. Inside the tensor, the variables are in
+%                         dr.order_var order of state endogenous variables
+%                         and shocks 
+% derivs        struct    contains the original derivatives of the
+%                         decision function (ghx, ghu, ghxx, ghxu, ghuu,
+%                         ghs2, ghxxx, ghxxu, ghxuu,ghuuu, ghxss, ghuss),
+%                         keeping the effect of future volatility
+%                         separate (in  ghs2, ghxss and ghuss). The
+%                         derivatives matrices contain full versions of
+%                         the Hessian matrices and 3rd order
+%                         tensor. Symmetric derivatives are repeated. The
+%                         Taylor coefficients (1/2 and 1/6) aren't
+%                         included.
+% k_order_peturbation is a compiled MEX function. It's source code is in
+% dynare/mex/sources/k_order_perturbation.cc and it uses code provided by
+% dynare++
diff --git a/matlab/kalman/likelihood/computeDLIK.m b/matlab/kalman/likelihood/computeDLIK.m
index bb2ea4c98ea00bfb83c4734c8922cf8ac92b0ad8..d08901356cf3728ea81f38ed71a225bb572f8df9 100644
--- a/matlab/kalman/likelihood/computeDLIK.m
+++ b/matlab/kalman/likelihood/computeDLIK.m
@@ -24,18 +24,18 @@ persistent DK DF D2K D2F
 if notsteady
 if Zflag
     [DK,DF,DP1] = computeDKalmanZ(T,DT,DOm,P,DP,DH,Z,iF,K);
-    if nargout>3,
+    if nargout>4,
         [D2K,D2F,D2P1] = computeD2KalmanZ(T,DT,D2T,D2Om,P,DP,D2P,DH,Z,iF,K,DK);
     end
 else
     [DK,DF,DP1] = computeDKalman(T,DT,DOm,P,DP,DH,Z,iF,K);
-    if nargout>3,
+    if nargout>4,
         [D2K,D2F,D2P1] = computeD2Kalman(T,DT,D2T,D2Om,P,DP,D2P,DH,Z,iF,K,DK);
     end
 end
 else
     DP1=DP;
-    if nargout>3,
+    if nargout>4,
         D2P1=D2P;
     end
 end
@@ -95,10 +95,27 @@ for ii = 1:k
             end
         end
     end
+        
     Da(:,ii)   = DT(:,:,ii)*tmp + T*dtmp(:,ii);
     DLIK(ii,1)  = trace( iF*DF(:,:,ii) ) + 2*Dv(:,ii)'*iF*v - v'*(iF*DF(:,:,ii)*iF)*v;
 end
 
+if nargout==4,
+    %         Hesst(ii,jj) = getHesst_ij(v,Dv(:,ii),Dv(:,jj),0,iF,diFi,diFj,0,dFj,0);
+    vecDPmf = reshape(DF,[],k);
+    D2a = 2*Dv'*iF*Dv + (vecDPmf' * kron(iF,iF) * vecDPmf);
+%     for ii = 1:k
+%         
+%         diFi = -iF*DF(:,:,ii)*iF;
+%         for jj = 1:ii
+%             dFj    = DF(:,:,jj);
+%             diFj   = -iF*DF(:,:,jj)*iF;
+%             
+%             Hesst(ii,jj) = getHesst_ij(v*0,Dv(:,ii),Dv(:,jj),v*0,iF,diFi,diFj,0,-dFj,0);
+%         end
+%     end
+end
+
 % end of computeDLIK
 
 function Hesst_ij = getHesst_ij(e,dei,dej,d2eij,iS,diSi,diSj,d2iSij,dSj,d2Sij);
diff --git a/matlab/kalman/likelihood/kalman_filter.m b/matlab/kalman/likelihood/kalman_filter.m
index e6ab6161586af51a7f69927f1be8c662eb0d9d1b..f7db1f3aaf13d48dcc7c1a1e1f9be35ed2866a96 100644
--- a/matlab/kalman/likelihood/kalman_filter.m
+++ b/matlab/kalman/likelihood/kalman_filter.m
@@ -1,4 +1,4 @@
-function [LIK, likk, a, P] = kalman_filter(Y,start,last,a,P,kalman_tol,riccati_tol,presample,T,Q,R,H,Z,mm,pp,rr,Zflag,diffuse_periods,analytic_derivation,DT,DYss,DOm,DH,DP,D2T,D2Yss,D2Om,D2H,D2P)
+function [LIK, LIKK, a, P] = kalman_filter(Y,start,last,a,P,kalman_tol,riccati_tol,presample,T,Q,R,H,Z,mm,pp,rr,Zflag,diffuse_periods,analytic_derivation,DT,DYss,DOm,DH,DP,D2T,D2Yss,D2Om,D2H,D2P)
 % Computes the likelihood of a stationnary state space model.
 
 %@info:
@@ -71,7 +71,7 @@ function [LIK, likk, a, P] = kalman_filter(Y,start,last,a,P,kalman_tol,riccati_t
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2004-2011 Dynare Team
+% Copyright (C) 2004-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -123,14 +123,17 @@ LIK  = Inf;                % Default value of the log likelihood.
 oldK = Inf;
 notsteady   = 1;
 F_singular  = 1;
+asy_hess=0;
 
 if  analytic_derivation == 0,
     DLIK=[];
     Hess=[];
+    LIKK=[];
 else
     k = size(DT,3);                                 % number of structural parameters
     DLIK  = zeros(k,1);                             % Initialization of the score.
     Da    = zeros(mm,k);                            % Derivative State vector.
+    dlikk = zeros(smpl,k);
     
     if Zflag==0,
         C = zeros(pp,mm);
@@ -144,12 +147,17 @@ else
         D2a    = zeros(mm,k,k);                             % State vector.
         d2C = zeros(pp,mm,k,k);
     else
+        asy_hess=D2T;
         Hess=[];
         D2a=[];
         D2T=[];
         D2Yss=[];
     end
+    if asy_hess,
+        Hess  = zeros(k,k);                             % Initialization of the Hessian
+    end
     LIK={inf,DLIK,Hess};
+    LIKK={likk,dlikk};
 end
 
 while notsteady && t<=last
@@ -185,14 +193,15 @@ while notsteady && t<=last
             if analytic_derivation==2,
                 [Da,DP,DLIKt,D2a,D2P, Hesst] = computeDLIK(k,tmp,Z,Zflag,v,T,K,P,iF,Da,DYss,DT,DOm,DP,DH,notsteady,D2a,D2Yss,D2T,D2Om,D2P);
             else
-                [Da,DP,DLIKt] = computeDLIK(k,tmp,Z,Zflag,v,T,K,P,iF,Da,DYss,DT,DOm,DP,DH,notsteady);
+                [Da,DP,DLIKt,Hesst] = computeDLIK(k,tmp,Z,Zflag,v,T,K,P,iF,Da,DYss,DT,DOm,DP,DH,notsteady);
             end
             if t>presample
                 DLIK = DLIK + DLIKt;
-                if analytic_derivation==2,
+                if analytic_derivation==2 || asy_hess,
                     Hess = Hess + Hesst;
                 end
             end
+            dlikk(s,:)=DLIKt;
         end
         a = T*tmp;
         P=Ptmp;
@@ -208,19 +217,31 @@ end
 
 % Add observation's densities constants and divide by two.
 likk(1:s) = .5*(likk(1:s) + pp*log(2*pi));
+if analytic_derivation,
+    DLIK = DLIK/2;
+    dlikk = dlikk/2;
+    if analytic_derivation==2 || asy_hess,
+        if asy_hess==0,
+        Hess = Hess + tril(Hess,-1)';
+        end
+        Hess = -Hess/2;
+    end
+end
 
 % Call steady state Kalman filter if needed.
 if t <= last
     if analytic_derivation,
         if analytic_derivation==2,
-            [tmp, likk(s+1:end)] = kalman_filter_ss(Y,t,last,a,T,K,iF,dF,Z,pp,Zflag, ...
+            [tmp, tmp2] = kalman_filter_ss(Y,t,last,a,T,K,iF,dF,Z,pp,Zflag, ...
                 analytic_derivation,Da,DT,DYss,D2a,D2T,D2Yss);
         else
-            [tmp, likk(s+1:end)] = kalman_filter_ss(Y,t,last,a,T,K,iF,dF,Z,pp,Zflag, ...
-                analytic_derivation,Da,DT,DYss);
+            [tmp, tmp2] = kalman_filter_ss(Y,t,last,a,T,K,iF,dF,Z,pp,Zflag, ...
+                analytic_derivation,Da,DT,DYss,asy_hess);
         end
+        likk(s+1:end)=tmp2{1};
+        dlikk(s+1:end,:)=tmp2{2};
         DLIK = DLIK + tmp{2};
-        if analytic_derivation==2,
+        if analytic_derivation==2 || asy_hess,
             Hess = Hess + tmp{3};
         end
     else
@@ -229,20 +250,19 @@ if t <= last
 end
 
 % Compute minus the log-likelihood.
-if presample
-    if presample>=diffuse_periods
-        likk = likk(1+(presample-diffuse_periods):end);
-    end
+if presample>diffuse_periods,
+    LIK = sum(likk(1+(presample-diffuse_periods):end));
+else
+    LIK = sum(likk);
 end
-LIK = sum(likk);
 
 if analytic_derivation,
-    DLIK = DLIK/2;
-    if analytic_derivation==2,
-        Hess = Hess + tril(Hess,-1)';
-        Hess = -Hess/2;
+    if analytic_derivation==2 || asy_hess,
         LIK={LIK, DLIK, Hess};
     else
         LIK={LIK, DLIK};
     end
+    LIKK={likk, dlikk};
+else
+    LIKK=likk;
 end
diff --git a/matlab/kalman/likelihood/kalman_filter_d.m b/matlab/kalman/likelihood/kalman_filter_d.m
index 608ee9f1197e5877b197202af42878958beeef3d..e84103f52e82a623bab0647920d76eb215055213 100644
--- a/matlab/kalman/likelihood/kalman_filter_d.m
+++ b/matlab/kalman/likelihood/kalman_filter_d.m
@@ -31,7 +31,7 @@ function [dLIK,dlik,a,Pstar] = kalman_filter_d(Y, start, last, a, Pinf, Pstar, k
 %   Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series 
 %   Analysis, vol. 24(1), pp. 85-98). 
 
-% Copyright (C) 2004-2011 Dynare Team
+% Copyright (C) 2004-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/kalman/likelihood/kalman_filter_ss.m b/matlab/kalman/likelihood/kalman_filter_ss.m
index a99e51b3ea87c352ea486f292c6405f24d587521..43493e4fadd4b353871b3c83caf11aa5ce58b49b 100644
--- a/matlab/kalman/likelihood/kalman_filter_ss.m
+++ b/matlab/kalman/likelihood/kalman_filter_ss.m
@@ -54,7 +54,7 @@ function [LIK, likk, a] = kalman_filter_ss(Y,start,last,a,T,K,iF,dF,Z,pp,Zflag,a
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -81,6 +81,7 @@ t    = start;              % Initialization of the time index.
 likk = zeros(smpl,1);      % Initialization of the vector gathering the densities.
 LIK  = Inf;                % Default value of the log likelihood.
 notsteady = 0;
+asy_hess=0;
 if nargin<12
     analytic_derivation = 0;
 end
@@ -91,10 +92,16 @@ if  analytic_derivation == 0,
 else
     k = size(DT,3);                                 % number of structural parameters
     DLIK  = zeros(k,1);                             % Initialization of the score.
+    dlikk = zeros(smpl,k);
     if analytic_derivation==2,
         Hess  = zeros(k,k);                             % Initialization of the Hessian
     else
-        Hess=[];
+        asy_hess=D2a;
+        if asy_hess,
+            Hess  = zeros(k,k);                             % Initialization of the Hessian
+        else
+            Hess=[];
+        end
     end
 end
 
@@ -109,12 +116,13 @@ while t <= last
         if analytic_derivation==2,
             [Da,junk,DLIKt,D2a,junk2, Hesst] = computeDLIK(k,tmp,Z,Zflag,v,T,K,[],iF,Da,DYss,DT,[],[],[],notsteady,D2a,D2Yss,D2T,[],[]);
         else
-            [Da,junk,DLIKt] = computeDLIK(k,tmp,Z,Zflag,v,T,K,[],iF,Da,DYss,DT,[],[],[],notsteady);
+            [Da,junk,DLIKt,Hesst] = computeDLIK(k,tmp,Z,Zflag,v,T,K,[],iF,Da,DYss,DT,[],[],[],notsteady);
         end
         DLIK = DLIK + DLIKt;
-        if analytic_derivation==2,
+        if analytic_derivation==2 || asy_hess,
             Hess = Hess + Hesst;
         end
+        dlikk(t-start+1,:)=DLIKt;
     end
     a = T*tmp;
     likk(t-start+1) = transpose(v)*iF*v;
@@ -129,9 +137,17 @@ likk = .5*(likk + pp*log(2*pi));
 
 % Sum the observation's densities (minus the likelihood)
 LIK = sum(likk);
-if analytic_derivation==2,
-    LIK={LIK,DLIK,Hess};
+if analytic_derivation,
+    dlikk = dlikk/2;
+    DLIK = DLIK/2;
+    likk = {likk, dlikk};
 end
-if analytic_derivation==1,
+if analytic_derivation==2 || asy_hess,
+    if asy_hess==0,
+        Hess = Hess + tril(Hess,-1)';
+    end
+    Hess = -Hess/2;
+    LIK={LIK,DLIK,Hess};
+elseif analytic_derivation==1,
     LIK={LIK,DLIK};
 end
diff --git a/matlab/kalman/likelihood/missing_observations_kalman_filter.m b/matlab/kalman/likelihood/missing_observations_kalman_filter.m
index a7e9c9ad1218e3404cf45ef9decbc8d1f7a7aefb..577d57bebaf2545dc9eadba5b1e84d5aca0e3916 100644
--- a/matlab/kalman/likelihood/missing_observations_kalman_filter.m
+++ b/matlab/kalman/likelihood/missing_observations_kalman_filter.m
@@ -32,7 +32,7 @@ function  [LIK, lik, a, P] = missing_observations_kalman_filter(data_index,numbe
 % NOTES
 %   The vector "lik" is used to evaluate the jacobian of the likelihood.   
 
-% Copyright (C) 2004-2011 Dynare Team
+% Copyright (C) 2004-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -67,6 +67,10 @@ if isempty(diffuse_periods)
     diffuse_periods = 0;
 end
 
+if isequal(H,0)
+    H = zeros(pp,pp);
+end
+
 % Get sample size.
 smpl = last-start+1;
 
@@ -79,7 +83,8 @@ LIK  = Inf;                % Default value of the log likelihood.
 oldK = Inf;
 notsteady   = 1;
 F_singular  = 1;
-    
+s = 0;
+
 while notsteady & t<=last
     s  = t-start+1;
     d_index = data_index{t};
diff --git a/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m b/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m
index 4e0ae990fffa5a4068cf0e5dd7158ddd1158168d..608a07b7dfe564729c856441f16e102df85c3519 100644
--- a/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m
+++ b/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m
@@ -38,7 +38,7 @@ function [dLIK,dlik,a,Pstar] = missing_observations_kalman_filter_d(data_index,n
 %   Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series 
 %   Analysis, vol. 24(1), pp. 85-98). 
 
-% Copyright (C) 2004-2011 Dynare Team
+% Copyright (C) 2004-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -67,6 +67,11 @@ dlik = zeros(smpl,1);      % Initialization of the vector gathering the densitie
 dLIK = Inf;                % Default value of the log likelihood.
 oldK = Inf;
 
+if isequal(H,0)
+    H = zeros(pp,pp);
+end
+s = 0;
+
 while rank(Pinf,kalman_tol) && (t<=last)
     s = t-start+1;
     d_index = data_index{t};
@@ -107,7 +112,7 @@ while rank(Pinf,kalman_tol) && (t<=last)
             dlik(s) = log(det(Finf));
             iFinf  = inv(Finf);
             Kinf   = Pinf*ZZ'*iFinf;
-            Fstar  = ZZ*Pstar*ZZ' + H;
+            Fstar  = ZZ*Pstar*ZZ' + H(d_index,d_index);
             Kstar  = (Pstar*ZZ'-Kinf*Fstar)*iFinf;
             Pstar  = T*(Pstar-Pstar*ZZ'*Kinf'-Pinf*ZZ'*Kstar')*T'+QQ;
             Pinf   = T*(Pinf-Pinf*ZZ'*Kinf')*T';
diff --git a/matlab/kalman/likelihood/univariate_computeDLIK.m b/matlab/kalman/likelihood/univariate_computeDLIK.m
index c2662ea63f7ca3d0bbc77c25b03111d09df2249b..a9eb34459152b0b65fce003f2b99636c24e827c6 100644
--- a/matlab/kalman/likelihood/univariate_computeDLIK.m
+++ b/matlab/kalman/likelihood/univariate_computeDLIK.m
@@ -30,7 +30,7 @@ if notsteady,
             DF(j)=Z*DP(:,:,j)*Z'+DH;
             DK(:,j) = (DP(:,:,j)*Z')/F-PZ*DF(j)/F^2;
         end
-        if nargout>3
+        if nargout>4
             D2F = zeros(k,k);
             D2v = zeros(k,k);
             D2K = zeros(rows(K),k,k);
@@ -50,7 +50,7 @@ if notsteady,
         Dv   = -Da(Z,:) - DYss(Z,:);
         DF = squeeze(DP(Z,Z,:))+DH';
         DK = squeeze(DP(:,Z,:))/F-PZ*transpose(DF)/F^2;
-        if nargout>3
+        if nargout>4
             D2v   = squeeze(-D2a(Z,:,:) - D2Yss(Z,:,:));
             D2F = squeeze(D2P(Z,Z,:,:));
             D2K = squeeze(D2P(:,Z,:,:))/F;
@@ -60,7 +60,7 @@ if notsteady,
             end
         end
     end
-    if nargout>3
+    if nargout>4
         DD2K(:,indx,:,:)=D2K;
         DD2F(indx,:,:)=D2F;
     end
@@ -69,13 +69,13 @@ if notsteady,
 else
     DK = squeeze(DDK(:,indx,:));
     DF = DDF(indx,:)';
-    if nargout>3
+    if nargout>4
         D2K = squeeze(DD2K(:,indx,:,:));
         D2F = squeeze(DD2F(indx,:,:));
     end
     if Zflag
         Dv   = -Z*Da(:,:) - Z*DYss(:,:);
-        if nargout>3
+        if nargout>4
             D2v = zeros(k,k);
             for j=1:k,
                 D2v(:,j)   = -Z*D2a(:,:,j) - Z*D2Yss(:,:,j);
@@ -83,7 +83,7 @@ else
         end
     else
         Dv   = -Da(Z,:) - DYss(Z,:);
-        if nargout>3
+        if nargout>4
             D2v   = squeeze(-D2a(Z,:,:) - D2Yss(Z,:,:));
         end
     end
@@ -93,10 +93,15 @@ DLIK = DF/F + 2*Dv'/F*v - v^2/F^2*DF;
 if nargout==6
     Hesst = D2F/F-1/F^2*(DF*DF') + 2*D2v/F*v + 2*(Dv'*Dv)/F - 2*(DF*Dv)*v/F^2 ...
         - v^2/F^2*D2F - 2*v/F^2*(Dv'*DF') + 2*v^2/F^3*(DF*DF');
+elseif nargout==4,
+    D2a = 1/F^2*(DF*DF') + 2*(Dv'*Dv)/F ;
+%     D2a = -1/F^2*(DF*DF') + 2*(Dv'*Dv)/F  + 2*v^2/F^3*(DF*DF') ...
+%         - 2*(DF*Dv)*v/F^2 - 2*v/F^2*(Dv'*DF');
+%     D2a = +2*(Dv'*Dv)/F + (DF' * DF)/F^2;
 end
 
 Da = Da + DK*v+K*Dv;
-if nargout>3
+if nargout>4
     
     D2a = D2a + D2K*v;
     for j=1:k,
@@ -121,7 +126,7 @@ if notsteady,
             DP1(:,:,j)=DP(:,:,j) - (DP(:,Z,j))*K'-PZ*DK(:,j)';
         end
     end
-    if nargout>3,
+    if nargout>4,
         if Zflag,
             for j=1:k,
                 D2P = D2P;
diff --git a/matlab/kalman/likelihood/univariate_kalman_filter.m b/matlab/kalman/likelihood/univariate_kalman_filter.m
index d5efcb0a78a8f4c10518299b00d77513d2f4474e..acc3fec818bf53e89fb1fd3204cc7641b698bbce 100644
--- a/matlab/kalman/likelihood/univariate_kalman_filter.m
+++ b/matlab/kalman/likelihood/univariate_kalman_filter.m
@@ -77,7 +77,7 @@ function [LIK, lik,a,P] = univariate_kalman_filter(data_index,number_of_observat
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2004-2011 Dynare Team
+% Copyright (C) 2004-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -119,6 +119,7 @@ notsteady = 1;
 
 oldK = Inf;
 K = NaN(mm,pp);
+asy_hess=0;
 
 if  analytic_derivation == 0,
     DLIK=[];
@@ -127,6 +128,7 @@ else
     k = size(DT,3);                                 % number of structural parameters
     DLIK  = zeros(k,1);                             % Initialization of the score.
     Da    = zeros(mm,k);                            % Derivative State vector.
+    dlik  = zeros(smpl,k);
     
     if Zflag==0,
         C = zeros(pp,mm);
@@ -140,11 +142,15 @@ else
         D2a    = zeros(mm,k,k);                             % State vector.
         d2C = zeros(pp,mm,k,k);
     else
+        asy_hess=D2T;
         Hess=[];
         D2a=[];
         D2T=[];
         D2Yss=[];
     end
+    if asy_hess,
+        Hess  = zeros(k,k);                             % Initialization of the Hessian
+    end
     LIK={inf,DLIK,Hess};
 end
 
@@ -177,14 +183,15 @@ while notsteady && t<=last
                 if analytic_derivation==2,
                     [Da,DP,DLIKt,D2a,D2P, Hesst] = univariate_computeDLIK(k,i,z(i,:),Zflag,prediction_error,Ki,PZ,Fi,Da,DYss,DP,DH(d_index(i),:),notsteady,D2a,D2Yss,D2P);
                 else
-                    [Da,DP,DLIKt] = univariate_computeDLIK(k,i,z(i,:),Zflag,prediction_error,Ki,PZ,Fi,Da,DYss,DP,DH(d_index(i),:),notsteady);
+                    [Da,DP,DLIKt,Hesst] = univariate_computeDLIK(k,i,z(i,:),Zflag,prediction_error,Ki,PZ,Fi,Da,DYss,DP,DH(d_index(i),:),notsteady);
                 end
                 if t>presample
                     DLIK = DLIK + DLIKt;
-                    if analytic_derivation==2,
+                    if analytic_derivation==2 || asy_hess,
                         Hess = Hess + Hesst;
                     end
                 end
+                dlik(s,:)=DLIKt;
             end
             a = a + Ki*prediction_error;
             P = P - PZ*Ki';
@@ -208,19 +215,29 @@ end
 
 % Divide by two.
 lik(1:s) = .5*lik(1:s);
+if analytic_derivation,
+    DLIK = DLIK/2;
+    dlik = dlik/2;
+    if analytic_derivation==2 || asy_hess,
+%         Hess = (Hess + Hess')/2;
+        Hess = -Hess/2;
+    end
+end
 
 % Call steady state univariate kalman filter if needed.
 if t <= last
     if analytic_derivation,
         if analytic_derivation==2,
-            [tmp, lik(s+1:end)] = univariate_kalman_filter_ss(Y,t,last,a,P,kalman_tol,T,H,Z,pp,Zflag, ...
+            [tmp, tmp2] = univariate_kalman_filter_ss(Y,t,last,a,P,kalman_tol,T,H,Z,pp,Zflag, ...
                 analytic_derivation,Da,DT,DYss,DP,DH,D2a,D2T,D2Yss,D2P);
         else
-            [tmp, lik(s+1:end)] = univariate_kalman_filter_ss(Y,t,last,a,P,kalman_tol,T,H,Z,pp,Zflag, ...
-                analytic_derivation,Da,DT,DYss,DP,DH);
+            [tmp, tmp2] = univariate_kalman_filter_ss(Y,t,last,a,P,kalman_tol,T,H,Z,pp,Zflag, ...
+                analytic_derivation,Da,DT,DYss,DP,DH,asy_hess);
         end
+        lik(s+1:end)=tmp2{1};
+        dlik(s+1:end,:)=tmp2{2};
         DLIK = DLIK + tmp{2};
-        if analytic_derivation==2,
+        if analytic_derivation==2 || asy_hess,
             Hess = Hess + tmp{3};
         end
     else
@@ -236,11 +253,10 @@ else
 end
 
 if analytic_derivation,
-    DLIK = DLIK/2;
-    if analytic_derivation==2,
-        Hess = -Hess/2;
+    if analytic_derivation==2 || asy_hess,
         LIK={LIK, DLIK, Hess};
     else
         LIK={LIK, DLIK};
     end
+    lik={lik, dlik};
 end
diff --git a/matlab/kalman/likelihood/univariate_kalman_filter_d.m b/matlab/kalman/likelihood/univariate_kalman_filter_d.m
index ae5b2baaf2322f8d723bb3063d36cc4d3b2f6072..e983fd820d74c00f5f9b476d41a2c07494d4fd99 100644
--- a/matlab/kalman/likelihood/univariate_kalman_filter_d.m
+++ b/matlab/kalman/likelihood/univariate_kalman_filter_d.m
@@ -81,7 +81,7 @@ function [dLIK, dlikk, a, Pstar, llik] = univariate_kalman_filter_d(data_index,
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2004-2011 Dynare Team
+% Copyright (C) 2004-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/kalman/likelihood/univariate_kalman_filter_ss.m b/matlab/kalman/likelihood/univariate_kalman_filter_ss.m
index 5747b0870e78c40688dc45a16bd2d274918cdac7..9b48bcef3d4acbdb1a9ec47e79b83a14b52dc24d 100644
--- a/matlab/kalman/likelihood/univariate_kalman_filter_ss.m
+++ b/matlab/kalman/likelihood/univariate_kalman_filter_ss.m
@@ -55,7 +55,7 @@ function [LIK,likk,a] = univariate_kalman_filter_ss(Y,start,last,a,P,kalman_tol,
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -82,6 +82,7 @@ t    = start;              % Initialization of the time index.
 likk = zeros(smpl,1);      % Initialization of the vector gathering the densities.
 LIK  = Inf;                % Default value of the log likelihood.
 l2pi = log(2*pi);
+asy_hess=0;
 
 if nargin<12
     analytic_derivation = 0;
@@ -93,10 +94,16 @@ if  analytic_derivation == 0,
 else
     k = size(DT,3);                                 % number of structural parameters
     DLIK  = zeros(k,1);                             % Initialization of the score.
+    dlikk = zeros(smpl,k);
     if analytic_derivation==2,
         Hess  = zeros(k,k);                             % Initialization of the Hessian
     else
-        Hess=[];
+        asy_hess=D2a;
+        if asy_hess,
+            Hess  = zeros(k,k);                             % Initialization of the Hessian
+        else
+            Hess=[];
+        end
     end
 end
 
@@ -129,12 +136,13 @@ while t<=last
                 if analytic_derivation==2,
                     [Da,DPP,DLIKt,D2a,D2PP, Hesst] = univariate_computeDLIK(k,i,Z(i,:),Zflag,prediction_error,Ki,PPZ,Fi,Da,DYss,DPP,DH(i,:),0,D2a,D2Yss,D2PP);
                 else
-                    [Da,DPP,DLIKt] = univariate_computeDLIK(k,i,Z(i,:),Zflag,prediction_error,Ki,PPZ,Fi,Da,DYss,DPP,DH(i,:),0);
+                    [Da,DPP,DLIKt,Hesst] = univariate_computeDLIK(k,i,Z(i,:),Zflag,prediction_error,Ki,PPZ,Fi,Da,DYss,DPP,DH(i,:),0);
                 end
                 DLIK = DLIK + DLIKt;
-                if analytic_derivation==2,
+                if analytic_derivation==2 || asy_hess,
                     Hess = Hess + Hesst;
                 end
+                dlikk(s,:)=DLIKt;
             end
         end
     end
@@ -152,9 +160,15 @@ end
 likk = .5*likk;
 
 LIK = sum(likk);
-if analytic_derivation==2,
-    LIK={LIK,DLIK,Hess};
+if analytic_derivation,
+    dlikk = dlikk/2;
+    DLIK = DLIK/2;
+    likk = {likk, dlikk};
 end
-if analytic_derivation==1,
+if analytic_derivation==2 || asy_hess,
+%     Hess = (Hess + Hess')/2;
+    Hess = -Hess/2;
+    LIK={LIK,DLIK,Hess};
+elseif analytic_derivation==1,
     LIK={LIK,DLIK};
 end
\ No newline at end of file
diff --git a/matlab/lnsrch1_wrapper_one_boundary.m b/matlab/lnsrch1_wrapper_one_boundary.m
index dd5eb0e4d457f107175b69b4b9faaad30c522a59..22485104681cb7639e1fc975cc48365bebe2984c 100644
--- a/matlab/lnsrch1_wrapper_one_boundary.m
+++ b/matlab/lnsrch1_wrapper_one_boundary.m
@@ -21,7 +21,7 @@ function r = lnsrch1_wrapper_one_boundary(ya, y_index, fname, y, x, params, stea
 %   none.
 %  
 
-% Copyright (C) 2009 Dynare Team
+% Copyright (C) 2009-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/lnsrch1_wrapper_two_boundaries.m b/matlab/lnsrch1_wrapper_two_boundaries.m
index 51c8a4a99b97348fe1316e3178c3496043f3f45c..5f4fd356d46f37ea82b40dc9b868fa51b0a669b4 100644
--- a/matlab/lnsrch1_wrapper_two_boundaries.m
+++ b/matlab/lnsrch1_wrapper_two_boundaries.m
@@ -26,7 +26,7 @@ function ra = lnsrch1_wrapper_two_boundaries(ya, fname, y, y_index, x, ...
 %   none.
 %  
 
-% Copyright (C) 2009 Dynare Team
+% Copyright (C) 2009-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/logarithmic_reduction.m b/matlab/logarithmic_reduction.m
new file mode 100644
index 0000000000000000000000000000000000000000..4d7d0d1329caada83cc9ce179a58a0dd39445c80
--- /dev/null
+++ b/matlab/logarithmic_reduction.m
@@ -0,0 +1,96 @@
+function [X1, info] = logarithmic_reduction(A,B,C,tol,maxit,check)
+
+%@info:
+%! @deftypefn {Function File} {[@var{X1}, @var{info}] =} logarithmic_reduction (@var{A},@var{B},@var{C},@var{tol},@var{maxit},@var{check})
+%! @anchor{logarithmic_reduction}
+%! @sp 1
+%! Solves the quadratic matrix equation AX^2 + BX + C = 0.
+%! @sp 2
+%! @strong{Inputs}
+%! @sp 1
+%! @table @ @var
+%! @item A
+%! Square matrix of doubles, n*n.
+%! @item B
+%! Square matrix of doubles, n*n.
+%! @item C
+%! Square matrix of doubles, n*n.
+%! @item tol
+%! Scalar double, tolerance parameter.
+%! @item maxit
+%! Scalar integer, maximum number of iterations.
+%! @item check
+%! Scalar integer, if non zero the solution is checked.
+%! @end table
+%! @sp 1
+%! @strong{Outputs}
+%! @sp 1
+%! @table @ @var
+%! @item X1
+%! Square matrix of doubles, n*n, solution of the matrix equation.
+%! @item info
+%! Scalar integer, if nonzero the algorithm failed in finding the solution of the matrix equation.
+%! @end table
+%! @sp 2
+%! @strong{This function is called by:}
+%! @sp 2
+%! @strong{This function calls:}
+%! @sp 2
+%! @strong{References:}
+%! @sp 1
+%! G. Latouche and V. Ramaswami (1993), "A logarithmic reduction algorithm for Quasi-Birth-Death processes", in Journal of Applied Probability, Vol. 30, No. 3, pp. 650-674.
+%! @sp 2
+%! @end deftypefn
+%@eod:
+
+% Copyright (C) 2012 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/>.
+
+info = 0;
+
+n = length(A);
+i = 1:n;
+
+tmp0 = -B\[A,C];
+
+X0 = tmp0(:,n+i);
+U0 = tmp0(:,i);
+
+kk = 0;
+cc = 1;
+
+while cc>tol && kk<=maxit
+    tmp1 = (eye(n)-tmp0*[tmp0(:,n+i);tmp0(:,i)])\[tmp0(:,i)*tmp0(:,i),tmp0(:,n+i)*tmp0(:,n+i)];
+    X1 = X0 + U0*tmp1(:,n+i);
+    U1 = U0*tmp1(:,i);
+    cc = max(max(abs(X1-X0)));
+    X0 = X1; U0 = U1;
+    tmp0 = tmp1;
+    kk = kk+1;
+end
+
+if kk==maxit
+    disp(['logarithmic_reduction:: Convergence not achieved after ' int2str(maxit) ' iterations!']);
+    info = 1;
+end
+
+if nargin>5 && check
+    if max(max(abs(A*X1*X1 + B*X1 + C)))>tol
+        disp(['logarithmic_reduction:: Algotithm did not converge to the solution of the matrix quadratic equation!']);
+        info = 1;
+    end
+end
\ No newline at end of file
diff --git a/matlab/lpdfgam.m b/matlab/lpdfgam.m
index 1246f2a9e9586bda1933ba0c52660a31e7dde15f..03728445669e9c894a46b86ef2be196ce6cee03a 100644
--- a/matlab/lpdfgam.m
+++ b/matlab/lpdfgam.m
@@ -13,7 +13,7 @@ function  [ldens,Dldens,D2ldens] = lpdfgam(x,a,b);
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2009 Dynare Team
+% Copyright (C) 2003-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/lpdfgbeta.m b/matlab/lpdfgbeta.m
index 27a3c7fde7a17a4f77e2692ccac9e5a1b64ad4cc..cb6967f6bcd3ccfcd098524e6e99e542cb35f7fb 100644
--- a/matlab/lpdfgbeta.m
+++ b/matlab/lpdfgbeta.m
@@ -14,7 +14,7 @@ function [ldens,Dldens,D2ldens] = lpdfgbeta(x,a,b,aa,bb);
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2009 Dynare Team
+% Copyright (C) 2003-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/lpdfig1.m b/matlab/lpdfig1.m
index c0bb8ff770ff0b8994d5a444a197ac71405cdeab..5aeb05f90c95e5352b42d608fe6075e579e9b752 100644
--- a/matlab/lpdfig1.m
+++ b/matlab/lpdfig1.m
@@ -17,7 +17,7 @@ function [ldens,Dldens,D2ldens] = lpdfig1(x,s,nu)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2004-2009 Dynare Team
+% Copyright (C) 2004-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/lpdfig2.m b/matlab/lpdfig2.m
index 63e458db000ac9759a0c5d77f852af751e16b6ea..00de3abb12746e3396812d651d6216af2a460369 100644
--- a/matlab/lpdfig2.m
+++ b/matlab/lpdfig2.m
@@ -17,7 +17,7 @@ function [ldens,Dldens,D2ldens] = lpdfig2(x,s,nu)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2004-2009 Dynare Team
+% Copyright (C) 2004-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/lpdfnorm.m b/matlab/lpdfnorm.m
index 9afdd2b6df2076e4210793049e29164f948c4482..bb9da98d8e64ff4f522bda0feba1867e6e73bcb8 100644
--- a/matlab/lpdfnorm.m
+++ b/matlab/lpdfnorm.m
@@ -13,7 +13,7 @@ function  [ldens,Dldens,D2ldens] = lpdfnorm(x,a,b)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2009 Dynare Team
+% Copyright (C) 2003-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -35,9 +35,9 @@ if nargin<2, a=0; end
 ldens = -log(b) -.5*log(2*pi) - .5*((x-a)./b).*((x-a)./b) ;
 
 if nargout >1 
-    Dldens =  - (1/b)*((x-a)/b) ;
+    Dldens =  - (1./b).*((x-a)./b) ;
 end
 
 if nargout == 3 
-    D2ldens =  - (1/b)^2 ;
+    D2ldens =  - (1./b).^2 ;
 end
\ No newline at end of file
diff --git a/matlab/lyapunov_symm.m b/matlab/lyapunov_symm.m
index 93913d335d4253da76f4da0b33d04d6188f6cd16..e23323f77b7634fce692e3004a5e5520d668520f 100644
--- a/matlab/lyapunov_symm.m
+++ b/matlab/lyapunov_symm.m
@@ -26,7 +26,7 @@ function [x,u] = lyapunov_symm(a,b,third_argument,lyapunov_complex_threshold,met
 % SPECIAL REQUIREMENTS
 %   None
 
-% Copyright (C) 2006-2010 Dynare Team
+% Copyright (C) 2006-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/make_ex_.m b/matlab/make_ex_.m
index 7aea8071ee9d1bda559c535dd7af0e3282d791eb..9665b2a0cb2939ffee8ce6e427441ee4c2a42e8b 100644
--- a/matlab/make_ex_.m
+++ b/matlab/make_ex_.m
@@ -1,4 +1,4 @@
-function make_ex_
+function make_ex_()
 % forms oo_.exo_simul and oo_.exo_det_simul
 %
 % INPUTS
@@ -12,7 +12,7 @@ function make_ex_
 % SPECIAL REQUIREMENTS
 %  
 
-% Copyright (C) 1996-2011 Dynare Team
+% Copyright (C) 1996-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/make_y_.m b/matlab/make_y_.m
index 914f37d346fbe7f428b3ba9afc40d380705d3dc8..f7f3a88380f9d7384ea046a264dc5d1ae74747ff 100644
--- a/matlab/make_y_.m
+++ b/matlab/make_y_.m
@@ -1,4 +1,4 @@
-function make_y_
+function make_y_()
 % function make_y_
 % forms oo_.endo_simul as guess values for deterministic simulations
 %  
@@ -12,7 +12,7 @@ function make_y_
 %   none
 %  
 
-% Copyright (C) 1996-2009 Dynare Team
+% Copyright (C) 1996-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/metropolis_draw.m b/matlab/metropolis_draw.m
index 86fce488ec55bd25903fd2ef0375a15776d0f197..9165047f1199fefe530bee884c3e7a444183ced3 100644
--- a/matlab/metropolis_draw.m
+++ b/matlab/metropolis_draw.m
@@ -12,7 +12,7 @@ function [xparams, logpost]=metropolis_draw(init)
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2003-2009 Dynare Team
+% Copyright (C) 2003-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/metropolis_run_analysis.m b/matlab/metropolis_run_analysis.m
index dbb98b8bc950ef6f699e6ee933931ff1b54d0f75..99b589c820b0d2a2aeb086ea7654266650ab29a6 100644
--- a/matlab/metropolis_run_analysis.m
+++ b/matlab/metropolis_run_analysis.m
@@ -13,7 +13,7 @@ function metropolis_run_analysis(M,basetopt,j)
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2003-2009, 2010, 2011 Dynare Team
+% Copyright (C) 2003-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/mh_autocorrelation_function.m b/matlab/mh_autocorrelation_function.m
index a77506578b9ddaf3a5c73155c03c94af2f87eb2c..7b4858a10245159e5fc82f4750b4ba3eabfa50a5 100644
--- a/matlab/mh_autocorrelation_function.m
+++ b/matlab/mh_autocorrelation_function.m
@@ -18,7 +18,7 @@ function mh_autocorrelation_function(options_,M_,estim_params_,type,blck,name1,n
 %        
 % SPECIAL REQUIREMENTS
 
-% Copyright (C) 2003-2009 Dynare Team
+% Copyright (C) 2003-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/missing/linsolve/linsolve.m b/matlab/missing/linsolve/linsolve.m
new file mode 100644
index 0000000000000000000000000000000000000000..2ae167bd4455b97020a3ae46ee3d113f5ea0e238
--- /dev/null
+++ b/matlab/missing/linsolve/linsolve.m
@@ -0,0 +1,33 @@
+function [x,c] = linsolve(A,B,opts)
+% (very imperfect) Clone of Matlab's linsolve.
+
+% Copyright (C) 2010-2011 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/>.
+
+    c = [];
+    x = [];
+    if nargin == 3
+        if isfield(opts,'TRANSA')
+            A = A';
+        end
+    end
+    if nargout == 2
+        c = rcond(A);
+    end
+    
+    x = A\B;
+    
diff --git a/matlab/mode_check.m b/matlab/mode_check.m
index e827c4b2d7067e871a9d7ad8199c3c46bb6a786f..4bab74446abe034d812545335c29bd7b70e469b6 100644
--- a/matlab/mode_check.m
+++ b/matlab/mode_check.m
@@ -40,7 +40,7 @@ function mode_check(fun,x,hessian,DynareDataset,DynareOptions,Model,EstimatedPar
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2003-2010, 2012 Dynare Team
+% Copyright (C) 2003-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/model_diagnostics.m b/matlab/model_diagnostics.m
index 7ff07f471e6dc5a47854256a9a432ee434d1c62e..3118bb2defd21ba17b461dd49eeb680db8c5af57 100644
--- a/matlab/model_diagnostics.m
+++ b/matlab/model_diagnostics.m
@@ -16,7 +16,7 @@ function model_diagnostics(M,options,oo)
 %   none.
 %  
 
-% Copyright (C) 1996-2011 Dynare Team
+% Copyright (C) 1996-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/model_info.m b/matlab/model_info.m
index e67923b0045993df7f4466f6ddb82202cf532864..d99ca48078556c0b21d07cfa4ce9dc0ea2106159 100644
--- a/matlab/model_info.m
+++ b/matlab/model_info.m
@@ -1,7 +1,7 @@
 function model_info(varargin);
 %function model_info;
 
-% Copyright (C) 2008-2010 Dynare Team
+% Copyright (C) 2008-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -19,39 +19,56 @@ function model_info(varargin);
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 global M_;
-fprintf('                                          Informations about %s\n',M_.fname);
-fprintf(strcat('                                          ===================',char(ones(1,length(M_.fname))*'='),'\n\n'));
-if(isfield(M_,'block_structure'))
-    nb_blocks=length(M_.block_structure.block);
+if sum(strcmp(varargin,'static')) > 0
+    static_ = 1;
+else
+    static_ = 0;
+end;
+if sum(strcmp(varargin,'incidence')) > 0
+    incidence = 1;
+else
+    incidence = 0;
+end;
+if static_
+        fprintf('                                          Informations about %s (static model)\n',M_.fname);
+        block_structre_str = 'block_structure_stat';
+        nb_leadlag = 1;
+    else
+        fprintf('                                          Informations about %s (dynamic model)\n',M_.fname);
+        block_structre_str = 'block_structure';
+        nb_leadlag = 3;
+    end;
+if(isfield(M_,block_structre_str))
+    if static_
+        block_structure = M_.block_structure_stat;
+    else
+        block_structure = M_.block_structure;
+    end;
+    fprintf(strcat('                                          ===================',char(ones(1,length(M_.fname))*'='),'\n\n'));
+    nb_blocks=length(block_structure.block);
     fprintf('The model has %d equations and is decomposed in %d blocks as follow:\n',M_.endo_nbr,nb_blocks);
     fprintf('===============================================================================================================\n');
     fprintf('| %10s | %10s | %30s | %14s | %31s |\n','Block no','Size','Block Type','   Equation','Dependent variable');
     fprintf('|============|============|================================|================|=================================|\n');
     for i=1:nb_blocks
-        size_block=length(M_.block_structure.block(i).equation);
+        size_block=length(block_structure.block(i).equation);
         if(i>1)
             fprintf('|------------|------------|--------------------------------|----------------|---------------------------------|\n');
         end;
         for j=1:size_block
             if(j==1)
-                fprintf('| %10d | %10d | %30s | %14d | %-6d %24s |\n',i,size_block,Sym_type(M_.block_structure.block(i).Simulation_Type),M_.block_structure.block(i).equation(j),M_.block_structure.block(i).variable(j),M_.endo_names(M_.block_structure.block(i).variable(j),:));
+                fprintf('| %10d | %10d | %30s | %14d | %-6d %24s |\n',i,size_block,Sym_type(block_structure.block(i).Simulation_Type),block_structure.block(i).equation(j),block_structure.block(i).variable(j),M_.endo_names(block_structure.block(i).variable(j),:));
             else
-                fprintf('| %10s | %10s | %30s | %14d | %-6d %24s |\n','','','',M_.block_structure.block(i).equation(j),M_.block_structure.block(i).variable(j),M_.endo_names(M_.block_structure.block(i).variable(j),:));
+                fprintf('| %10s | %10s | %30s | %14d | %-6d %24s |\n','','','',block_structure.block(i).equation(j),block_structure.block(i).variable(j),M_.endo_names(block_structure.block(i).variable(j),:));
             end;
         end;
     end;
     fprintf('===============================================================================================================\n');
     fprintf('\n');
-    for k=1:M_.maximum_endo_lag+M_.maximum_endo_lead+1
-        if(k==M_.maximum_endo_lag+1)
-            fprintf('%-30s %s','the variable','is used in equations Contemporaneously');
-        elseif(k<M_.maximum_endo_lag+1)
-            fprintf('%-30s %s %d','the variable','is used in equations with lag ',M_.maximum_endo_lag+1-k);
-        else
-            fprintf('%-30s %s %d','the variable','is used in equations with lead ',k-(M_.maximum_endo_lag+1));
-        end;
-        if(size(M_.block_structure.incidence(k).sparse_IM,1)>0)
-            IM=sortrows(M_.block_structure.incidence(k).sparse_IM,2);
+    if static_
+        fprintf('%-30s %s','the variable','is used in equations Contemporaneously');
+        if(size(block_structure.incidence.sparse_IM,1)>0)
+            IM=sortrows(block_structure.incidence.sparse_IM,2);
         else
             IM=[];
         end;
@@ -65,17 +82,42 @@ if(isfield(M_,'block_structure'))
             last=IM(i,2);
         end;
         fprintf('\n\n');
+    else
+        for k=1:M_.maximum_endo_lag+M_.maximum_endo_lead+1
+            if(k==M_.maximum_endo_lag+1)
+                fprintf('%-30s %s','the variable','is used in equations Contemporaneously');
+            elseif(k<M_.maximum_endo_lag+1)
+                fprintf('%-30s %s %d','the variable','is used in equations with lag ',M_.maximum_endo_lag+1-k);
+            else
+                fprintf('%-30s %s %d','the variable','is used in equations with lead ',k-(M_.maximum_endo_lag+1));
+            end;
+            if(size(block_structure.incidence(k).sparse_IM,1)>0)
+                IM=sortrows(block_structure.incidence(k).sparse_IM,2);
+            else
+                IM=[];
+            end;
+            size_IM=size(IM,1);
+            last=99999999;
+            for i=1:size_IM
+                if(last~=IM(i,2))
+                    fprintf('\n%-30s',M_.endo_names(IM(i,2),:));
+                end;
+                fprintf(' %5d',IM(i,1));
+                last=IM(i,2);
+            end;
+            fprintf('\n\n');
+        end;
     end;
     
     %printing the gross incidence matrix
     IM_star = char([kron(ones(M_.endo_nbr, M_.endo_nbr-1), double(blanks(3))) double(blanks(M_.endo_nbr)')]);
-    for i = 1:3
-        n = size(M_.block_structure.incidence(i).sparse_IM,1);
+    for i = 1:nb_leadlag
+        n = size(block_structure.incidence(i).sparse_IM,1);
         for j = 1:n
-            if ismember(M_.block_structure.incidence(i).sparse_IM(j,2), M_.state_var)
-                IM_star(M_.block_structure.incidence(i).sparse_IM(j,1), 3 * (M_.block_structure.incidence(i).sparse_IM(j,2) - 1) + 1) = 'X';
+            if ismember(block_structure.incidence(i).sparse_IM(j,2), M_.state_var)
+                IM_star(block_structure.incidence(i).sparse_IM(j,1), 3 * (block_structure.incidence(i).sparse_IM(j,2) - 1) + 1) = 'X';
             else
-                IM_star(M_.block_structure.incidence(i).sparse_IM(j,1), 3 * (M_.block_structure.incidence(i).sparse_IM(j,2) - 1) + 1) = '1';
+                IM_star(block_structure.incidence(i).sparse_IM(j,1), 3 * (block_structure.incidence(i).sparse_IM(j,2) - 1) + 1) = '1';
             end;
         end;
     end;
@@ -88,7 +130,7 @@ if(isfield(M_,'block_structure'))
             var_names = [var_names; blank; M_.endo_names(i,:)];
         end;
     end;
-    if nargin == 1 && strcmp(varargin{1},'incidence')
+    if incidence
         topp = [char(kron(double(blanks(ceil(log10(M_.endo_nbr)))),ones(size(M_.endo_names,2),1))) var_names' ];
         bott = [int2str(seq') blanks(M_.endo_nbr)' blanks(M_.endo_nbr)' IM_star];
         fprintf('\n                                          Gross incidence matrix\n');
@@ -97,42 +139,42 @@ if(isfield(M_,'block_structure'))
     
         %printing the reordered incidence matrix
         IM_star_reordered = char([kron(ones(M_.endo_nbr, M_.endo_nbr-1), double(blanks(3))) double(blanks(M_.endo_nbr)')]);
-        eq(M_.block_structure.equation_reordered) = seq;
-        va(M_.block_structure.variable_reordered) = seq;
+        eq(block_structure.equation_reordered) = seq;
+        va(block_structure.variable_reordered) = seq;
         barre_blank = [ barre(size(M_.endo_names,2)); blanks(size(M_.endo_names,2))];
         cur_block = 1;
         for i = 1:M_.endo_nbr
             past_block = cur_block;
-            while ismember(M_.block_structure.variable_reordered(i), M_.block_structure.block(cur_block).variable) == 0;
+            while ismember(block_structure.variable_reordered(i), block_structure.block(cur_block).variable) == 0;
                 cur_block = cur_block + 1;
             end;
             if i == 1
-                var_names = [blank; M_.endo_names(M_.block_structure.variable_reordered(i),:)];
+                var_names = [blank; M_.endo_names(block_structure.variable_reordered(i),:)];
             else
                 if past_block ~= cur_block
-                    var_names = [var_names; barre_blank; M_.endo_names(M_.block_structure.variable_reordered(i),:)];
+                    var_names = [var_names; barre_blank; M_.endo_names(block_structure.variable_reordered(i),:)];
                 else
-                    var_names = [var_names; blank; M_.endo_names(M_.block_structure.variable_reordered(i),:)];
+                    var_names = [var_names; blank; M_.endo_names(block_structure.variable_reordered(i),:)];
                 end
             end;
         end;
         topp = [char(kron(double(blanks(ceil(log10(M_.endo_nbr)))),ones(size(M_.endo_names,2),1))) var_names' ];
         n_state_var = length(M_.state_var);
         IM_state_var = zeros(n_state_var, n_state_var);
-        inv_variable_reordered(M_.block_structure.variable_reordered) = 1:M_.endo_nbr;
-        state_equation = M_.block_structure.equation_reordered(inv_variable_reordered(M_.state_var));
-        for i = 1:3
-            n = size(M_.block_structure.incidence(i).sparse_IM,1);
+        inv_variable_reordered(block_structure.variable_reordered) = 1:M_.endo_nbr;
+        state_equation = block_structure.equation_reordered(inv_variable_reordered(M_.state_var));
+        for i = 1:nb_leadlag
+            n = size(block_structure.incidence(i).sparse_IM,1);
             for j = 1:n
-                [tf, loc] = ismember(M_.block_structure.incidence(i).sparse_IM(j,2), M_.state_var);
+                [tf, loc] = ismember(block_structure.incidence(i).sparse_IM(j,2), M_.state_var);
                 if tf
-                    IM_star_reordered(eq(M_.block_structure.incidence(i).sparse_IM(j,1)), 3 * (va(M_.block_structure.incidence(i).sparse_IM(j,2)) - 1) + 1) = 'X';
-                    [tfi, loci] = ismember(M_.block_structure.incidence(i).sparse_IM(j,1), state_equation);
+                    IM_star_reordered(eq(block_structure.incidence(i).sparse_IM(j,1)), 3 * (va(block_structure.incidence(i).sparse_IM(j,2)) - 1) + 1) = 'X';
+                    [tfi, loci] = ismember(block_structure.incidence(i).sparse_IM(j,1), state_equation);
                     if tfi
                         IM_state_var(loci, loc) = 1;
                     end;
                 else
-                    IM_star_reordered(eq(M_.block_structure.incidence(i).sparse_IM(j,1)), 3 * (va(M_.block_structure.incidence(i).sparse_IM(j,2)) - 1) + 1) = '1';
+                    IM_star_reordered(eq(block_structure.incidence(i).sparse_IM(j,1)), 3 * (va(block_structure.incidence(i).sparse_IM(j,2)) - 1) + 1) = '1';
                 end;
             end;
         end;
@@ -143,7 +185,7 @@ if(isfield(M_,'block_structure'))
         block = {};
         for i = 1:n_state_var;
             past_block = cur_block;
-            while ismember(M_.state_var(i), M_.block_structure.block(cur_block).variable) == 0;
+            while ismember(M_.state_var(i), block_structure.block(cur_block).variable) == 0;
                 cur_block = cur_block + 1;
             end;
             if (past_block ~= cur_block) || (past_block == cur_block && i == n_state_var)
@@ -154,7 +196,7 @@ if(isfield(M_,'block_structure'))
         cur_block = 1;
         for i = 1:M_.endo_nbr
             past_block = cur_block;
-            while ismember(M_.block_structure.variable_reordered(i), M_.block_structure.block(cur_block).variable) == 0;
+            while ismember(block_structure.variable_reordered(i), block_structure.block(cur_block).variable) == 0;
                 cur_block = cur_block + 1;
             end;
             if past_block ~= cur_block
@@ -164,7 +206,7 @@ if(isfield(M_,'block_structure'))
             end;
         end
         
-        bott = [int2str(M_.block_structure.equation_reordered') blanks(M_.endo_nbr)' blanks(M_.endo_nbr)' IM_star_reordered];
+        bott = [int2str(block_structure.equation_reordered') blanks(M_.endo_nbr)' blanks(M_.endo_nbr)' IM_star_reordered];
         fprintf('\n                                          Reordered incidence matrix\n');
         fprintf('                                          ==========================\n');
         disp([topp; bott]);
diff --git a/matlab/moment_function.m b/matlab/moment_function.m
index c3f414fa18373c68326b1de876e95019a3c8784f..af0488a594da38a1454019e6faff2b6195b6c6c3 100644
--- a/matlab/moment_function.m
+++ b/matlab/moment_function.m
@@ -15,7 +15,7 @@ function [g,grad,hess,flag] = moment_function(xparams,sample_moments,dataset,opt
 % SPECIAL REQUIREMENTS
 %  The user has to provide a file where the moment conditions are defined.
 
-% Copyright (C) 2010 Dynare Team
+% Copyright (C) 2010-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/mr_gstep.m b/matlab/mr_gstep.m
index 381b21fa0b25565fcd20dee56a06182235b53e03..690ffa01bd57d7f3513ba2853afac4fc5026f42c 100644
--- a/matlab/mr_gstep.m
+++ b/matlab/mr_gstep.m
@@ -3,7 +3,7 @@ function [f0, x, ig] = mr_gstep(h1,x,func0,htol0,DynareDataset,DynareOptions,Mod
 %
 % Gibbs type step in optimisation
 
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -21,6 +21,10 @@ function [f0, x, ig] = mr_gstep(h1,x,func0,htol0,DynareDataset,DynareOptions,Mod
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 n=size(x,1);
+if isempty(h1),
+    h1=DynareOptions.gradient_epsilon*ones(n,1);
+end
+
 
 if isempty(htol0)
     htol = 1.e-6;
diff --git a/matlab/mr_hessian.m b/matlab/mr_hessian.m
index 99149969f682daf80336388d81ca20c73ec5ddd3..0b059d9d6a0db5a13d56477e6535537e9700c4b2 100644
--- a/matlab/mr_hessian.m
+++ b/matlab/mr_hessian.m
@@ -11,7 +11,7 @@ function [hessian_mat, gg, htol1, ihh, hh_mat0, hh1] = mr_hessian(init,x,func,hf
 %    of the log-likelihood to compute outer product gradient
 %  x = parameter values
 %  hflag = 0, Hessian computed with outer product gradient, one point
-%  increments for partial derivatives in  gradients
+%  increments for partial derivatives in gradients
 %  hflag = 1, 'mixed' Hessian: diagonal elements computed with numerical second order derivatives
 %             with correlation structure as from outer product gradient;
 %             two point evaluation of derivatives for partial derivatives
@@ -24,7 +24,7 @@ function [hessian_mat, gg, htol1, ihh, hh_mat0, hh1] = mr_hessian(init,x,func,hf
 %
 %  varargin: other parameters of func
 
-% Copyright (C) 2004-2011 Dynare Team
+% Copyright (C) 2004-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -55,6 +55,12 @@ end
 h2=BayesInfo.ub-BayesInfo.lb;
 hmax=BayesInfo.ub-x;
 hmax=min(hmax,x-BayesInfo.lb);
+if isempty(ff0),
+    outer_product_gradient=0;
+else
+    outer_product_gradient=1;
+end
+
 
 h1 = min(h1,0.5.*hmax);
 
@@ -64,9 +70,11 @@ end
 xh1=x;
 f1=zeros(size(f0,1),n);
 f_1=f1;
-ff1=zeros(size(ff0));
-ff_1=ff1;
-ggh=zeros(size(ff0,1),n);
+if outer_product_gradient
+    ff1=zeros(size(ff0));
+    ff_1=ff1;
+    ggh=zeros(size(ff0,1),n);
+end
 
 i=0;
 while i<n
@@ -124,20 +132,24 @@ while i<n
         end
     end
     f1(:,i)=fx;
-    if any(isnan(ffx))
-        ff1=ones(size(ff0)).*fx/length(ff0);
-    else
-        ff1=ffx;
+    if outer_product_gradient,
+        if any(isnan(ffx))
+            ff1=ones(size(ff0)).*fx/length(ff0);
+        else
+            ff1=ffx;
+        end
     end
     xh1(i)=x(i)-h1(i);
     [fx, ffx]=feval(func,xh1,DynareDataset,DynareOptions,Model,EstimatedParameters,BayesInfo,DynareResults);
     f_1(:,i)=fx;
-    if any(isnan(ffx))
-        ff_1=ones(size(ff0)).*fx/length(ff0);
-    else
-        ff_1=ffx;
+    if outer_product_gradient,
+        if any(isnan(ffx))
+            ff_1=ones(size(ff0)).*fx/length(ff0);
+        else
+            ff_1=ffx;
+        end
+        ggh(:,i)=(ff1-ff_1)./(2.*h1(i));
     end
-    ggh(:,i)=(ff1-ff_1)./(2.*h1(i));
     xh1(i)=x(i);
     if hcheck && htol<1
         htol=min(1,max(min(abs(dx))*2,htol*10));
@@ -152,85 +164,93 @@ xh_1=xh1;
 
 gg=(f1'-f_1')./(2.*h1);
 
-if hflag==2
-    gg=(f1'-f_1')./(2.*h1);
-    hessian_mat = zeros(size(f0,1),n*n);
-    for i=1:n
-        if i > 1
-            k=[i:n:n*(i-1)];
-            hessian_mat(:,(i-1)*n+1:(i-1)*n+i-1)=hessian_mat(:,k);
+if outer_product_gradient,
+    if hflag==2
+        gg=(f1'-f_1')./(2.*h1);
+        hessian_mat = zeros(size(f0,1),n*n);
+        for i=1:n
+            if i > 1
+                k=[i:n:n*(i-1)];
+                hessian_mat(:,(i-1)*n+1:(i-1)*n+i-1)=hessian_mat(:,k);
+            end
+            hessian_mat(:,(i-1)*n+i)=(f1(:,i)+f_1(:,i)-2*f0)./(h1(i)*h_1(i));
+            temp=f1+f_1-f0*ones(1,n);
+            for j=i+1:n
+                xh1(i)=x(i)+h1(i);
+                xh1(j)=x(j)+h_1(j);
+                xh_1(i)=x(i)-h1(i);
+                xh_1(j)=x(j)-h_1(j);
+                temp1 = feval(func,xh1,DynareDataset,DynareOptions,Model,EstimatedParameters,BayesInfo,DynareResults);
+                temp2 = feval(func,xh_1,DynareDataset,DynareOptions,Model,EstimatedParameters,BayesInfo,DynareResults);
+                hessian_mat(:,(i-1)*n+j)=-(-temp1 -temp2+temp(:,i)+temp(:,j))./(2*h1(i)*h_1(j));
+                xh1(i)=x(i);
+                xh1(j)=x(j);
+                xh_1(i)=x(i);
+                xh_1(j)=x(j);
+                j=j+1;
+            end
+            i=i+1;
         end
-        hessian_mat(:,(i-1)*n+i)=(f1(:,i)+f_1(:,i)-2*f0)./(h1(i)*h_1(i));
-        temp=f1+f_1-f0*ones(1,n);
-        for j=i+1:n
-            xh1(i)=x(i)+h1(i);
-            xh1(j)=x(j)+h_1(j);
-            xh_1(i)=x(i)-h1(i);
-            xh_1(j)=x(j)-h_1(j);
-            temp1 = feval(func,xh1,DynareDataset,DynareOptions,Model,EstimatedParameters,BayesInfo,DynareResults);
-            temp2 = feval(func,xh_1,DynareDataset,DynareOptions,Model,EstimatedParameters,BayesInfo,DynareResults);
-            hessian_mat(:,(i-1)*n+j)=-(-temp1 -temp2+temp(:,i)+temp(:,j))./(2*h1(i)*h_1(j));
-            xh1(i)=x(i);
-            xh1(j)=x(j);
-            xh_1(i)=x(i);
-            xh_1(j)=x(j);
-            j=j+1;
+    elseif hflag==1
+        hessian_mat = zeros(size(f0,1),n*n);
+        for i=1:n
+            dum = (f1(:,i)+f_1(:,i)-2*f0)./(h1(i)*h_1(i));
+            if dum>eps
+                hessian_mat(:,(i-1)*n+i)=dum;
+            else
+                hessian_mat(:,(i-1)*n+i)=max(eps, gg(i)^2);
+            end
         end
-        i=i+1;
     end
-elseif hflag==1
-    hessian_mat = zeros(size(f0,1),n*n);
-    for i=1:n
-        dum = (f1(:,i)+f_1(:,i)-2*f0)./(h1(i)*h_1(i));
-        if dum>eps
-            hessian_mat(:,(i-1)*n+i)=dum;
-        else
-            hessian_mat(:,(i-1)*n+i)=max(eps, gg(i)^2);
+    
+    gga=ggh.*kron(ones(size(ff1)),2.*h1');  % re-scaled gradient
+    hh_mat=gga'*gga;  % rescaled outer product hessian
+    hh_mat0=ggh'*ggh;  % outer product hessian
+    A=diag(2.*h1);  % rescaling matrix
+    % igg=inv(hh_mat);  % inverted rescaled outer product hessian
+    ihh=A'*(hh_mat\A);  % inverted outer product hessian
+    if hflag>0 && min(eig(reshape(hessian_mat,n,n)))>0
+        hh0 = A*reshape(hessian_mat,n,n)*A';  %rescaled second order derivatives
+        hh = reshape(hessian_mat,n,n);  %rescaled second order derivatives
+        sd0=sqrt(diag(hh0));   %rescaled 'standard errors' using second order derivatives
+        sd=sqrt(diag(hh_mat));  %rescaled 'standard errors' using outer product
+        hh_mat=hh_mat./(sd*sd').*(sd0*sd0');  %rescaled inverse outer product with 'true' std's
+        igg=inv(hh_mat);   % rescaled outer product hessian with 'true' std's
+        ihh=A'*(hh_mat\A);  % inverted outer product hessian
+        hh_mat0=inv(A)'*hh_mat*inv(A);  % outer product hessian with 'true' std's
+        sd=sqrt(diag(ihh));   %standard errors
+        sdh=sqrt(1./diag(hh));   %diagonal standard errors
+        for j=1:length(sd)
+            sd0(j,1)=min(BayesInfo.p2(j), sd(j));  %prior std
+            sd0(j,1)=10^(0.5*(log10(sd0(j,1))+log10(sdh(j,1))));
         end
+        ihh=ihh./(sd*sd').*(sd0*sd0');  %inverse outer product with modified std's
+        igg=inv(A)'*ihh*inv(A);  % inverted rescaled outer product hessian with modified std's
+        hh_mat=inv(igg);   % outer product rescaled hessian with modified std's
+        hh_mat0=inv(A)'*hh_mat*inv(A);  % outer product hessian with modified std's
+        %     sd0=sqrt(1./diag(hh0));   %rescaled 'standard errors' using second order derivatives
+        %     sd=sqrt(diag(igg));  %rescaled 'standard errors' using outer product
+        %     igg=igg./(sd*sd').*(sd0*sd0');  %rescaled inverse outer product with 'true' std's
+        %     hh_mat=inv(igg);   % rescaled outer product hessian with 'true' std's
+        %     ihh=A'*igg*A;  % inverted outer product hessian
+        %     hh_mat0=inv(A)'*hh_mat*inv(A);  % outer product hessian with 'true' std's
     end
-end
-
-gga=ggh.*kron(ones(size(ff1)),2.*h1');  % re-scaled gradient
-hh_mat=gga'*gga;  % rescaled outer product hessian
-hh_mat0=ggh'*ggh;  % outer product hessian
-A=diag(2.*h1);  % rescaling matrix
-% igg=inv(hh_mat);  % inverted rescaled outer product hessian
-ihh=A'*(hh_mat\A);  % inverted outer product hessian
-if hflag>0 && min(eig(reshape(hessian_mat,n,n)))>0
-    hh0 = A*reshape(hessian_mat,n,n)*A';  %rescaled second order derivatives
-    hh = reshape(hessian_mat,n,n);  %rescaled second order derivatives
-    sd0=sqrt(diag(hh0));   %rescaled 'standard errors' using second order derivatives
-    sd=sqrt(diag(hh_mat));  %rescaled 'standard errors' using outer product
-    hh_mat=hh_mat./(sd*sd').*(sd0*sd0');  %rescaled inverse outer product with 'true' std's
-    igg=inv(hh_mat);   % rescaled outer product hessian with 'true' std's
-    ihh=A'*(hh_mat\A);  % inverted outer product hessian
-    hh_mat0=inv(A)'*hh_mat*inv(A);  % outer product hessian with 'true' std's
-    sd=sqrt(diag(ihh));   %standard errors
-    sdh=sqrt(1./diag(hh));   %diagonal standard errors
-    for j=1:length(sd)
-        sd0(j,1)=min(BayesInfo.p2(j), sd(j));  %prior std
-        sd0(j,1)=10^(0.5*(log10(sd0(j,1))+log10(sdh(j,1))));
+    if hflag<2
+        hessian_mat=hh_mat0(:);
     end
-    ihh=ihh./(sd*sd').*(sd0*sd0');  %inverse outer product with modified std's
-    igg=inv(A)'*ihh*inv(A);  % inverted rescaled outer product hessian with modified std's
-    hh_mat=inv(igg);   % outer product rescaled hessian with modified std's
-    hh_mat0=inv(A)'*hh_mat*inv(A);  % outer product hessian with modified std's
-                                    %     sd0=sqrt(1./diag(hh0));   %rescaled 'standard errors' using second order derivatives
-                                    %     sd=sqrt(diag(igg));  %rescaled 'standard errors' using outer product
-                                    %     igg=igg./(sd*sd').*(sd0*sd0');  %rescaled inverse outer product with 'true' std's
-                                    %     hh_mat=inv(igg);   % rescaled outer product hessian with 'true' std's
-                                    %     ihh=A'*igg*A;  % inverted outer product hessian
-                                    %     hh_mat0=inv(A)'*hh_mat*inv(A);  % outer product hessian with 'true' std's
-end
-if hflag<2
-    hessian_mat=hh_mat0(:);
+    
+    if any(isnan(hessian_mat))
+        hh_mat0=eye(length(hh_mat0));
+        ihh=hh_mat0;
+        hessian_mat=hh_mat0(:);
+    end
+    hh1=h1;
+    save hess.mat hessian_mat
+else
+    hessian_mat=[];
+    ihh=[];
+    hh_mat0 = [];
+    hh1 = [];
 end
 
-if any(isnan(hessian_mat))
-    hh_mat0=eye(length(hh_mat0));
-    ihh=hh_mat0;
-    hessian_mat=hh_mat0(:);
-end
-hh1=h1;
 htol1=htol;
-save hess.mat hessian_mat
\ No newline at end of file
diff --git a/matlab/ms-sbvar/ms_estimation.m b/matlab/ms-sbvar/ms_estimation.m
index b08f664930c0c2975ddb39a612fcb4a07963a747..eb28f94340ebf4d3244a7af8135a6c74ffb33091 100644
--- a/matlab/ms-sbvar/ms_estimation.m
+++ b/matlab/ms-sbvar/ms_estimation.m
@@ -14,7 +14,7 @@ function [options_, oo_]=ms_estimation(M_, options_, oo_)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/ms-sbvar/ms_mardd.m b/matlab/ms-sbvar/ms_mardd.m
index 078bd5b924f9cc7d918bc9bf63b95cbc967d62ca..7b83b2453578f11d46fe4b385f7d25af1c5a1b59 100644
--- a/matlab/ms-sbvar/ms_mardd.m
+++ b/matlab/ms-sbvar/ms_mardd.m
@@ -6,7 +6,7 @@ function ms_mardd(options_)
 %
 % Tao Zha, September 1999.  Quick revisions, May 2003.  Final revision, September 2004.
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/ms-sbvar/ms_variance_decomposition.m b/matlab/ms-sbvar/ms_variance_decomposition.m
index 648c89952ad297dd28461c1a13e187be510e102f..57ee893b288ff993af44f59ad9ad237b4756557c 100644
--- a/matlab/ms-sbvar/ms_variance_decomposition.m
+++ b/matlab/ms-sbvar/ms_variance_decomposition.m
@@ -14,7 +14,7 @@ function [options_, oo_]=ms_variance_decomposition(M_, options_, oo_)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/ms-sbvar/ms_write_markov_file.m b/matlab/ms-sbvar/ms_write_markov_file.m
index 46623e72135f1982b3515e1dc4cf0d88758934ff..c04051f62ed81ede835f8051ab346decc4775804 100644
--- a/matlab/ms-sbvar/ms_write_markov_file.m
+++ b/matlab/ms-sbvar/ms_write_markov_file.m
@@ -10,7 +10,7 @@ function ms_write_markov_file(fname, options)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/ms-sbvar/ms_write_mhm_input.m b/matlab/ms-sbvar/ms_write_mhm_input.m
index f9f560135bf2f1cdbf4c94f981deb3c8ab5a291c..57854d59ae3f6958fb3ca785859467f73a2b3f51 100644
--- a/matlab/ms-sbvar/ms_write_mhm_input.m
+++ b/matlab/ms-sbvar/ms_write_mhm_input.m
@@ -11,7 +11,7 @@ function ms_write_mhm_input(fname, options_ms)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/ms-sbvar/msstart2.m b/matlab/ms-sbvar/msstart2.m
index e9dd08f6687c6ff655e5732e5b2907e5929a7de1..2c1ae25242c5e69d859f75e7ae8a36260036a188 100644
--- a/matlab/ms-sbvar/msstart2.m
+++ b/matlab/ms-sbvar/msstart2.m
@@ -12,7 +12,7 @@
 %
 % February 2004
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/ms-sbvar/msstart_setup.m b/matlab/ms-sbvar/msstart_setup.m
index ab43607b395a75bf66df1fd94a756b7209d7b6ea..c7be924519b22a6008b445cdd9812c1acf032898 100644
--- a/matlab/ms-sbvar/msstart_setup.m
+++ b/matlab/ms-sbvar/msstart_setup.m
@@ -1,6 +1,6 @@
 %function []= msstart_setup(options_)
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/ms-sbvar/set_ms_estimation_file.m b/matlab/ms-sbvar/set_ms_estimation_file.m
index 1d105d767be88551e9e415fc94d88fec0b7a4914..38a9ac82d585639d7a7337cb820f0769dbfe0351 100644
--- a/matlab/ms-sbvar/set_ms_estimation_file.m
+++ b/matlab/ms-sbvar/set_ms_estimation_file.m
@@ -17,7 +17,7 @@ function [options_, oo_]=set_ms_estimation_file(file_tag, options_, oo_)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/newrat.m b/matlab/newrat.m
index d907493ea1dd3ca323336755f8157705004c9be7..19f1d7e0ea7c94ca94ed7645e8022e43605c1fb8 100644
--- a/matlab/newrat.m
+++ b/matlab/newrat.m
@@ -1,4 +1,4 @@
-function [xparam1, hh, gg, fval, igg] = newrat(func0, x, hh, gg, igg, ftol0, nit, flagg, DynareDataset,DynareOptions,Model,EstimatedParameters,BayesInfo,DynareResults)
+function [xparam1, hh, gg, fval, igg] = newrat(func0, x, analytic_derivation, ftol0, nit, flagg, DynareDataset,DynareOptions,Model,EstimatedParameters,BayesInfo,DynareResults)
 %  [xparam1, hh, gg, fval, igg] = newrat(func0, x, hh, gg, igg, ftol0, nit, flagg, varargin)
 %
 %  Optimiser with outer product gradient and with sequences of univariate steps
@@ -10,9 +10,7 @@ function [xparam1, hh, gg, fval, igg] = newrat(func0, x, hh, gg, igg, ftol0, nit
 %    of the log-likelihood to compute outer product gradient
 %
 %  x = starting guess
-%  hh = initial Hessian [OPTIONAL]
-%  gg = initial gradient [OPTIONAL]
-%  igg = initial inverse Hessian [OPTIONAL]
+%  analytic_derivation = 1 if analytic derivs
 %  ftol0 = ending criterion for function change
 %  nit = maximum number of iterations
 %
@@ -25,7 +23,7 @@ function [xparam1, hh, gg, fval, igg] = newrat(func0, x, hh, gg, igg, ftol0, nit
 %
 %  varargin = list of parameters for func0
 
-% Copyright (C) 2004-2011 Dynare Team
+% Copyright (C) 2004-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -56,21 +54,27 @@ gibbstol=length(BayesInfo.pshape)/50; %25;
 
 % func0 = str2func([func2str(func0),'_hh']);
 % func0 = func0;
-fval0=feval(func0,x,DynareDataset,DynareOptions,Model,EstimatedParameters,BayesInfo,DynareResults);
+[fval0,gg,hh]=feval(func0,x,DynareDataset,DynareOptions,Model,EstimatedParameters,BayesInfo,DynareResults);
 fval=fval0;
 
 % initialize mr_gstep and mr_hessian
-mr_hessian(1,x,[],[],[],DynareDataset,DynareOptions,Model,EstimatedParameters,BayesInfo,DynareResults);
 
+outer_product_gradient=1;
 if isempty(hh)
+    mr_hessian(1,x,[],[],[],DynareDataset,DynareOptions,Model,EstimatedParameters,BayesInfo,DynareResults);
     [dum, gg, htol0, igg, hhg, h1]=mr_hessian(0,x,func0,flagit,htol,DynareDataset,DynareOptions,Model,EstimatedParameters,BayesInfo,DynareResults);
-    hh0 = reshape(dum,nx,nx);
-    hh=hhg;
-    if min(eig(hh0))<0
-        hh0=hhg; %generalized_cholesky(hh0);
-    elseif flagit==2
-        hh=hh0;
-        igg=inv(hh);
+    if isempty(dum),
+        outer_product_gradient=0;
+        igg = 1e-4*eye(nx);
+    else
+        hh0 = reshape(dum,nx,nx);
+        hh=hhg;
+        if min(eig(hh0))<0
+            hh0=hhg; %generalized_cholesky(hh0);
+        elseif flagit==2
+            hh=hh0;
+            igg=inv(hh);
+        end
     end
     if htol0>htol
         htol=htol0;
@@ -79,6 +83,7 @@ else
     hh0=hh;
     hhg=hh;
     igg=inv(hh);
+    h1=[];
 end
 H = igg;
 disp(['Gradient norm ',num2str(norm(gg))])
@@ -119,7 +124,11 @@ while norm(gg)>gtol && check==0 && jit<nit
         if length(find(ig))<nx
             ggx=ggx*0;
             ggx(find(ig))=gg(find(ig));
-            hhx = reshape(dum,nx,nx);
+            if analytic_derivation,
+                hhx=hh;
+            else
+                hhx = reshape(dum,nx,nx);
+            end
             iggx=eye(length(gg));
             iggx(find(ig),find(ig)) = inv( hhx(find(ig),find(ig)) );
             [fvala,x0,fc,retcode] = csminit1(func0,x0,fval,ggx,0,iggx,DynareDataset,DynareOptions,Model,EstimatedParameters,BayesInfo,DynareResults);
@@ -153,6 +162,11 @@ while norm(gg)>gtol && check==0 && jit<nit
     if (fval0(icount)-fval)<ftol
         disp('No further improvement is possible!')
         check=1;
+        if analytic_derivation,
+            [fvalx,gg,hh]=feval(func0,xparam1,DynareDataset,DynareOptions,Model,EstimatedParameters,BayesInfo,DynareResults);
+            hhg=hh;
+            H = inv(hh);            
+        else
         if flagit==2
             hh=hh0;
         elseif flagg>0
@@ -167,6 +181,7 @@ while norm(gg)>gtol && check==0 && jit<nit
                 hh=hhg;
             end
         end
+        end
         disp(['Actual dxnorm ',num2str(norm(x(:,end)-x(:,end-1)))])
         disp(['FVAL          ',num2str(fval)])
         disp(['Improvement   ',num2str(fval0(icount)-fval)])
@@ -185,13 +200,16 @@ while norm(gg)>gtol && check==0 && jit<nit
         disp(['Ftol          ',num2str(ftol)])
         disp(['Htol          ',num2str(htol0)])
         htol=htol_base;
-        if norm(x(:,icount)-xparam1)>1.e-12
+        if norm(x(:,icount)-xparam1)>1.e-12 && analytic_derivation==0,
             try
                 save m1.mat x fval0 nig -append
             catch
                 save m1.mat x fval0 nig
             end
             [dum, gg, htol0, igg, hhg, h1]=mr_hessian(0,xparam1,func0,flagit,htol,DynareDataset,DynareOptions,Model,EstimatedParameters,BayesInfo,DynareResults);
+            if isempty(dum),
+                outer_product_gradient=0;
+            end
             if htol0>htol
                 htol=htol0;
                 disp(' ')
@@ -199,26 +217,37 @@ while norm(gg)>gtol && check==0 && jit<nit
                 disp('Tolerance has to be relaxed')
                 disp(' ')
             end
-            hh0 = reshape(dum,nx,nx);
-            hh=hhg;
-            if flagit==2
-                if min(eig(hh0))<=0
-                    hh0=hhg; %generalized_cholesky(hh0);
-                else
-                    hh=hh0;
-                    igg=inv(hh);
+            if ~outer_product_gradient,
+                H = bfgsi1(H,gg-g(:,icount),xparam1-x(:,icount));
+                hh=inv(H);
+                hhg=hh;
+            else
+                hh0 = reshape(dum,nx,nx);
+                hh=hhg;
+                if flagit==2
+                    if min(eig(hh0))<=0
+                        hh0=hhg; %generalized_cholesky(hh0);
+                    else
+                        hh=hh0;
+                        igg=inv(hh);
+                    end
                 end
+                H = igg;
             end
+        else
+            [fvalx,gg,hh]=feval(func0,xparam1,DynareDataset,DynareOptions,Model,EstimatedParameters,BayesInfo,DynareResults);
+            hhg=hh;
+            H = inv(hh);
         end
         disp(['Gradient norm  ',num2str(norm(gg))])
         ee=eig(hh);
         disp(['Minimum Hessian eigenvalue ',num2str(min(ee))])
         disp(['Maximum Hessian eigenvalue ',num2str(max(ee))])
-        if max(eig(hh))<0, disp('Negative definite Hessian! Local maximum!'), pause, end,
+        if max(eig(hh))<0, disp('Negative definite Hessian! Local maximum!'), pause(1), end,
         t=toc;
         disp(['Elapsed time for iteration ',num2str(t),' s.'])
         g(:,icount+1)=gg;
-        H = igg;
+
         save m1.mat x hh g hhg igg fval0 nig H
     end
 end
diff --git a/matlab/non_linear_dsge_likelihood.m b/matlab/non_linear_dsge_likelihood.m
index e245e009c93ea523a51b763b26c19d9745d88953..163b3b34ed3862950b8fad56cedf4d28c5c58713 100644
--- a/matlab/non_linear_dsge_likelihood.m
+++ b/matlab/non_linear_dsge_likelihood.m
@@ -101,7 +101,7 @@ function [fval,exit_flag,ys,trend_coeff,info,Model,DynareOptions,BayesInfo,Dynar
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2010, 2011, 2012 Dynare Team
+% Copyright (C) 2010-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -151,7 +151,7 @@ nvobs = DynareDataset.info.nvobs;
 %------------------------------------------------------------------------------
 
 % Return, with endogenous penalty, if some parameters are smaller than the lower bound of the prior domain.
-if (DynareOptions.mode_compute~=1) & any(xparam1<BayesInfo.lb)
+if (DynareOptions.mode_compute~=1) && any(xparam1<BayesInfo.lb)
     k = find(xparam1 < BayesInfo.lb);
     fval = penalty+sum((BayesInfo.lb(k)-xparam1(k)).^2);
     exit_flag = 0;
@@ -160,7 +160,7 @@ if (DynareOptions.mode_compute~=1) & any(xparam1<BayesInfo.lb)
 end
 
 % Return, with endogenous penalty, if some parameters are greater than the upper bound of the prior domain.
-if (DynareOptions.mode_compute~=1) & any(xparam1>BayesInfo.ub)
+if (DynareOptions.mode_compute~=1) && any(xparam1>BayesInfo.ub)
     k = find(xparam1>BayesInfo.ub);
     fval = penalty+sum((xparam1(k)-BayesInfo.ub(k)).^2);
     exit_flag = 0;
@@ -337,7 +337,7 @@ switch DynareOptions.particle.initialization
     StateVectorMean = ReducedForm.constant(mf0);
     old_DynareOptionsperiods = DynareOptions.periods;
     DynareOptions.periods = 5000;
-    y_ = simult(oo_.steady_state, dr);
+    y_ = simult(oo_.steady_state, dr,Model,DynareOptions,DynareResults);
     y_ = y_(state_variables_idx,2001:5000);
     StateVectorVariance = cov(y_');
     DynareOptions.periods = old_DynareOptionsperiods;
diff --git a/matlab/numgrad2.m b/matlab/numgrad2.m
index 33d104d1bb92ab038477f58d72662a63913d13c8..599924d1bc4aa141e91c4c26695c3e873dbb7107 100644
--- a/matlab/numgrad2.m
+++ b/matlab/numgrad2.m
@@ -1,11 +1,11 @@
-function [g, badg] = numgrad(fcn,f0,x,epsilon,varargin)
-% function [g badg] = numgrad(fcn,xvarargin)
+function [g, badg] = numgrad2(fcn,f0,x,epsilon,varargin)
+% function [g badg] = numgrad2(fcn,xvarargin)
 
 % Original file downloaded from:
 % http://sims.princeton.edu/yftp/optimize/mfiles/numgrad.m
 
 % Copyright (C) 1993-2007 Christopher Sims
-% Copyright (C) 2008-2010 Dynare Team
+% Copyright (C) 2008-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/numgrad3.m b/matlab/numgrad3.m
index 5014ad8a32358e76d210ea7e47ccbce0e45e30ab..3ca0ab0d993efc20f4626d6bfaa3c8debad872b7 100644
--- a/matlab/numgrad3.m
+++ b/matlab/numgrad3.m
@@ -11,7 +11,7 @@ function [g, badg, f0, f1, f2] = numgrad3(fcn,f0,x,epsilon,varargin)
 % http://sims.princeton.edu/yftp/optimize/mfiles/numgrad.m
 
 % Copyright (C) 1993-2007 Christopher Sims
-% Copyright (C) 2008-2010 Dynare Team
+% Copyright (C) 2008-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/numgrad5.m b/matlab/numgrad5.m
index 107f2230e9c6f35bc5c526491a9581e4e59c879c..598cde0947240d60ee1f452d71a895fa6d1ee772 100644
--- a/matlab/numgrad5.m
+++ b/matlab/numgrad5.m
@@ -13,7 +13,7 @@ function [g, badg, f0, f1, f2, f3, f4] = numgrad5(fcn,f0,x,epsilon,varargin)
 % http://sims.princeton.edu/yftp/optimize/mfiles/numgrad.m
 
 % Copyright (C) 1993-2007 Christopher Sims
-% Copyright (C) 2008-2010 Dynare Team
+% Copyright (C) 2008-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/octave_ver_less_than.m b/matlab/octave_ver_less_than.m
index 198341b9502cc9cc45ea289a281c383e4f47ab97..9d702d5972e4c22fbc57c53b84745bb210f3111b 100644
--- a/matlab/octave_ver_less_than.m
+++ b/matlab/octave_ver_less_than.m
@@ -15,7 +15,7 @@ function r = octave_ver_less_than(verstr)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2008-2009 Dynare Team
+% Copyright (C) 2008-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/osr.m b/matlab/osr.m
index eab1a8ecd7975ae99085968f106609e98ba9edcd..7f062291d2a0e3681ed49252aae2f7cbecbb6aea 100644
--- a/matlab/osr.m
+++ b/matlab/osr.m
@@ -1,6 +1,6 @@
 function osr(var_list,params,i_var,W)
 
-% Copyright (C) 2001-2010,2012 Dynare Team
+% Copyright (C) 2001-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/osr1.m b/matlab/osr1.m
index b72cc290adb919af078a3c5b86102183f45edffc..822ae69acd90e1e0e73896ab493b250d05e57a70 100644
--- a/matlab/osr1.m
+++ b/matlab/osr1.m
@@ -1,6 +1,6 @@
 function osr1(i_params,i_var,weights)
 
-% Copyright (C) 2005-2011 Dynare Team
+% Copyright (C) 2005-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -40,7 +40,7 @@ end
 
 exe =zeros(M_.exo_nbr,1);
 
-oo_.dr = set_state_space(oo_.dr,M_);
+oo_.dr = set_state_space(oo_.dr,M_,options_);
 
 
 np = size(i_params,1);
diff --git a/matlab/osr_obj.m b/matlab/osr_obj.m
index 28a481341f8f0499a2443025fa0a22a056804a1a..e2d34f7eba937a12d1c716fc896b074c058b2f80 100644
--- a/matlab/osr_obj.m
+++ b/matlab/osr_obj.m
@@ -1,7 +1,7 @@
 function [loss,vx,junk,exit_flag]=osr_obj(x,i_params,i_var,weights);
 % objective function for optimal simple rules (OSR)
 
-% Copyright (C) 2005-2009 Dynare Team
+% Copyright (C) 2005-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/parallel/AnalyseComputationalEnvironment.m b/matlab/parallel/AnalyseComputationalEnvironment.m
index 6b336b07a3e4d3f4d02665f2b2795e13242907de..2a8887df74c1abef86bf5b499c74d9d37e1eb844 100644
--- a/matlab/parallel/AnalyseComputationalEnvironment.m
+++ b/matlab/parallel/AnalyseComputationalEnvironment.m
@@ -78,7 +78,7 @@ dynareParallelMkDir(RemoteTmpFolder,DataInput);
 % Currently when errors are detected execution simply stops and users can
 % fix configuration errors according to the error type.
 
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -581,13 +581,13 @@ for Node=1:length(DataInput) % To obtain a recoursive function remove the 'for'
     
     RealCPUnbr='';
 %    keyboard;
-    RealCPUnbr=GiveCPUnumber(de0,OStargetUnix);
+    RealCPUnbr=GiveCPUnumber(de0);
     
     % Questo controllo penso che si possa MIGLIORARE!!!!!
     if  isempty (RealCPUnbr) && Environment==0,
         [si0 de0]=system(['psinfo \\',DataInput(Node).ComputerName]);
     end        
-    RealCPUnbr=GiveCPUnumber(de0,OStargetUnix);
+    RealCPUnbr=GiveCPUnumber(de0);
 
     if  isempty (RealCPUnbr)
         % An error occurred when we try to know the Cpu/Cores
diff --git a/matlab/parallel/closeSlave.m b/matlab/parallel/closeSlave.m
index 1e78bb9e5ef07cf8c97d098eb763d6f1f465630c..01c4ee13f519afe3f8ca6d40e45f2044cf0e83ff 100644
--- a/matlab/parallel/closeSlave.m
+++ b/matlab/parallel/closeSlave.m
@@ -15,7 +15,7 @@ function closeSlave(Parallel,TmpFolder,partial),
 % OUTPUTS
 %   None
 %
-% Copyright (C) 2010-2011 Dynare Team
+% Copyright (C) 2010-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/parallel/dynareParallelDelete.m b/matlab/parallel/dynareParallelDelete.m
index 9b9babf48d5331f39ea1fd6740208cdf77bb139e..221bd62a638ec1b1b762b7dcc3c506308d19d26d 100644
--- a/matlab/parallel/dynareParallelDelete.m
+++ b/matlab/parallel/dynareParallelDelete.m
@@ -11,7 +11,7 @@ function dynareParallelDelete(fname,pname,Parallel)
 %  None
 %
 %
-% Copyright (C) 2009-2010 Dynare Team
+% Copyright (C) 2009-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/parallel/dynareParallelDeleteNewFiles.m b/matlab/parallel/dynareParallelDeleteNewFiles.m
index 846f275789640b06bb4f88e203d0ac512055ddd2..797c8f841643c12313e62a2f53ba6d7efd258ff5 100644
--- a/matlab/parallel/dynareParallelDeleteNewFiles.m
+++ b/matlab/parallel/dynareParallelDeleteNewFiles.m
@@ -15,7 +15,7 @@ function dynareParallelDeleteNewFiles(PRCDir,Parallel,PRCDirSnapshot)
 %
 %
 %
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/parallel/dynareParallelGetNewFiles.m b/matlab/parallel/dynareParallelGetNewFiles.m
index 3d2df0c7bf20defe1e9cc3d9ddb206d19b266bb3..6a4e6cec080a32eb3341f70219873fd32b1f5086 100644
--- a/matlab/parallel/dynareParallelGetNewFiles.m
+++ b/matlab/parallel/dynareParallelGetNewFiles.m
@@ -15,7 +15,7 @@ function [PRCDirSnapshot]=dynareParallelGetNewFiles(PRCDir,Parallel,PRCDirSnapsh
 %
 %
 %
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/parallel/dynareParallelRmDir.m b/matlab/parallel/dynareParallelRmDir.m
index c05635c10bc28d8dffc9a589c1d689a4e5efa5ba..1a84986a1db2c3dbf9898426514d987b732b209d 100644
--- a/matlab/parallel/dynareParallelRmDir.m
+++ b/matlab/parallel/dynareParallelRmDir.m
@@ -11,7 +11,7 @@ function dynareParallelRmDir(PRCDir,Parallel)
 %
 %
 %
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/parallel/fMessageStatus.m b/matlab/parallel/fMessageStatus.m
index 53576de436669b6b2cdc725760ca655d2065c21e..6d84705ab5cca65455d3c16bb9c43e6365ff5c6b 100644
--- a/matlab/parallel/fMessageStatus.m
+++ b/matlab/parallel/fMessageStatus.m
@@ -14,7 +14,7 @@ function fMessageStatus(prtfrc, njob, waitbarString, waitbarTitle, Parallel)
 % OUTPUTS 
 % o None 
 
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/parallel/fParallel.m b/matlab/parallel/fParallel.m
index 3ce751af74618d4e8066d7eab4aeff64b80f5d7f..51e6ebe16fd65640ad0a973eeb88b30abacdb888 100644
--- a/matlab/parallel/fParallel.m
+++ b/matlab/parallel/fParallel.m
@@ -18,7 +18,7 @@ function fParallel(fblck,nblck,whoiam,ThisMatlab,fname)
 % OUTPUTS
 %   None
 %
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/parallel/masterParallel.m b/matlab/parallel/masterParallel.m
index 30a145595e66919955459d67d6682820fee5d2fc..573adb2de99be848688b9ddb171d5d5ff6508400 100644
--- a/matlab/parallel/masterParallel.m
+++ b/matlab/parallel/masterParallel.m
@@ -53,7 +53,7 @@ function [fOutVar,nBlockPerCPU, totCPU] = masterParallel(Parallel,fBlock,nBlock,
 %                              the number of CPU declared in "Parallel", if
 %                              the number of required threads is lower)
 
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/parallel/slaveParallel.m b/matlab/parallel/slaveParallel.m
index c7b23aa7be72a2d8c461e70614368087f0e5d5ff..d7275a4fdb10f9a07a17d81a521c96d3cec9ce4b 100644
--- a/matlab/parallel/slaveParallel.m
+++ b/matlab/parallel/slaveParallel.m
@@ -15,7 +15,7 @@ function slaveParallel(whoiam,ThisMatlab)
 % OUTPUTS 
 %   None  
 
-% Copyright (C) 2006-2011 Dynare Team
+% Copyright (C) 2006-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/partial_information/disclyap_fast.m b/matlab/partial_information/disclyap_fast.m
index 5c4fd8cea1de09576d186218518f0a20e9d911b4..2f748b6d2e7387a05321c58f547a53a6523f808e 100644
--- a/matlab/partial_information/disclyap_fast.m
+++ b/matlab/partial_information/disclyap_fast.m
@@ -11,7 +11,7 @@ function X=disclyap_fast(G,V,tol,ch)
 % Joe Pearlman and Alejandro Justiniano 
 % 3/5/2005 
 
-% Copyright (C) 2010-2011 Dynare Team
+% Copyright (C) 2010-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/partial_information/dr1_PI.m b/matlab/partial_information/dr1_PI.m
index 134da7f91f2b4a27f1f71878bf4f007076e0287c..4dbedb97f8acb526f161b5ecdc9c7e99e78cfeeb 100644
--- a/matlab/partial_information/dr1_PI.m
+++ b/matlab/partial_information/dr1_PI.m
@@ -155,7 +155,7 @@ if options_.debug
     save([M_.fname '_debug.mat'],'jacobia_')
 end
 
-dr=set_state_space(dr,M_);
+dr=set_state_space(dr,M_,options_);
 kstate = dr.kstate;
 kad = dr.kad;
 kae = dr.kae;
diff --git a/matlab/particle/auxiliary_particle_filter.m b/matlab/particle/auxiliary_particle_filter.m
index eda6ff52709473295467c4d27e11cbb5c1da3037..30ea4ef6f45c652d1754429cc9f8f1c3d0c8dcf2 100644
--- a/matlab/particle/auxiliary_particle_filter.m
+++ b/matlab/particle/auxiliary_particle_filter.m
@@ -20,7 +20,7 @@ function [LIK,lik] = auxiliary_particle_filter(ReducedForm,Y,start,DynareOptions
 % NOTES
 %   The vector "lik" is used to evaluate the jacobian of the likelihood.
 
-% Copyright (C) 2011, 2012 Dynare Team
+% Copyright (C) 2011-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/particle/local_state_space_iteration/local_state_space_iteration_2.m b/matlab/particle/local_state_space_iteration/local_state_space_iteration_2.m
index 778e2d075b4334fd7bb778faf431be7208315e69..bc205d1803497df5910a92423c8e8450a03edabb 100644
--- a/matlab/particle/local_state_space_iteration/local_state_space_iteration_2.m
+++ b/matlab/particle/local_state_space_iteration/local_state_space_iteration_2.m
@@ -58,7 +58,7 @@ function [y,y_] = local_state_space_iteration_2(yhat,epsilon,ghx,ghu,constant,gh
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2011, 2012 Dynare Team
+% Copyright (C) 2011-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/particle/resample.m b/matlab/particle/resample.m
index f8e6ba3b409bc75dddb63a3bed87b94b47600c7d..46647a97252d8d71c4ff364d10323b23e81ef730 100644
--- a/matlab/particle/resample.m
+++ b/matlab/particle/resample.m
@@ -34,7 +34,7 @@ function indx = resample(weights,method1,method2)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2011, 2012 Dynare Team
+% Copyright (C) 2011-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/particle/residual_resampling.m b/matlab/particle/residual_resampling.m
index e2af3349ca161b415be25a6036b81a49b353f7f5..11a10e67b10a6c41196e8efda5d4fd05157e0c06 100644
--- a/matlab/particle/residual_resampling.m
+++ b/matlab/particle/residual_resampling.m
@@ -30,7 +30,7 @@ function indx = residual_resampling(weights)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2011, 2012 Dynare Team
+% Copyright (C) 2011-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/particle/sequential_importance_particle_filter.m b/matlab/particle/sequential_importance_particle_filter.m
index 4a01e8e49cc0b46a45f34d7f8279907d565e5095..ee13ec2e0d2824ae138f85ac4e1de4f58c670f8f 100644
--- a/matlab/particle/sequential_importance_particle_filter.m
+++ b/matlab/particle/sequential_importance_particle_filter.m
@@ -38,7 +38,7 @@ function [LIK,lik] = sequential_importance_particle_filter(ReducedForm,Y,start,D
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2011, 2012 Dynare Team
+% Copyright (C) 2011-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/particle/traditional_resampling.m b/matlab/particle/traditional_resampling.m
index df46a9990b97e41e78e621dc64633094eddc9738..1f5fe32c3e3dfe324ecc88a2848106e017c284bf 100644
--- a/matlab/particle/traditional_resampling.m
+++ b/matlab/particle/traditional_resampling.m
@@ -33,7 +33,7 @@ function indx = traditional_resampling(weights,noise)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2011, 2012 Dynare Team
+% Copyright (C) 2011-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/perfect_foresight_simulation.m b/matlab/perfect_foresight_simulation.m
index 2e95573aca81806b64a990566988df5aef4c272c..17d253a91901cb474a508e9410eddd33e3db1086 100644
--- a/matlab/perfect_foresight_simulation.m
+++ b/matlab/perfect_foresight_simulation.m
@@ -18,7 +18,7 @@ function info = perfect_foresight_simulation(compute_linear_solution,steady_stat
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2009-2010 Dynare Team
+% Copyright (C) 2009-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/plot_icforecast.m b/matlab/plot_icforecast.m
index 66aed05ecb7af277fc3a0ea661507bcdc30c54ff..486fde3379baa756d02e169cfecfb72fae015304 100644
--- a/matlab/plot_icforecast.m
+++ b/matlab/plot_icforecast.m
@@ -10,7 +10,7 @@ function plot_icforecast(Variables,periods,options_)
 % SPECIAL REQUIREMENTS
 %  This routine has to be called after imcforecast.m.
 
-% Copyright (C) 2006-2009 Dynare Team
+% Copyright (C) 2006-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/plot_identification.m b/matlab/plot_identification.m
index 4f8b7ff0dbc5340576822ed618c4adbf70d74fda..d439eb6a6877d61c0bb00967d6b0bbd30f6b75b8 100644
--- a/matlab/plot_identification.m
+++ b/matlab/plot_identification.m
@@ -18,7 +18,7 @@ function plot_identification(params,idemoments,idehess,idemodel, idelre, advance
 % SPECIAL REQUIREMENTS
 %    None
 
-% Copyright (C) 2008-2011 Dynare Team
+% Copyright (C) 2008-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -87,8 +87,10 @@ if SampleSize == 1,
     dyn_saveas(hh,[IdentifDirectoryName '/' M_.fname '_ident_strength_' tittxt1],options_);
     
     if advanced,
-        disp(' ')
-        disp('Press ENTER to display advanced diagnostics'), pause(5),
+        if ~options_.nodisplay,
+            disp(' ')
+            disp('Press ENTER to plot advanced diagnostics'), pause(5),
+        end
         hh = dyn_figure(options_,'Name',[tittxt, ' - Sensitivity plot']);
         subplot(211)
         mmm = (siJnorm)'./max(siJnorm);
@@ -112,9 +114,9 @@ if SampleSize == 1,
         % identificaton patterns
         for  j=1:size(idemoments.cosnJ,2),
             pax=NaN(nparam,nparam);
-            fprintf('\n')
-            disp(['Collinearity patterns with ', int2str(j) ,' parameter(s)'])
-            fprintf('%-15s [%-*s] %10s\n','Parameter',(15+1)*j,' Expl. params ','cosn')
+%             fprintf('\n')
+%             disp(['Collinearity patterns with ', int2str(j) ,' parameter(s)'])
+%             fprintf('%-15s [%-*s] %10s\n','Parameter',(15+1)*j,' Expl. params ','cosn')
             for i=1:nparam,
                 namx='';
                 for in=1:j,
@@ -126,7 +128,7 @@ if SampleSize == 1,
                         pax(i,dumpindx)=idemoments.cosnJ(i,j);
                     end
                 end
-                fprintf('%-15s [%s] %10.3f\n',name{i},namx,idemoments.cosnJ(i,j))
+%                 fprintf('%-15s [%s] %10.3f\n',name{i},namx,idemoments.cosnJ(i,j))
             end
             hh = dyn_figure(options_,'Name',[tittxt,' - Collinearity patterns with ', int2str(j) ,' parameter(s)']);
             imagesc(pax,[0 1]);
@@ -171,10 +173,10 @@ if SampleSize == 1,
         end
         for j=1:min(nparam,8),
             if j<5,
-                figure(f1),
+                set(0,'CurrentFigure',f1),
                 jj=j;
             else
-                figure(f2),
+                set(0,'CurrentFigure',f2),
                 jj=j-4;
             end
             subplot(4,1,jj),
@@ -228,8 +230,10 @@ else
     title('MC mean of sensitivity measures')
     dyn_saveas(hh,[ IdentifDirectoryName '/' M_.fname '_MC_sensitivity' ],options_);
     if advanced,
-        disp(' ')
-        disp('Press ENTER to display advanced diagnostics'), pause(5),
+        if ~options_.nodisplay,
+            disp(' ')
+            disp('Press ENTER to display advanced diagnostics'), pause(5),
+        end
 %         options_.nograph=1;
         hh = dyn_figure(options_,'Name','MC Condition Number');
         subplot(221)
@@ -261,7 +265,7 @@ else
 %         end
 
         if nparam<5,
-            f1 = dyn_figure(options_,'Name',[tittxt,' - MC Identification patterns (moments): HIGHEST SV'])
+            f1 = dyn_figure(options_,'Name',[tittxt,' - MC Identification patterns (moments): HIGHEST SV']);
         else
             f1 = dyn_figure(options_,'Name',[tittxt,' - MC Identification patterns (moments): SMALLEST SV']);
             f2 = dyn_figure(options_,'Name',[tittxt,' - MC Identification patterns (moments): HIGHEST SV']);
@@ -274,12 +278,12 @@ else
         end
         for j=1:nplots,
             if (nparam>4 && j<=ceil(nplots/2)) || nparam<5,
-                figure(f1),
+                set(0,'CurrentFigure',f1),
                 jj=j;
                 VVV=squeeze(abs(idemoments.V(:,:,end-j+1)));
                 SSS = idemoments.S(:,end-j+1);
             else
-                figure(f2),
+                set(0,'CurrentFigure',f2),
                 jj=j-ceil(nplots/2);
                 VVV=squeeze(abs(idemoments.V(:,:,jj)));
                 SSS = idemoments.S(:,jj);
diff --git a/matlab/plot_priors.m b/matlab/plot_priors.m
index c232ee2cf6e65ffd957d8616dfefc0c9f4a6e0b1..b2104b5978caf00ff413fff688ecd8b01dfb60fe 100644
--- a/matlab/plot_priors.m
+++ b/matlab/plot_priors.m
@@ -13,7 +13,7 @@ function plot_priors(bayestopt_,M_,estim_params_,options_)
 % SPECIAL REQUIREMENTS
 %    None
 
-% Copyright (C) 2004-2010 Dynare Team
+% Copyright (C) 2004-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/pm3.m b/matlab/pm3.m
index 5912fca3b0a9ffd96f8a6d6521acaf4189143b6b..dbc81e7c7ec47158f688d4a41ecd2b1cbe24faba 100644
--- a/matlab/pm3.m
+++ b/matlab/pm3.m
@@ -4,7 +4,7 @@ function pm3(n1,n2,ifil,B,tit1,tit2,tit3,tit_tex,names1,names2,name3,DirectoryNa
 % See also the comment in random_walk_metropolis_hastings.m funtion.
 
 
-% Copyright (C) 2007-2011 Dynare Team
+% Copyright (C) 2007-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/pm3_core.m b/matlab/pm3_core.m
index 3c41ae955b2f2298ec3d5968cddc3a5dca8b3120..aac2aaae4fe6a423e2d8fb64cccbe415ed53f310 100644
--- a/matlab/pm3_core.m
+++ b/matlab/pm3_core.m
@@ -16,7 +16,7 @@ function myoutput=pm3_core(myinputs,fpar,nvar,whoiam, ThisMatlab)
 % SPECIAL REQUIREMENTS.
 %   None.
 
-% Copyright (C) 2007-2011 Dynare Team
+% Copyright (C) 2007-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/posterior_analysis.m b/matlab/posterior_analysis.m
index 37e43ba1f217d27e390d35d8055a5d991a981330..df978c64766fdbaf33783ccbdef9e9d4a30d0084 100644
--- a/matlab/posterior_analysis.m
+++ b/matlab/posterior_analysis.m
@@ -1,5 +1,5 @@
 function oo_ = posterior_analysis(type,arg1,arg2,arg3,options_,M_,oo_)  
-% Copyright (C) 2008-2009 Dynare Team
+% Copyright (C) 2008-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -33,7 +33,7 @@ switch info
   case {4,5}
     oo_ = job(type,SampleSize,arg1,arg2,arg3,options_,M_,oo_);
   case 6
-    [ivar,vartan] = set_stationary_variables_list(options_,M_);
+    [ivar,vartan] = get_variables_list(options_,M_);
     nvar = length(ivar);
     oo_ = job(type,SampleSize,arg1,arg2,arg3,options_,M_,oo_,nvar,vartan);
   otherwise
diff --git a/matlab/posterior_moments.m b/matlab/posterior_moments.m
index 2f2e3cbf17b37ab034c6f33682f66ab02d0118ba..ff9eeb8e17dcd83f229ad7a11fe469944f2d49dd 100644
--- a/matlab/posterior_moments.m
+++ b/matlab/posterior_moments.m
@@ -21,7 +21,7 @@ function [post_mean, post_median, post_var, hpd_interval, post_deciles, density]
 %                                                   kernel_density_estimate.m.
 %
 
-% Copyright (C) 2005-2010 Dynare Team
+% Copyright (C) 2005-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/print_info.m b/matlab/print_info.m
index 64e82debe36353e1b1d1c15e1091f076bddb0688..b406e964a004111787713a13f76ca84c7c827925 100644
--- a/matlab/print_info.m
+++ b/matlab/print_info.m
@@ -10,7 +10,7 @@ function print_info(info,noprint)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2005-2011 Dynare Team
+% Copyright (C) 2005-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -65,7 +65,7 @@ if ~noprint
         error('Some updated params are complex')
       case 24
         error('Some updated params contain NaN or Inf')
-      case 30 
+      case 30
         error('Variance can''t be computed')
       case 41
         error('one (many) parameter(s) do(es) not satisfy the lower bound');
@@ -77,20 +77,22 @@ if ~noprint
         error('The covariance matrix of the measurement errors is not positive definite.');
       case 45 %DsgeLikelihood_hh / dsge_likelihood
         error('Likelihood is not a number (NaN) or a complex number');
+      case 46 %DsgeLikelihood_hh / dsge_likelihood
+        error('Likelihood is a complex number');
+      case 47 %DsgeLikelihood_hh / dsge_likelihood
+        error('Prior density is not a number (NaN)');
+      case 48 %DsgeLikelihood_hh / dsge_likelihood
+        error('Prior density is a complex number');
       case 51
         error('You are estimating a DSGE-VAR model, but the value of the dsge prior weight is too low!')
       case 52 %DsgeVarLikelihood
         error('');
       case 61 %Discretionary policy
-        error(['Discretionary policy: maximum number of iterations has ' ...
-               'been reached. Procedure failed. ']);
+        error(['Discretionary policy: maximum number of iterations has been reached. Procedure failed. ']);
       case 62
-        error(['Discretionary policy: some eigenvalues greater than ' ...
-               'options_.qz_criterium. Model potentially unstable.']);
+        error(['Discretionary policy: some eigenvalues greater than options_.qz_criterium. Model potentially unstable.']);
       case 63
-        error(['Discretionary policy: NaN elements are present in the ' ...
-               'solution. Procedure failed.']);
-        
+        error(['Discretionary policy: NaN elements are present in the solution. Procedure failed.']);
         % Aim Code Conversions by convertAimCodeToInfo.m
       case 102
         error('Aim: roots not correctly computed by real_schur');
diff --git a/matlab/prior_analysis.m b/matlab/prior_analysis.m
index 63e4a678d77c384d873d51ee65ce2a349dc87310..69c1ca7d985f3a4c53d3f2dd340cefd1c6c0aad1 100644
--- a/matlab/prior_analysis.m
+++ b/matlab/prior_analysis.m
@@ -1,5 +1,5 @@
-function oo_ = prior_analysis(type,arg1,arg2,arg3,options_,M_,oo_)  
-% Copyright (C) 2009 Dynare Team
+function oo_ = prior_analysis(type,arg1,arg2,arg3,options_,M_,oo_,estim_params_)
+% Copyright (C) 2009-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -28,13 +28,13 @@ switch info
         drsave=1;
     end
     load([M_.dname '/prior/definition.mat']);
-    prior_sampler(drsave,M_,bayestopt_,options_,oo_);
+    prior_sampler(drsave,M_,bayestopt_,options_,oo_,estim_params_);
     clear('bayestopt_');
     oo_ = job(type,SampleSize,arg1,arg2,arg3,options_,M_,oo_);
   case {4,5}
     oo_ = job(type,SampleSize,arg1,arg2,arg3,options_,M_,oo_);
   case 6
-    [ivar,vartan] = set_stationary_variables_list(options_,M_);
+    [ivar,vartan] = get_variables_list(options_,M_);
     nvar = length(ivar);
     oo_ = job(type,SampleSize,arg1,arg2,arg3,options_,M_,oo_,nvar,vartan);
   otherwise
diff --git a/matlab/prior_posterior_statistics.m b/matlab/prior_posterior_statistics.m
index 588ab9e29e63a9d1cf387d06cde95d00eb385327..3bb87776b93b927d76eb62612b082d0bb7aed854 100644
--- a/matlab/prior_posterior_statistics.m
+++ b/matlab/prior_posterior_statistics.m
@@ -19,7 +19,7 @@ function prior_posterior_statistics(type,dataset)
 % See the comments random_walk_metropolis_hastings.m funtion.
 
 
-% Copyright (C) 2005-2011 Dynare Team
+% Copyright (C) 2005-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/prior_posterior_statistics_core.m b/matlab/prior_posterior_statistics_core.m
index 7787829dbbeeedaff9ed6e47d61f9400b05cb99f..98eb639e2672bbd499a38ffe24a96b0e0752a01d 100644
--- a/matlab/prior_posterior_statistics_core.m
+++ b/matlab/prior_posterior_statistics_core.m
@@ -24,7 +24,7 @@ function myoutput=prior_posterior_statistics_core(myinputs,fpar,B,whoiam, ThisMa
 % SPECIAL REQUIREMENTS.
 %   None.
 
-% Copyright (C) 2005-2011 Dynare Team
+% Copyright (C) 2005-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -149,7 +149,7 @@ for b=fpar:B
             logpo = evaluate_posterior_kernel(deep');
         end
     end
-    set_all_parameters(deep);
+    M_ = set_all_parameters(deep,estim_params_,M_);
     [dr,info,M_,options_,oo_] = resol(0,M_,options_,oo_);
 
     if run_smoother
diff --git a/matlab/prior_sampler.m b/matlab/prior_sampler.m
index ff7c1e8cff5b2d6859c4da2a8fc35d5d3949ada9..7fa3867f102fc6c6718211bb46170bdd92e825f9 100644
--- a/matlab/prior_sampler.m
+++ b/matlab/prior_sampler.m
@@ -1,4 +1,4 @@
-function results = prior_sampler(drsave,M_,bayestopt_,options_,oo_)
+function results = prior_sampler(drsave,M_,bayestopt_,options_,oo_,estim_params_)
 % This function builds a (big) prior sample.
 %
 % INPUTS
@@ -13,7 +13,7 @@ function results = prior_sampler(drsave,M_,bayestopt_,options_,oo_)
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2009-2010 Dynare Team
+% Copyright (C) 2009-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -79,7 +79,7 @@ file_indx_number = 0;
 while iteration < NumberOfSimulations
     loop_indx = loop_indx+1;
     params = prior_draw();
-    set_all_parameters(params);
+    M_ = set_all_parameters(params,estim_params_,M_);
     [dr,INFO,M_,options_,oo_] = resol(work,M_,options_,oo_);
     switch INFO(1)
       case 0
diff --git a/matlab/priordens.m b/matlab/priordens.m
index 62cbda5d7f634e6b13a31681a9a9f02be72f6ff7..aca29df9850766717dc2176786b143bd51889658 100644
--- a/matlab/priordens.m
+++ b/matlab/priordens.m
@@ -14,7 +14,7 @@ function [logged_prior_density, dlprior, d2lprior] = priordens(x, pshape, p6, p7
 %    logged_prior_density  [double]  scalar, log of the prior density evaluated at x.
 %
 
-% Copyright (C) 2003-2010 Dynare Team
+% Copyright (C) 2003-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/qmc_sequence.m b/matlab/qmc_sequence.m
index 783546767678c44d7e02e88c4ecfad1aa150fb5d..bfbb15dff4dcb2a5c1867769674b25ae2bdd8508 100644
--- a/matlab/qmc_sequence.m
+++ b/matlab/qmc_sequence.m
@@ -55,6 +55,23 @@
 %! @end deftypefn
 %@eod:
 
+% Copyright (C) 2012 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/>.
+
 %@test:1
 %$ t = ones(3,1);
 %$
diff --git a/matlab/quadratic_matrix_equation_solver.m b/matlab/quadratic_matrix_equation_solver.m
new file mode 100644
index 0000000000000000000000000000000000000000..146dc9aee91a36661773ce04e3a4ce9f64ebe28e
--- /dev/null
+++ b/matlab/quadratic_matrix_equation_solver.m
@@ -0,0 +1,158 @@
+function [X,info] = quadratic_matrix_equation_solver(A,B,C,tol,maxit,line_search_flag,X)
+
+%@info:
+%! @deftypefn {Function File} {[@var{X1}, @var{info}] =} quadratic_matrix_equation_solver (@var{A},@var{B},@var{C},@var{tol},@var{maxit},@var{line_search_flag},@var{X0})
+%! @anchor{logarithmic_reduction}
+%! @sp 1
+%! Solves the quadratic matrix equation AX^2 + BX + C = 0 with a Newton algorithm.
+%! @sp 2
+%! @strong{Inputs}
+%! @sp 1
+%! @table @ @var
+%! @item A
+%! Square matrix of doubles, n*n.
+%! @item B
+%! Square matrix of doubles, n*n.
+%! @item C
+%! Square matrix of doubles, n*n.
+%! @item tol
+%! Scalar double, tolerance parameter.
+%! @item maxit
+%! Scalar integer, maximum number of iterations.
+%! @item line_search_flag
+%! Scalar integer, if nonzero an exact line search algorithm is used.
+%! @item X
+%! Square matrix of doubles, n*n, initial condition.
+%! @end table
+%! @sp 1
+%! @strong{Outputs}
+%! @sp 1
+%! @table @ @var
+%! @item X
+%! Square matrix of doubles, n*n, solution of the matrix equation.
+%! @item info
+%! Scalar integer, if nonzero the algorithm failed in finding the solution of the matrix equation.
+%! @end table
+%! @sp 2
+%! @strong{This function is called by:}
+%! @sp 2
+%! @strong{This function calls:}
+%! @sp 1
+%! @ref{fastgensylv}
+%! @sp 2
+%! @strong{References:}
+%! @sp 1
+%! N.J. Higham and H.-M. Kim (2001), "Solving a quadratic matrix equation by Newton's method with exact line searches.", in SIAM J. Matrix Anal. Appl., Vol. 23, No. 3, pp. 303-316.
+%! @sp 2
+%! @end deftypefn
+%@eod:
+
+% Copyright (C) 2012 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/>.
+
+provide_initial_condition_to_fastgensylv = 0;
+
+info = 0;
+
+F = eval_quadratic_matrix_equation(A,B,C,X);
+
+if max(max(abs(F)))<tol
+    return
+end
+
+kk = 0.0;
+cc = 1+tol;
+
+step_length = 1.0;
+
+while kk<maxit && cc>tol
+    if provide_initial_condition_to_fastgensylv && exist('H','var')
+        H = fastgensylv(A*X+B,A,X,F,tol,maxit,H);
+    else
+        try
+            H = fastgensylv(A*X+B,A,X,F,tol,maxit);
+        catch
+            X = zeros(length(X));
+            H = fastgensylv(A*X+B,A,X,F,tol,maxit);
+        end
+    end
+    if line_search_flag
+        step_length = line_search(A,H,F);
+    end
+    X = X + step_length*H;
+    F = eval_quadratic_matrix_equation(A,B,C,X);
+    cc = max(max(abs(F)));
+    kk = kk +1;
+end
+
+if cc>tol
+    X = NaN(size(X));
+    info = 1;
+end
+
+
+function f = eval_quadratic_matrix_equation(A,B,C,X)
+    f = C + (B + A*X)*X;
+
+function [p0,p1] = merit_polynomial(A,H,F)
+    AHH = A*H*H;
+    gamma = norm(AHH,'fro')^2;
+    alpha = norm(F,'fro')^2;
+    beta  = trace(F*AHH*AHH*F);
+    p0 = [gamma, -beta, alpha+beta, -2*alpha, alpha];
+    p1 = [4*gamma, -3*beta, 2*(alpha+beta), -2*alpha];
+
+function t = line_search(A,H,F)
+    [p0,p1] = merit_polynomial(A,H,F);
+    if any(isnan(p0)) || any(isinf(p0))
+        t = 1.0;
+        return
+    end
+    r = roots(p1);
+    s = [Inf(3,1),r];
+    for i = 1:3
+        if isreal(r(i))
+            s(i,1) = p0(1)*r(i)^4 + p0(2)*r(i)^3 + p0(3)*r(i)^2 + p0(4)*r(i) + p0(5);
+        end
+    end
+    s = sortrows(s,1);
+    t = s(1,2);
+    if t<=1e-12 || t>=2
+        t = 1;
+    end
+
+%@test:1
+%$ addpath ../matlab
+%$
+%$ % Set the dimension of the problem to be solved
+%$ n = 200;
+%$ % Set the equation to be solved
+%$ A = eye(n);
+%$ B = diag(30*ones(n,1)); B(1,1) = 20; B(end,end) = 20; B = B - diag(10*ones(n-1,1),-1); B = B - diag(10*ones(n-1,1),1);
+%$ C = diag(15*ones(n,1)); C = C - diag(5*ones(n-1,1),-1); C = C - diag(5*ones(n-1,1),1);
+%$
+%$ % Solve the equation with the cycle reduction algorithm
+%$ tic, X1 = cycle_reduction(C,B,A,1e-7); toc
+%$
+%$ % Solve the equation with the logarithmic reduction algorithm
+%$ tic, X2 = quadratic_matrix_equation_solver(A,B,C,1e-16,100,1,zeros(n)); toc
+%$
+%$ % Check the results.
+%$ t(1) = dyn_assert(X1,X2,1e-12);
+%$
+%$ T = all(t);
+%@eof:1
\ No newline at end of file
diff --git a/matlab/ramsey_policy.m b/matlab/ramsey_policy.m
index a3d54cd078ed39f6df7a3cd46a2c2a9e62247bb5..9e6523f6d2b7bf871885efc9e761d5c0cf8d6029 100644
--- a/matlab/ramsey_policy.m
+++ b/matlab/ramsey_policy.m
@@ -1,6 +1,6 @@
 function info = ramsey_policy(var_list)
 
-% Copyright (C) 2007-2011 Dynare Team
+% Copyright (C) 2007-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -37,6 +37,6 @@ if options_.noprint == 0
 end
 
 
-oo_.planner_objective_value = evaluate_planner_objective(M_,oo_,options_);
+oo_.planner_objective_value = evaluate_planner_objective(M_,options_,oo_);
 
 options_ = oldoptions;
\ No newline at end of file
diff --git a/matlab/read_data_.m b/matlab/read_data_.m
index db520b2971bd19d6829ba45edaa41946731c2487..7ad6b4228ac58b873d0e4988ff3a99c0265e3e8c 100644
--- a/matlab/read_data_.m
+++ b/matlab/read_data_.m
@@ -1,4 +1,4 @@
-function read_data_
+function read_data_()
 % function read_data_
 % reads endogenous and exogenous variables from a text file 
 % Used by datafile option in simulate
@@ -12,7 +12,7 @@ function read_data_
 % SPECIAL REQUIREMENT
 %   none
 
-% Copyright (C) 2007-2010 Dynare Team
+% Copyright (C) 2007-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/reduced_rank_cholesky.m b/matlab/reduced_rank_cholesky.m
index 22cb2a0df9e0d41179d7464a4048211f45aadf6a..af16453b396710593b2da656746fa8764e1dd6fc 100644
--- a/matlab/reduced_rank_cholesky.m
+++ b/matlab/reduced_rank_cholesky.m
@@ -36,7 +36,7 @@ function T = reduced_rank_cholesky(X)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2009, 2010, 2011 Dynare Team
+% Copyright (C) 2009-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/resid.m b/matlab/resid.m
index 27939eed1570d3f9d87a50d3ee32ceba1760e4ae..63f37eb89b82094bc0ee8b415c3d4017f80d0c0e 100644
--- a/matlab/resid.m
+++ b/matlab/resid.m
@@ -12,7 +12,7 @@ function z = resid(junk)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2001-2011 Dynare Team
+% Copyright (C) 2001-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -36,28 +36,25 @@ if nargin && ischar(junk)
     tagname = junk;
 end
 
-
 tags  = M_.equations_tags;
 istag = 0;
 if length(tags)
     istag = 1;
 end
 
-
 steady_state_old = oo_.steady_state;
 
-info = 0;
-if options_.steadystate_flag
-    [oo_.steady_state,M.params,info] = ...
-        evaluate_steady_state(oo_.steady_state,M_,options_,oo_,0);
-end
-
 % Keep of a copy of M_.Sigma_e
 Sigma_e = M_.Sigma_e;
 
 % Set M_.Sigma_e=0 (we evaluate the *deterministic* static model)
 M_.Sigma_e = zeros(size(Sigma_e));
 
+info = 0;
+if options_.steadystate_flag
+    [oo_.steady_state,M.params,info] = ...
+        evaluate_steady_state(oo_.steady_state,M_,options_,oo_,0);
+end
 
 % Compute the residuals
 if options_.block && ~options_.bytecode
@@ -120,4 +117,4 @@ if info(1)
 end
 
 
-oo_.steady_state = steady_state_old;
+oo_.steady_state = steady_state_old;
\ No newline at end of file
diff --git a/matlab/resol.m b/matlab/resol.m
index a2db2b32dde32773d00c014fe8a42e2471666f9a..b15a91cc570765a4eae16c1fc00a104c5ecb2962 100644
--- a/matlab/resol.m
+++ b/matlab/resol.m
@@ -76,7 +76,7 @@ function [dr,info,M,options,oo] = resol(check_flag,M,options,oo)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2001-2011 Dynare Team
+% Copyright (C) 2001-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -113,6 +113,7 @@ end
 
 if options.block
     [dr,info,M,options,oo] = dr_block(dr,check_flag,M,options,oo);
+    oo.dr = dr;
 else
     [dr,info] = stochastic_solvers(dr,check_flag,M,options,oo);
     oo.dr = dr;
diff --git a/matlab/reversed_extended_path.m b/matlab/reversed_extended_path.m
index f71b78f3ae3ef54f1948b4065ff9eee2f5a87975..415804f403393c78cb4d1fe9eef9b23508a6f4e8 100644
--- a/matlab/reversed_extended_path.m
+++ b/matlab/reversed_extended_path.m
@@ -14,7 +14,7 @@ function innovation_paths = reversed_extended_path(controlled_variable_names, co
 %
 % SPECIAL REQUIREMENTS
 
-% Copyright (C) 2010 Dynare Team.
+% Copyright (C) 2010-2011 Dynare Team.
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/score.m b/matlab/score.m
index dba04b84ce53796f428528e1e080ec5d76338a24..273ca639537cc49807369e58f71156023eac6afe 100644
--- a/matlab/score.m
+++ b/matlab/score.m
@@ -8,7 +8,7 @@ function [DLIK] = score(T,R,Q,H,P,Y,DT,DYss,DOm,DH,DP,start,mf,kalman_tol,riccat
 % NOTE: the derivative matrices (DT,DR ...) are 3-dim. arrays with last
 % dimension equal to the number of structural parameters
 
-% Copyright (C) 2009 Dynare Team
+% Copyright (C) 2009-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/set_all_parameters.m b/matlab/set_all_parameters.m
index a81bf02610337c87adac0702e478f5686f49a772..a34fbd9fea3548613293ff78e834f76581a5271d 100644
--- a/matlab/set_all_parameters.m
+++ b/matlab/set_all_parameters.m
@@ -1,18 +1,39 @@
-function set_all_parameters(xparam1)
+function M = set_all_parameters(xparam1,estim_params,M)
 
-% function set_all_parameters(xparam1)
-% Sets parameters value 
-% 
-% INPUTS
-%    xparam1:   vector of parameters to be estimated (initial values)
-%    
-% OUTPUTS
-%    none
-%        
-% SPECIAL REQUIREMENTS
-%    none
+%@info:
+%! @deftypefn {Function File} {@var{M} =} dynSeries (@var{xparams1},@var{estim_params},@var{M})
+%! @anchor{set_all_parameters}
+%! @sp 1
+%! Update parameter values (deep parameters and covariance matrices).
+%! @sp 2
+%! @strong{Inputs}
+%! @sp 1
+%! @table @ @var
+%! @item xparam1
+%! N*1 vector of doubles, the values of the N estimated parameters.
+%! @item estim_params
+%! Dynare structure describing the estimated parameters.
+%! @item M
+%! Dynare structure describing the model.
+%! @end table
+%! @sp 1
+%! @strong{Outputs}
+%! @sp 1
+%! @table @ @var
+%! @item M
+%! Dynare structure describing the model, with updated parameters and covariances matrices.
+%! @end table
+%! @sp 2
+%! @strong{This function is called by:}
+%! @sp 1
+%! @ref{DsgeSmoother}, @ref{dynare_estimation_1}, @ref{@@gsa/filt_mc_}, @ref{identification_analysis}, @ref{PosteriorFilterSmootherAndForecast}, @ref{prior_posterior_statistics_core}, @ref{prior_sampler}
+%! @sp 2
+%! @strong{This function calls:}
+%! @sp 2
+%! @end deftypefn
+%@eod:
 
-% Copyright (C) 2003-2009 Dynare Team
+% Copyright (C) 2003-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -29,19 +50,17 @@ function set_all_parameters(xparam1)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-global estim_params_ M_
-
-nvx = estim_params_.nvx;
-ncx = estim_params_.ncx;
-nvn = estim_params_.nvn;
-ncn = estim_params_.ncn;
-np = estim_params_.np;
-Sigma_e = M_.Sigma_e;
-H = M_.H;
+nvx = estim_params.nvx;
+ncx = estim_params.ncx;
+nvn = estim_params.nvn;
+ncn = estim_params.ncn;
+np = estim_params.np;
+Sigma_e = M.Sigma_e;
+H = M.H;
 
 % setting shocks variance
 if nvx
-    var_exo = estim_params_.var_exo;
+    var_exo = estim_params.var_exo;
     for i=1:nvx
         k =var_exo(i,1);
         Sigma_e(k,k) = xparam1(i)^2;
@@ -52,7 +71,7 @@ offset = nvx;
 
 % setting measument error variance
 if nvn
-    var_endo = estim_params_.var_endo;
+    var_endo = estim_params.var_endo;
     for i=1:nvn
         k = var_endo(i,1);
         H(k,k) = xparam1(i+offset)^2;
@@ -63,11 +82,16 @@ end
 offset = nvx+nvn;
 
 % setting shocks covariances
+if ~isempty(M.Correlation_matrix)
+    Sigma_e = diag(sqrt(diag(Sigma_e)))*M.Correlation_matrix*diag(sqrt(diag(Sigma_e)));
+end
 if ncx
-    corrx = estim_params_.corrx;
+    corrx = estim_params.corrx;
     for i=1:ncx
         k1 = corrx(i,1);
         k2 = corrx(i,2);
+        M.Correlation_matrix(k1,k2) = xparam1(i+offset);
+        M.Correlation_matrix(k2,k1) = M.Correlation_matrix(k1,k2);
         Sigma_e(k1,k2) = xparam1(i+offset)*sqrt(Sigma_e(k1,k1)*Sigma_e(k2,k2));
         Sigma_e(k2,k1) = Sigma_e(k1,k2);
     end
@@ -77,7 +101,7 @@ end
 offset = nvx+nvn+ncx;
 % setting measurement error covariances
 if ncn
-    corrn = estim_params_.corrn;
+    corrn = estim_params.corrn;
     for i=1:ncn
         k1 = corr(i,1);
         k2 = corr(i,2);
@@ -91,13 +115,13 @@ offset = nvx+ncx+nvn+ncn;
 % setting structural parameters
 %
 if np
-    M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end);
+    M.params(estim_params.param_vals(:,1)) = xparam1(offset+1:end);
 end
 
-% updating matrices in M_
-if nvx
-    M_.Sigma_e = Sigma_e;
+% updating matrices in M
+if nvx || ncx
+    M.Sigma_e = Sigma_e;
 end
 if nvn
-    M_.H = H;
-end
+    M.H = H;
+end
\ No newline at end of file
diff --git a/matlab/set_dynare_threads.m b/matlab/set_dynare_threads.m
index c113b936951b1bf5fc13ae15e08b799176aa9a15..2bdfc1145d8657977b53b6805d8337bd8c186188 100644
--- a/matlab/set_dynare_threads.m
+++ b/matlab/set_dynare_threads.m
@@ -10,7 +10,7 @@ function set_dynare_threads(mexname,n)
 % OUTPUTS
 %  none.
 
-% Copyright (C) 2009-2010 Dynare Team
+% Copyright (C) 2009-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/set_prior.m b/matlab/set_prior.m
index 2d3f4534448dc62d2c6c6b98564ccfcdee9f2c10..e4e3cb62a9a0c06032bbb130df07b6d413c4241e 100644
--- a/matlab/set_prior.m
+++ b/matlab/set_prior.m
@@ -60,7 +60,7 @@ bayestopt_.p6 = []; % first hyper-parameter (\alpha for the BETA and GAMMA distr
 bayestopt_.p7 = []; % second hyper-parameter (\beta for the BETA and GAMMA distributions, \nu for the INVERSE GAMMAs, standard deviation for the GAUSSIAN distribution, upper bound for the UNIFORM distribution).
 
 bayestopt_.jscale = [];
-bayestopt_.name = [];
+bayestopt_.name = {};
 if nvx
     xparam1 = estim_params_.var_exo(:,2);
     ub = estim_params_.var_exo(:,4); 
@@ -94,29 +94,21 @@ if nvn
     bayestopt_.p3 = [ bayestopt_.p3; estim_params_.var_endo(:,8)];
     bayestopt_.p4 = [ bayestopt_.p4; estim_params_.var_endo(:,9)];
     bayestopt_.jscale = [ bayestopt_.jscale; estim_params_.var_endo(:,10)];
-    if isempty(bayestopt_.name)
-        bayestopt_.name = cellstr(char(options_.varobs(estim_params_.var_endo(:,1),:)));
-    else
-        bayestopt_.name = cellstr(char(char(bayestopt_.name), options_.varobs(estim_params_.var_endo(:,1),:)));
-    end
+    bayestopt_.name = [ bayestopt_.name; cellstr(options_.varobs(estim_params_.var_endo(:,1),:))];
 end
 if ncx
     xparam1 = [xparam1; estim_params_.corrx(:,3)];
     ub = [ub; max(min(estim_params_.corrx(:,5),1),-1)];
-    lb = [lb; max(min(estim_params_.corrx(:,4),1),-1)];
+    lb = [lb; min(max(estim_params_.corrx(:,4),-1),1)];
     bayestopt_.pshape = [ bayestopt_.pshape; estim_params_.corrx(:,6)];
     bayestopt_.p1 = [ bayestopt_.p1; estim_params_.corrx(:,7)];
     bayestopt_.p2 = [ bayestopt_.p2; estim_params_.corrx(:,8)];
     bayestopt_.p3 = [ bayestopt_.p3; estim_params_.corrx(:,9)];
     bayestopt_.p4 = [ bayestopt_.p4; estim_params_.corrx(:,10)];
     bayestopt_.jscale = [ bayestopt_.jscale; estim_params_.corrx(:,11)];
-    if isempty(bayestopt_.name)
-        bayestopt_.name = cellstr(char(char(strcat(cellstr(M_.exo_names(estim_params_.corrx(:,1),:)), ...
-                                                   ',' , cellstr(M_.exo_names(estim_params_.corrx(:,2),:))))));
-    else
-        bayestopt_.name = cellstr(char(char(bayestopt_.name), char(strcat(cellstr(M_.exo_names(estim_params_.corrx(:,1),:)), ...
-                                                          ',' , cellstr(M_.exo_names(estim_params_.corrx(:,2),:))))));
-    end
+    bayestopt_.name = [bayestopt_.name; cellstr(['corr ' ...
+                        deblank(M_.exo_names(estim_params_.corrx(:,1),:)) ...
+                        ', ' , deblank(M_.exo_names(estim_params_.corrx(:,2),:))])];
 end
 if ncn
     if isequal(M_.H,0)
@@ -125,20 +117,16 @@ if ncn
     end
     xparam1 = [xparam1; estim_params_.corrn(:,3)];
     ub = [ub; max(min(estim_params_.corrn(:,5),1),-1)];
-    lb = [lb; max(min(estim_params_.corrn(:,4),1),-1)];
+    lb = [lb; min(max(estim_params_.corrn(:,4),-1),1)];
     bayestopt_.pshape = [ bayestopt_.pshape; estim_params_.corrn(:,6)];
     bayestopt_.p1 = [ bayestopt_.p1; estim_params_.corrn(:,7)];
     bayestopt_.p2 = [ bayestopt_.p2; estim_params_.corrn(:,8)];
     bayestopt_.p3 = [ bayestopt_.p3; estim_params_.corrn(:,9)];
     bayestopt_.p4 = [ bayestopt_.p4; estim_params_.corrn(:,10)];
     bayestopt_.jscale = [ bayestopt_.jscale; estim_params_.corrn(:,11)];
-    if isempty(bayestopt_.name)
-        bayestopt_.name = cellstr(char(char(strcat(cellstr(M_.endo_names(estim_params_.corrn(:,1),:)),...
-                                                   ',' ,  cellstr(M_.endo_names(estim_params_.corrn(:,2),:))))));
-    else
-        bayestopt_.name = cellstr(char(char(bayestopt_.name), char(strcat(cellstr(M_.endo_names(estim_params_.corrn(:,1),:)),...
-                                                          ',' ,  cellstr(M_.endo_names(estim_params_.corrn(:,2),:))))));
-    end
+    bayestopt_.name = [bayestiopt_.name; cellstr(['corr ' ...
+                        deblank(M_.exo_names(estim_params_.corrn(:,1),:)) ...
+                        ', ' , deblank(M_.exo_names(estim_params_.corrn(:,2),:))])];
 end
 if np
     xparam1 = [xparam1; estim_params_.param_vals(:,2)];
@@ -150,11 +138,7 @@ if np
     bayestopt_.p3 = [ bayestopt_.p3; estim_params_.param_vals(:,8)];
     bayestopt_.p4 = [ bayestopt_.p4; estim_params_.param_vals(:,9)];
     bayestopt_.jscale = [ bayestopt_.jscale; estim_params_.param_vals(:,10)];
-    if isempty(bayestopt_.name)
-        bayestopt_.name = cellstr(char(M_.param_names(estim_params_.param_vals(:,1),:)));
-    else
-        bayestopt_.name = cellstr(char(char(bayestopt_.name),M_.param_names(estim_params_.param_vals(:,1),:)));
-    end
+    bayestopt_.name = [bayestopt_.name; cellstr(M_.param_names(estim_params_.param_vals(:,1),:))];
 end
 
 bayestopt_.ub = ub;
@@ -175,6 +159,11 @@ for i=1:length(k)
     end
     mu = (bayestopt_.p1(k(i))-bayestopt_.p3(k(i)))/(bayestopt_.p4(k(i))-bayestopt_.p3(k(i)));
     stdd = bayestopt_.p2(k(i))/(bayestopt_.p4(k(i))-bayestopt_.p3(k(i)));
+    if stdd^2 > (1-mu)*mu
+        error(sprintf(['Error in prior for %s: in a beta distribution with ' ...
+                       'mean %f, the standard error can''t be larger than' ...
+                       ' %f.'], bayestopt_.name{k(i)},mu,sqrt((1-mu)*mu)))
+    end
     bayestopt_.p6(k(i)) = (1-mu)*mu^2/stdd^2 - mu ;
     bayestopt_.p7(k(i)) = bayestopt_.p6(k(i))*(1/mu-1) ;
     m = compute_prior_mode([ bayestopt_.p6(k(i)) , bayestopt_.p7(k(i)) , bayestopt_.p3(k(i)) , bayestopt_.p4(k(i)) ],1);
diff --git a/matlab/set_state_space.m b/matlab/set_state_space.m
index 52b8ad6b0426ccde517982ba46fb1bf6e4147b90..8acbdd8c8a2d7a49ecff9bc4b3561df3c2691572 100644
--- a/matlab/set_state_space.m
+++ b/matlab/set_state_space.m
@@ -1,21 +1,40 @@
-function dr=set_state_space(dr,M_)
-% function dr = set_state_space(dr,M_)
-% finds the state vector for structural state space representation
-% sets many fields of dr 
-%
-% INPUTS
-%   dr: structure of decision rules for stochastic simulations
-%  
-% OUTPUTS
-%   dr: structure of decision rules for stochastic simulations
-%  
-% ALGORITHM
-%   ...
-% SPECIAL REQUIREMENTS
-%   none
-%  
+function dr=set_state_space(dr,DynareModel,DynareOptions)
+% Write the state space representation of the reduced form solution.
+
+%@info:
+%! @deftypefn {Function File} {[@var{dr} =} set_state_space (@var{dr},@var{DynareModel},@var{DynareOptions})
+%! @anchor{set_state_space}
+%! @sp 1
+%! Write the state space representation of the reduced form solution.
+%! @sp 2
+%! @strong{Inputs}
+%! @sp 1
+%! @table @ @var
+%! @item dr
+%! Matlab's structure describing decision and transition rules.
+%! @item DynareModel
+%! Matlab's structure describing the model (initialized by dynare, see @ref{M_})
+%! @item DynareOptions
+%! Matlab's structure describing the current options (initialized by dynare, see @ref{options_}).
+%! @end table
+%! @sp 2
+%! @strong{Outputs}
+%! @sp 1
+%! @table @ @var
+%! @item dr
+%! Matlab's structure describing decision and transition rules.
+%! @end table
+%! @sp 2
+%! @strong{This function is called by:}
+%! @sp 1
+%! @ref{check}, @ref{discretionary_policy_1}, @ref{dynare_estimation_init}, @ref{dyn_risky_steady_state_solver}, @ref{osr1}, @ref{partial_information/dr1_PI}, @ref{pea/pea_initialization}, @ref{stochastic_solvers}, @ref{stoch_simul}
+%! @sp 2
+%! @strong{This function calls:}
+%! @sp 2
+%! @end deftypefn
+%@eod:
 
-% Copyright (C) 1996-2010 Dynare Team
+% Copyright (C) 1996-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -31,12 +50,11 @@ function dr=set_state_space(dr,M_)
 %
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
-global options_
 
-max_lead = M_.maximum_endo_lead;
-max_lag = M_.maximum_endo_lag;
-endo_nbr = M_.endo_nbr;
-lead_lag_incidence = M_.lead_lag_incidence;
+max_lead = DynareModel.maximum_endo_lead;
+max_lag = DynareModel.maximum_endo_lag;
+endo_nbr = DynareModel.endo_nbr;
+lead_lag_incidence = DynareModel.lead_lag_incidence;
 klen = max_lag + max_lead + 1;
 
 fwrd_var = find(lead_lag_incidence(max_lag+2:end,:))';
@@ -55,8 +73,8 @@ nboth = length(both_var);
 npred = length(pred_var);
 nfwrd = length(fwrd_var);
 nstatic = length(stat_var);
-if options_.block == 1
-    order_var = M_.block_structure.variable_reordered;
+if DynareOptions.block == 1
+    order_var = DynareModel.block_structure.variable_reordered;
 else
     order_var = [ stat_var(:); pred_var(:); both_var(:); fwrd_var(:)];
 end;
@@ -65,7 +83,7 @@ inv_order_var(order_var) = (1:endo_nbr);
 % building kmask for z state vector in t+1
 if max_lag > 0
     kmask = [];
-    if max_lead > 0 
+    if max_lead > 0
         kmask = lead_lag_incidence(max_lag+2,order_var) ;
     end
     kmask = [kmask; lead_lag_incidence(1,order_var)] ;
@@ -81,30 +99,30 @@ kmask(i_kmask) = (1:nd);
 % auxiliary equations
 
 % elements that are both in z(t+1) and z(t)
-k1 = find([kmask(1:end-M_.endo_nbr) & kmask(M_.endo_nbr+1:end)] );
+k1 = find([kmask(1:end-DynareModel.endo_nbr) & kmask(DynareModel.endo_nbr+1:end)] );
 kad = [];
 kae = [];
 if ~isempty(k1)
-    kad = kmask(k1+M_.endo_nbr);
+    kad = kmask(k1+DynareModel.endo_nbr);
     kae = kmask(k1);
 end
 
 % composition of state vector
-% col 1: variable;           col 2: lead/lag in z(t+1); 
+% col 1: variable;           col 2: lead/lag in z(t+1);
 % col 3: A cols for t+1 (D); col 4: A cols for t (E)
 kstate = [ repmat([1:endo_nbr]',klen-1,1) kron([klen:-1:2]',ones(endo_nbr,1)) ...
            zeros((klen-1)*endo_nbr,2)];
 kiy = flipud(lead_lag_incidence(:,order_var))';
 kiy = kiy(:);
 if max_lead > 0
-    kstate(1:endo_nbr,3) = kiy(1:endo_nbr)-nnz(lead_lag_incidence(max_lag+1,:));  
+    kstate(1:endo_nbr,3) = kiy(1:endo_nbr)-nnz(lead_lag_incidence(max_lag+1,:));
     kstate(kstate(:,3) < 0,3) = 0;
-    kstate(endo_nbr+1:end,4) = kiy(2*endo_nbr+1:end);  
+    kstate(endo_nbr+1:end,4) = kiy(2*endo_nbr+1:end);
 else
-    kstate(:,4) = kiy(endo_nbr+1:end);  
+    kstate(:,4) = kiy(endo_nbr+1:end);
 end
 kstate = kstate(i_kmask,:);
-   
+
 dr.order_var = order_var;
 dr.inv_order_var = inv_order_var';
 dr.nstatic = nstatic;
@@ -119,4 +137,4 @@ dr.nsfwrd = nfwrd+nboth;
 % number of predetermined variables in the state vector
 dr.nspred = npred+nboth;
 
-dr.transition_auxiliary_variables = [];
+dr.transition_auxiliary_variables = [];
\ No newline at end of file
diff --git a/matlab/sim1.m b/matlab/sim1.m
index b8e27bc4ed7066f12aa4025147418b7c62ba22ae..31cebe318f0479d512697e95e8160cb80645a648 100644
--- a/matlab/sim1.m
+++ b/matlab/sim1.m
@@ -1,21 +1,19 @@
-function sim1
+function sim1()
 % function sim1
-% performs deterministic simulations with lead or lag on one period
+% Performs deterministic simulations with lead or lag on one period.
+% Uses sparse matrices.
 %
 % INPUTS
 %   ...
 % OUTPUTS
 %   ...
 % ALGORITHM
-%   Laffargue, Boucekkine, Juillard (LBJ)
-%   see Juillard (1996) Dynare: A program for the resolution and
-%   simulation of dynamic models with forward variables through the use
-%   of a relaxation algorithm. CEPREMAP. Couverture Orange. 9602.
+%   ...
 %
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 1996-2010 Dynare Team
+% Copyright (C) 1996-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -36,13 +34,19 @@ global M_ options_ oo_
 
 lead_lag_incidence = M_.lead_lag_incidence;
 
-ny = size(oo_.endo_simul,1) ;
+ny = M_.endo_nbr;
+
+max_lag = M_.maximum_endo_lag;
+
 nyp = nnz(lead_lag_incidence(1,:)) ;
+iyp = find(lead_lag_incidence(1,:)>0) ;
+ny0 = nnz(lead_lag_incidence(2,:)) ;
+iy0 = find(lead_lag_incidence(2,:)>0) ;
 nyf = nnz(lead_lag_incidence(3,:)) ;
-nrs = ny+nyp+nyf+1 ;
-nrc = nyf+1 ;
 iyf = find(lead_lag_incidence(3,:)>0) ;
-iyp = find(lead_lag_incidence(1,:)>0) ;
+
+nd = nyp+ny0+nyf;
+nrc = nyf+1 ;
 isp = [1:nyp] ;
 is = [nyp+1:ny+nyp] ;
 isf = iyf+nyp ;
@@ -50,57 +54,63 @@ isf1 = [nyp+ny+1:nyf+nyp+ny+1] ;
 stop = 0 ;
 iz = [1:ny+nyp+nyf];
 
+periods = options_.periods
+steady_state = oo_.steady_state;
+params = M_.params;
+endo_simul = oo_.endo_simul;
+exo_simul = oo_.exo_simul;
+i_cols_1 = nonzeros(lead_lag_incidence(2:3,:)');
+i_cols_A1 = find(lead_lag_incidence(2:3,:)');
+i_cols_T = nonzeros(lead_lag_incidence(1:2,:)');
+i_cols_j = 1:nd;
+i_upd = ny+(1:periods*ny);
+
+Y = endo_simul(:);
+
 disp (['-----------------------------------------------------']) ;
 disp (['MODEL SIMULATION :']) ;
 fprintf('\n') ;
 
-it_init = M_.maximum_lag+1 ;
 
+model_dynamic = str2func([M_.fname,'_dynamic']);
+z = Y(find(lead_lag_incidence'));
+[d1,jacobian] = model_dynamic(z,oo_.exo_simul, params, ...
+                              steady_state,2);
+
+A = sparse([],[],[],periods*ny,periods*ny,periods*nnz(jacobian));
+res = zeros(periods*ny,1);
+
+    
 h1 = clock ;
 for iter = 1:options_.maxit_
     h2 = clock ;
     
-    if options_.terminal_condition == 0
-        c = zeros(ny*options_.periods,nrc) ;
-    else
-        c = zeros(ny*(options_.periods+1),nrc) ;
-    end
-    
-    it_ = it_init ;
-    z = [oo_.endo_simul(iyp,it_-1) ; oo_.endo_simul(:,it_) ; oo_.endo_simul(iyf,it_+1)] ;
-    [d1,jacobian] = feval([M_.fname '_dynamic'],z,oo_.exo_simul, M_.params, oo_.steady_state,it_);
-    jacobian = [jacobian(:,iz) -d1] ;
-    ic = [1:ny] ;
-    icp = iyp ;
-    c (ic,:) = jacobian(:,is)\jacobian(:,isf1) ;
-    for it_ = it_init+(1:options_.periods-1)
-        z = [oo_.endo_simul(iyp,it_-1) ; oo_.endo_simul(:,it_) ; oo_.endo_simul(iyf,it_+1)] ;
-        [d1,jacobian] = feval([M_.fname '_dynamic'],z,oo_.exo_simul, ...
-                              M_.params, oo_.steady_state, it_);
-        jacobian = [jacobian(:,iz) -d1] ;
-        jacobian(:,[isf nrs]) = jacobian(:,[isf nrs])-jacobian(:,isp)*c(icp,:) ;
-        ic = ic + ny ;
-        icp = icp + ny ;
-        c (ic,:) = jacobian(:,is)\jacobian(:,isf1) ;
-    end
+    i_rows = 1:ny;
+    i_cols = find(lead_lag_incidence');
+    i_cols_A = i_cols;
     
-    if options_.terminal_condition == 1
-        s = eye(ny) ;
-        s(:,isf) = s(:,isf)+c(ic,1:nyf) ;
-        ic = ic + ny ;
-        c(ic,nrc) = s\c(ic,nrc) ;
-        c = bksup1(c,ny,nrc,iyf,options_.periods) ;
-        c = reshape(c,ny,options_.periods+1) ;
-        oo_.endo_simul(:,it_init+(0:options_.periods)) = oo_.endo_simul(:,it_init+(0:options_.periods))+options_.slowc*c ;
-    else
-        c = bksup1(c,ny,nrc,iyf,options_.periods) ;
-        c = reshape(c,ny,options_.periods) ;
-        oo_.endo_simul(:,it_init+(0:options_.periods-1)) = oo_.endo_simul(:,it_init+(0:options_.periods-1))+options_.slowc*c ;
+    for it = 2:(periods+1)
+
+        [d1,jacobian] = model_dynamic(Y(i_cols),exo_simul, params, ...
+                                      steady_state,it);
+        if it == 2
+            A(i_rows,i_cols_A1) = jacobian(:,i_cols_1);
+        elseif it == periods+1
+            A(i_rows,i_cols_A(i_cols_T)) = jacobian(:,i_cols_T);
+        else
+            A(i_rows,i_cols_A) = jacobian(:,i_cols_j);
+        end
+
+        res(i_rows) = d1;
+        
+        i_rows = i_rows + ny;
+        i_cols = i_cols + ny;
+        if it > 2
+            i_cols_A = i_cols_A + ny;
+        end
     end
-    
-    err = max(max(abs(c./options_.scalv')));
-    disp([num2str(iter) ' -     err = ' num2str(err)]) ;
-    disp(['     Time of iteration       :' num2str(etime(clock,h2))]) ;
+        
+    err = max(abs(res));
     
     if err < options_.dynatol.f
         stop = 1 ;
@@ -112,10 +122,17 @@ for iter = 1:options_.maxit_
         oo_.deterministic_simulation.status = 1;% Convergency obtained.
         oo_.deterministic_simulation.error = err;
         oo_.deterministic_simulation.iterations = iter;
+        oo_.endo_simul = reshape(Y,ny,periods+2);
         break
     end
+
+    dy = -A\res;
+    
+    Y(i_upd) =   Y(i_upd) + dy;
+
 end
 
+
 if ~stop
     fprintf('\n') ;
     disp(['     Total time of simulation        :' num2str(etime(clock,h1))]) ;
diff --git a/matlab/sim1a.m b/matlab/sim1_lbj.m
similarity index 57%
rename from matlab/sim1a.m
rename to matlab/sim1_lbj.m
index 2141e5b1c69e90863445b7a3c3818cfeb0721cee..8222ae4de6ddd00fad537fcc6de1ccbae926f4d6 100644
--- a/matlab/sim1a.m
+++ b/matlab/sim1_lbj.m
@@ -1,6 +1,7 @@
-function sim1
-% function sim1
+function sim1_lbj()
+% function sim1_lbj
 % performs deterministic simulations with lead or lag on one period
+% using the historical LBJ algorithm
 %
 % INPUTS
 %   ...
@@ -15,7 +16,7 @@ function sim1
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 1996-2010 Dynare Team
+% Copyright (C) 1996-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -36,19 +37,13 @@ global M_ options_ oo_
 
 lead_lag_incidence = M_.lead_lag_incidence;
 
-ny = M_.endo_nbr;
-
-max_lag = M_.maximum_endo_lag;
-
+ny = size(oo_.endo_simul,1) ;
 nyp = nnz(lead_lag_incidence(1,:)) ;
-iyp = find(lead_lag_incidence(1,:)>0) ;
-ny0 = nnz(lead_lag_incidence(2,:)) ;
-iy0 = find(lead_lag_incidence(2,:)>0) ;
 nyf = nnz(lead_lag_incidence(3,:)) ;
-iyf = find(lead_lag_incidence(3,:)>0) ;
-
-nd = nyp+ny0+nyf;
+nrs = ny+nyp+nyf+1 ;
 nrc = nyf+1 ;
+iyf = find(lead_lag_incidence(3,:)>0) ;
+iyp = find(lead_lag_incidence(1,:)>0) ;
 isp = [1:nyp] ;
 is = [nyp+1:ny+nyp] ;
 isf = iyf+nyp ;
@@ -56,63 +51,57 @@ isf1 = [nyp+ny+1:nyf+nyp+ny+1] ;
 stop = 0 ;
 iz = [1:ny+nyp+nyf];
 
-periods = options_.periods
-steady_state = oo_.steady_state;
-params = M_.params;
-endo_simul = oo_.endo_simul;
-exo_simul = oo_.exo_simul;
-i_cols_1 = nonzeros(lead_lag_incidence(2:3,:)');
-i_cols_A1 = find(lead_lag_incidence(2:3,:)');
-i_cols_T = nonzeros(lead_lag_incidence(1:2,:)');
-i_cols_j = 1:nd;
-i_upd = ny+(1:periods*ny);
-
-Y = endo_simul(:);
-
 disp (['-----------------------------------------------------']) ;
 disp (['MODEL SIMULATION :']) ;
 fprintf('\n') ;
 
+it_init = M_.maximum_lag+1 ;
 
-model_dynamic = str2func([M_.fname,'_dynamic']);
-z = Y(find(lead_lag_incidence'));
-[d1,jacobian] = model_dynamic(z,oo_.exo_simul, params, ...
-                              steady_state,2);
-
-A = sparse([],[],[],periods*ny,periods*ny,periods*nnz(jacobian));
-res = zeros(periods*ny,1);
-
-    
 h1 = clock ;
 for iter = 1:options_.maxit_
     h2 = clock ;
     
-    i_rows = 1:ny;
-    i_cols = find(lead_lag_incidence');
-    i_cols_A = i_cols;
+    if options_.terminal_condition == 0
+        c = zeros(ny*options_.periods,nrc) ;
+    else
+        c = zeros(ny*(options_.periods+1),nrc) ;
+    end
     
-    for it = 2:(periods+1)
-
-        [d1,jacobian] = model_dynamic(Y(i_cols),exo_simul, params, ...
-                                      steady_state,it);
-        if it == 2
-            A(i_rows,i_cols_A1) = jacobian(:,i_cols_1);
-        elseif it == periods+1
-            A(i_rows,i_cols_A(i_cols_T)) = jacobian(:,i_cols_T);
-        else
-            A(i_rows,i_cols_A) = jacobian(:,i_cols_j);
-        end
-
-        res(i_rows) = d1;
-        
-        i_rows = i_rows + ny;
-        i_cols = i_cols + ny;
-        if it > 2
-            i_cols_A = i_cols_A + ny;
-        end
+    it_ = it_init ;
+    z = [oo_.endo_simul(iyp,it_-1) ; oo_.endo_simul(:,it_) ; oo_.endo_simul(iyf,it_+1)] ;
+    [d1,jacobian] = feval([M_.fname '_dynamic'],z,oo_.exo_simul, M_.params, oo_.steady_state,it_);
+    jacobian = [jacobian(:,iz) -d1] ;
+    ic = [1:ny] ;
+    icp = iyp ;
+    c (ic,:) = jacobian(:,is)\jacobian(:,isf1) ;
+    for it_ = it_init+(1:options_.periods-1)
+        z = [oo_.endo_simul(iyp,it_-1) ; oo_.endo_simul(:,it_) ; oo_.endo_simul(iyf,it_+1)] ;
+        [d1,jacobian] = feval([M_.fname '_dynamic'],z,oo_.exo_simul, ...
+                              M_.params, oo_.steady_state, it_);
+        jacobian = [jacobian(:,iz) -d1] ;
+        jacobian(:,[isf nrs]) = jacobian(:,[isf nrs])-jacobian(:,isp)*c(icp,:) ;
+        ic = ic + ny ;
+        icp = icp + ny ;
+        c (ic,:) = jacobian(:,is)\jacobian(:,isf1) ;
+    end
+    
+    if options_.terminal_condition == 1
+        s = eye(ny) ;
+        s(:,isf) = s(:,isf)+c(ic,1:nyf) ;
+        ic = ic + ny ;
+        c(ic,nrc) = s\c(ic,nrc) ;
+        c = bksup1(c,ny,nrc,iyf,options_.periods) ;
+        c = reshape(c,ny,options_.periods+1) ;
+        oo_.endo_simul(:,it_init+(0:options_.periods)) = oo_.endo_simul(:,it_init+(0:options_.periods))+options_.slowc*c ;
+    else
+        c = bksup1(c,ny,nrc,iyf,options_.periods) ;
+        c = reshape(c,ny,options_.periods) ;
+        oo_.endo_simul(:,it_init+(0:options_.periods-1)) = oo_.endo_simul(:,it_init+(0:options_.periods-1))+options_.slowc*c ;
     end
-        
-    err = max(abs(res));
+    
+    err = max(max(abs(c./options_.scalv')));
+    disp([num2str(iter) ' -     err = ' num2str(err)]) ;
+    disp(['     Time of iteration       :' num2str(etime(clock,h2))]) ;
     
     if err < options_.dynatol.f
         stop = 1 ;
@@ -124,17 +113,10 @@ for iter = 1:options_.maxit_
         oo_.deterministic_simulation.status = 1;% Convergency obtained.
         oo_.deterministic_simulation.error = err;
         oo_.deterministic_simulation.iterations = iter;
-        oo_.endo_simul = reshape(Y,ny,periods+2);
         break
     end
-
-    dy = -A\res;
-    
-    Y(i_upd) =   Y(i_upd) + dy;
-
 end
 
-
 if ~stop
     fprintf('\n') ;
     disp(['     Total time of simulation        :' num2str(etime(clock,h1))]) ;
diff --git a/matlab/sim1_purely_backward.m b/matlab/sim1_purely_backward.m
new file mode 100644
index 0000000000000000000000000000000000000000..b432c4789f2cfb9d970cbf31805c367299747752
--- /dev/null
+++ b/matlab/sim1_purely_backward.m
@@ -0,0 +1,40 @@
+function sim1_purely_backward()
+% Performs deterministic simulation of a purely backward model
+
+% Copyright (C) 2012 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_ oo_
+
+    ny0 = nnz(M_.lead_lag_incidence(2,:)); % Number of variables at current period
+    nyb = nnz(M_.lead_lag_incidence(1,:)); % Number of variables at previous period
+    iyb = find(M_.lead_lag_incidence(1,:)>0); % Indices of variables at previous period
+
+    if ny0 ~= M_.endo_nbr
+        error('SIMUL: all endogenous variables must appear at the current period')
+    end
+    
+    model_dynamic = str2func([M_.fname,'_dynamic']);
+
+    for it = 2:options_.periods+1
+        yb = oo_.endo_simul(:,it-1); % Values at previous period, also used as guess value for current period
+        yb1 = yb(iyb);
+       
+        tmp = solve1(model_dynamic, [yb1; yb], 1:M_.endo_nbr, nyb+1:nyb+M_.endo_nbr, 1, 1, oo_.exo_simul, M_.params, oo_.steady_state, it);
+        oo_.endo_simul(:,it) = tmp(nyb+1:nyb+M_.endo_nbr);
+    end
+    
\ No newline at end of file
diff --git a/matlab/sim1_purely_forward.m b/matlab/sim1_purely_forward.m
new file mode 100644
index 0000000000000000000000000000000000000000..65a874b5055f035e8c0657712cb135bb994dd64c
--- /dev/null
+++ b/matlab/sim1_purely_forward.m
@@ -0,0 +1,39 @@
+function sim1_purely_forward()
+% Performs deterministic simulation of a purely forward model
+
+% Copyright (C) 2012 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_ oo_
+
+    ny0 = nnz(M_.lead_lag_incidence(1,:)); % Number of variables at current period
+    iyf = find(M_.lead_lag_incidence(2,:)>0); % Indices of variables at next period
+
+    if ny0 ~= M_.endo_nbr
+        error('SIMUL: all endogenous variables must appear at the current period')
+    end
+    
+    model_dynamic = str2func([M_.fname,'_dynamic']);
+
+    for it = options_.periods:-1:1
+        yf = oo_.endo_simul(:,it+1); % Values at next period, also used as guess value for current period
+        yf1 = yf(iyf);
+       
+        tmp = solve1(model_dynamic, [yf; yf1], 1:M_.endo_nbr, 1:M_.endo_nbr, 1, 1, oo_.exo_simul, M_.params, oo_.steady_state, it);
+        oo_.endo_simul(:,it) = tmp(1:M_.endo_nbr);
+    end
+    
\ No newline at end of file
diff --git a/matlab/simk.m b/matlab/simk.m
deleted file mode 100644
index 5904d2acc457920379957a92efa691ff5a299922..0000000000000000000000000000000000000000
--- a/matlab/simk.m
+++ /dev/null
@@ -1,334 +0,0 @@
-function simk
-% function simk
-% performs deterministic simulations with lead or lag on more than one
-% period
-%
-% Currently used only for purely forward models.
-%
-% INPUTS
-%   ...
-% OUTPUTS
-%   ...
-% ALGORITHM
-%   Laffargue, Boucekkine, Juillard (LBJ)
-%   see Juillard (1996) Dynare: A program for the resolution and
-%   simulation of dynamic models with forward variables through the use
-%   of a relaxation algorithm. CEPREMAP. Couverture Orange. 9602.
-%
-% SPECIAL REQUIREMENTS
-%   None.
-%  
-
-% Copyright (C) 1996-2012 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_ oo_
-
-nk = M_.maximum_endo_lag + M_.maximum_endo_lead + 1 ;
-ny = size(M_.lead_lag_incidence,2) ;
-icc1 = M_.lead_lag_incidence(nk,:) > 0;
-
-for i = 1:M_.maximum_lead -1
-    icc1 = [M_.lead_lag_incidence(nk-i,:) | icc1(1,:); icc1] ;
-end
-
-icc1 = find(icc1') ;
-iy = M_.lead_lag_incidence > 0 ;
-isc = cumsum(sum(iy',1))' ;
-iyr0 = find(M_.lead_lag_incidence') ;
-ncc1 = size(icc1,1) ;
-ncc = ncc1 + 1 ;
-ncs = size(iyr0,1) ;
-
-ky = zeros(ny,nk) ;            % indices of variables at each lead or lag
-lky = zeros(nk,1) ;
-for i = 1:nk
-    j = find(M_.lead_lag_incidence(i,:))' ;
-    if isempty(j)
-        lky(i) = 0;
-    else
-        lky(i) = size(j,1) ;
-        ky(1:lky(i),i) = j ;
-    end
-end
-
-jwc = find(iy(2:M_.maximum_endo_lead+1,:)') ; % indices of columns for
-                                              % triangularization
-                                              % as many rows as lags in model
-
-if isempty(jwc)
-    jwc = 0 ;
-    ljwc = 0 ;
-    temp = icc1 ;
-else
-    ljwc = size(jwc,1) ;          % length of each row in jwc
-    temp = union(jwc,icc1,'rows') ;      % prepares next iteration
-end
-
-j1 = ky(1:lky(1),1) ;
-lj1 = lky(1) ;
-
-for i = 2:M_.maximum_endo_lag
-    [j1,lj1] = ffill(j1,lj1,selif(temp+(i-1)*ny,temp <= ny)) ;
-    if M_.maximum_endo_lead == 1
-        if lky(i+M_.maximum_endo_lead) > 0
-            [jwc,ljwc] = ffill(jwc,ljwc, ky(1:lky(i+M_.maximum_endo_lead),i+M_.maximum_endo_lead)+(M_.maximum_endo_lead-1)*ny) ;
-            if ljwc(i) == 0
-                temp = icc1;
-            else
-                temp = union(jwc(1:ljwc(i),i),icc1,'rows') ;
-            end
-        else
-            [jwc,ljwc] = ffill(jwc,ljwc,[]) ;
-            temp = icc1 ;
-        end
-    else
-        temp = temp(lj1(i)+1:size(temp,1),:) - ny ;
-        if lky(i+M_.maximum_endo_lead) > 0
-            [jwc,ljwc] = ffill(jwc,ljwc,[temp;ky(1:lky(i+M_.maximum_endo_lead),i+M_.maximum_endo_lead)+(M_.maximum_endo_lead-1)*ny]);
-        else
-            [jwc,ljwc] = ffill(jwc,ljwc,temp) ;
-        end
-        temp = union(jwc(1:ljwc(i),i),icc1,'rows') ;
-    end
-end
-
-[j1,lj1] = ffill(j1,lj1,selif(temp+M_.maximum_endo_lag*ny, temp <= ny)) ;
-ltemp = zeros(M_.maximum_endo_lag,1) ;
-jwc1 = zeros(ncc1,M_.maximum_endo_lag) ;
-
-for i = 1:M_.maximum_endo_lag
-    temp = union(jwc(1:ljwc(i),i),icc1,'rows') ;
-    ltemp(i) = size(temp,1) ;
-    if ljwc(i) > 0
-        jwc(1:ljwc(i),i) = indnv(jwc(1:ljwc(i),i),temp) ;
-    end
-    jwc1(:,i) = indnv(icc1,temp) ;
-end
-
-h1 = clock ;
-
-disp (['-----------------------------------------------------']) ;
-disp ('MODEL SIMULATION') ;
-fprintf ('\n') ;
-
-for iter = 1:options_.maxit_
-    h2 = clock ;
-    oo_.endo_simul = oo_.endo_simul(:);
-    err_f = 0;
-    
-    fid = fopen([M_.fname '.swp'],'w+') ;
-
-    it_ = 1+M_.maximum_lag ;
-    ic = [1:ny] ;
-    iyr = iyr0 ;
-    i = M_.maximum_endo_lag+1 ;
-    while (i>1) && (it_<=options_.periods+M_.maximum_endo_lag)
-        h3 = clock ;
-        [d1,jacobian] = feval([M_.fname '_dynamic'],oo_.endo_simul(iyr),oo_.exo_simul, M_.params,oo_.steady_state, it_);
-        d1 = -d1 ;
-        err_f = max(err_f,max(abs(d1)));
-        if lky(i) ~= 0
-            j1i = ky(1:lky(i),i) ;
-            w0 = jacobian(:,isc(i-1)+1:isc(i)) ;
-        else
-            w0 = [];
-        end
-        ttemp = iy(i+1:i+M_.maximum_endo_lead,:)' ;
-        jwci = find(ttemp) ;
-        if ~ isempty(jwci)
-            w = jacobian(:,isc(i)+1:isc(i+M_.maximum_endo_lead)) ;
-        end
-        j = i ;
-        while j <= M_.maximum_endo_lag
-            if ~isempty(w0)
-
-                ofs = ((it_-M_.maximum_lag-M_.maximum_endo_lag+j-2)*ny)*ncc*8 ;
-                junk = fseek(fid,ofs,-1) ;
-                c = fread(fid,[ncc,ny],'float64')';
-
-                if isempty(jwci)
-                    w = -w0*c(j1i,1:ncc1) ;
-                    jwci = icc1 ;
-                else
-                    iz = union(jwci,icc1,'rows') ;
-                    ix = indnv(jwci,iz) ;
-                    iy__ = indnv(icc1,iz) ;
-                    temp = zeros(size(w,1),size(iz,1)) ;
-                    temp(:,ix) = w;
-                    temp(:,iy__) = temp(:,iy__)-w0*c(j1i,1:ncc1) ;
-                    w = temp ;
-                    jwci = iz ;
-                    clear temp iz ix iy__ ;
-                end
-                d1 = d1-w0*c(j1i,ncc) ;
-                clear c ;
-            end
-            j = j + 1 ;
-            if isempty(jwci)
-                j1i = [];
-                if lky(j+M_.maximum_endo_lead) ~= 0
-                    jwci = ky(1:lky(j+M_.maximum_endo_lead),j+M_.maximum_endo_lead) + (M_.maximum_endo_lead-1)*ny ;
-                    w = jacobian(:,isc(j+M_.maximum_endo_lead-1)+1:isc(j+M_.maximum_endo_lead)) ;
-                else
-                    jwci = [] ;
-                end
-            else
-                j1i = selif(jwci,jwci<(ny+1)) ;
-                w0 = w(:,1:size(j1i,1)) ;
-                if size(jwci,1) == size(j1i,1)
-                    if lky(j+M_.maximum_endo_lead) ~= 0
-                        jwci = ky(1:lky(j+M_.maximum_endo_lead),j+M_.maximum_endo_lead)+(M_.maximum_endo_lead-1)*ny ;
-                        w = jacobian(:,isc(j+M_.maximum_endo_lead-1)+1:isc(j+M_.maximum_endo_lead)) ;
-                    else
-                        jwci = [] ;
-                    end
-                else
-                    jwci = jwci(size(j1i,1)+1:size(jwci,1),:)-ny ;
-                    w = w(:,size(j1i,1)+1:size(w,2)) ; 
-                    if lky(j+M_.maximum_endo_lead) ~= 0
-                        jwci = [ jwci; ky(1: lky(j+M_.maximum_endo_lead),j+M_.maximum_endo_lead)+(M_.maximum_endo_lead-1)*ny] ;
-                        w = [w jacobian(:,isc(j+M_.maximum_endo_lead-1)+1:isc(j+M_.maximum_endo_lead))] ;
-                        %         else
-                        %           jwci = [] ;
-                    end
-                end
-            end
-        end
-        jwci = [indnv(jwci,icc1);ncc] ;
-        w = [w d1] ;
-        c = zeros(ny,ncc) ;
-        c(:,jwci) = w0\w ;
-        clear w w0 ;
-
-        junk = fseek(fid,0,1) ;
-        fwrite(fid,c','float64') ;
-        clear c ;
-
-        it_ = it_ + 1;
-        ic = ic + ny ;
-        iyr = iyr + ny ;
-        i = i - 1 ;
-    end
-    icr0 = (it_-M_.maximum_lag-M_.maximum_endo_lag -1)*ny ;
-    while it_ <= options_.periods+M_.maximum_lag
-        [d1,jacobian] = feval([M_.fname '_dynamic'],oo_.endo_simul(iyr),oo_.exo_simul, M_.params,oo_.steady_state, it_);
-        d1 = -d1 ;
-        err_f = max(err_f,max(abs(d1)));
-        w0 = jacobian(:,1:isc(1)) ;
-        w = jacobian(:,isc(1)+1:isc(1+M_.maximum_endo_lead)) ;
-        j = 1 ;
-        while j <= M_.maximum_endo_lag
-            icr = j1(1:lj1(j),j)-(j-1)*ny ;
-
-            ofs = ((icr0+(j-1)*ny+1)-1)*ncc*8 ;
-            junk = fseek(fid,ofs,-1) ;
-            c = fread(fid,[ncc,ny],'float64')' ;
-
-            temp = zeros(ny,ltemp(j)) ;
-            if ljwc(j) > 0
-                temp(:,jwc(1:ljwc(j),j)) = w ;
-            end
-            temp(:,jwc1(:,j))=temp(:,jwc1(:,j))-w0*c(icr,1:ncc1) ;
-            w = temp ;
-            clear temp ;
-            d1 = d1-w0*c(icr,ncc) ;
-            clear c ;
-            j = j + 1 ;
-            w0 = w(:,1:lj1(j)) ;
-            if M_.maximum_endo_lead == 1
-                w = jacobian(:,isc(j+M_.maximum_endo_lead-1)+1:isc(j+M_.maximum_endo_lead)) ;
-            else
-                w = w(:,lj1(j)+1:size(w,2)) ;
-
-                if lky(j+M_.maximum_endo_lead) > 0
-                    w = [w jacobian(:,isc(j+M_.maximum_endo_lead-1)+1:isc(j+M_.maximum_endo_lead))] ;
-                end
-            end
-        end
-        c = w0\[w d1] ;
-        d1 = [] ;
-        clear w w0 ;
-        junk = fseek(fid,0,1) ;
-        fwrite(fid,c','float64') ;
-        clear c ;
-        it_ = it_ + 1 ;
-        ic = ic + ny ;
-        iyr = iyr + ny ;
-        icr0 = icr0 + ny ;
-    end
-    if options_.terminal_condition == 1
-
-        ofs = (((it_-M_.maximum_lag-2)*ny+1)-1)*ncc*8 ;
-        junk = fseek(fid,ofs,-1) ;
-        c = fread(fid,[ncc,ny],'float64')';
-
-        for i = 1:M_.maximum_endo_lead
-            w = tril(triu(ones(ny,ny+ncc1))) ;
-            w(:,jwc1(:,M_.maximum_endo_lag)) = w(:,jwc1(:,M_.maximum_endo_lag))+c(:,1:ncc1) ;
-            c = [w(:,ny+1:size(w,2))' c(:,ncc)]/w(:,1:ny) ;
-
-            junk = fseek(fid,0,1) ;
-            fwrite(fid,c','float64') ;
-
-            it_ = it_+1 ;
-            ic = ic + ny ;
-
-        end
-    end
-    oo_.endo_simul = reshape(oo_.endo_simul,ny,options_.periods+M_.maximum_lag+M_.maximum_endo_lead) ;
-    if options_.terminal_condition == 1
-        hbacsup = clock ;
-        c = bksupk(ny,fid,ncc,icc1) ;
-        hbacsup = etime(clock,hbacsup) ;
-        c = reshape(c,ny,options_.periods+M_.maximum_endo_lead)' ;
-        y(:,1+M_.maximum_endo_lag:(options_.periods+M_.maximum_endo_lead+M_.maximum_endo_lag)) = y(:,1+M_.maximum_endo_lag:(options_.periods+M_.maximum_endo_lead+M_.maximum_endo_lag))+options_.slowc*c' ;
-    else
-        hbacsup = clock ;
-        c = bksupk(ny,fid,ncc,icc1) ;
-        hbacsup = etime(clock,hbacsup) ;
-        c = reshape(c,ny,options_.periods)' ;
-        oo_.endo_simul(:,1+M_.maximum_endo_lag:(options_.periods+M_.maximum_endo_lag)) = oo_.endo_simul(:,1+M_.maximum_endo_lag:(options_.periods+M_.maximum_endo_lag))+options_.slowc*c' ;
-    end
-
-    fclose(fid) ;
-
-    h2 = etime(clock,h2) ;
-    [junk,i1] = max(abs(c));
-    [junk,i2] = max(junk);
-    disp(['variable ' M_.endo_names(i2,:) ' period ' num2str(i1(i2))])
-    err = max(max(abs(c./options_.scalv'))) ;
-    disp ([num2str(iter) '-     err = ' num2str(err)]) ;
-    disp (['err_f = ' num2str(err_f)])
-    disp (['    Time of this iteration  : ' num2str(h2)]) ;
-    if options_.timing
-        disp (['        Back substitution               : ' num2str(hbacsup)]) ;
-    end
-    if err < options_.dynatol.f
-        h1 = etime(clock,h1) ;
-        fprintf ('\n') ;
-        disp (['        Total time of simulation        : ' num2str(h1)]) ;
-        fprintf ('\n') ;
-        disp (['        Convergence achieved.']) ;
-        disp (['-----------------------------------------------------']) ;
-        fprintf ('\n') ;
-        return ;
-    end
-end
-disp(['WARNING : the maximum number of iterations is reached.']) ;
-fprintf ('\n') ;
-disp (['-----------------------------------------------------']) ;
diff --git a/matlab/simplex_optimization_routine.m b/matlab/simplex_optimization_routine.m
index caccfc689182f1b37af29151993051a92d315fcf..2e7838aa49adf943063851d8f6d0766922eb3ce9 100644
--- a/matlab/simplex_optimization_routine.m
+++ b/matlab/simplex_optimization_routine.m
@@ -17,7 +17,7 @@ function [x,fval,exitflag] = simplex_optimization_routine(objective_function,x,o
 %
 %
 
-% Copyright (C) 2010, 2011 Dynare Team
+% Copyright (C) 2010-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/simul.m b/matlab/simul.m
index b523e926d0030f438b5aa9277bd8ff2664fabd01..a34c0925e5a98f5261dc0b3f93365b68225eaad9 100644
--- a/matlab/simul.m
+++ b/matlab/simul.m
@@ -1,4 +1,4 @@
-function simul
+function simul()
 % Computes deterministic simulations
 %  
 % INPUTS
@@ -33,18 +33,23 @@ global M_ options_ oo_
 
 test_for_deep_parameters_calibration(M_);
 
-if options_.stack_solve_algo < 0 || options_.stack_solve_algo > 5
-    error('SIMUL: stack_solve_algo must be between 0 and 5')
+if options_.stack_solve_algo < 0 || options_.stack_solve_algo > 6
+    error('SIMUL: stack_solve_algo must be between 0 and 6')
 end
 
-if ~options_.block && ~options_.bytecode && options_.stack_solve_algo ~= 0
-    error('SIMUL: you must use stack_solve_algo=0 when not using block nor bytecode option')
+if ~options_.block && ~options_.bytecode && options_.stack_solve_algo ~= 0 ...
+        && options_.stack_solve_algo ~= 6
+    error('SIMUL: you must use stack_solve_algo=0 or stack_solve_algo=6 when not using block nor bytecode option')
 end
 
 if options_.block && ~options_.bytecode && options_.stack_solve_algo == 5
     error('SIMUL: you can''t use stack_solve_algo = 5 without bytecode option')
 end
 
+if (options_.block || options_.bytecode) && options_.stack_solve_algo == 6
+    error('SIMUL: you can''t use stack_solve_algo = 6 with block or bytecode option')
+end
+
 if exist('OCTAVE_VERSION') && options_.stack_solve_algo == 2
     error('SIMUL: you can''t use stack_solve_algo = 2 under Octave')
 end
@@ -86,13 +91,17 @@ else
         [info, oo_.endo_simul]=bytecode('dynamic');
         mexErrCheck('bytecode', info);
     else
-        if M_.maximum_endo_lead == 0
-            error('SIMUL: purely backward models are not supported')
-        elseif M_.maximum_endo_lag == 1 && M_.maximum_endo_lead == 1
-        sim1 ;
-        else % For purely forward models
-            simk;
-        end;
+        if M_.maximum_endo_lead == 0 % Purely backward model
+            sim1_purely_backward;
+        elseif M_.maximum_endo_lag == 0 % Purely forward model
+            sim1_purely_forward;
+        else % General case
+            if options_.stack_solve_algo == 0
+                sim1;
+            else % stack_solve_algo = 6
+                sim1_lbj;
+            end
+        end
     end;
 end;
 
diff --git a/matlab/simul_backward_nonlinear_model.m b/matlab/simul_backward_nonlinear_model.m
new file mode 100644
index 0000000000000000000000000000000000000000..546990cb5eb656cd581f22117b77937563febcfc
--- /dev/null
+++ b/matlab/simul_backward_nonlinear_model.m
@@ -0,0 +1,109 @@
+function DynareOutput = simul_backward_nonlinear_model(sample_size,DynareOptions,DynareModel,DynareOutput)
+
+%@info:
+%! @deftypefn {Function File} {@var{DynareOutput} =} simul_backward_nonlinear_model (@var{sample_size},@var{DynareOptions}, @var{DynareModel}, @var{DynareOutput})
+%! @anchor{@simul_backward_nonlinear_model}
+%! @sp 1
+%! Simulates a stochastic non linear backward looking model with arbitrary precision (a deterministic solver is used).
+%! @sp 2
+%! @strong{Inputs}
+%! @sp 1
+%! @table @ @var
+%! @item sample_size
+%! Scalar integer, size of the sample to be generated.
+%! @item DynareOptions
+%! Matlab/Octave structure (Options used by Dynare).
+%! @item DynareDynareModel
+%! Matlab/Octave structure (Description of the model).
+%! @item DynareOutput
+%! Matlab/Octave structure (Results reported by Dynare).
+%! @end table
+%! @sp 1
+%! @strong{Outputs}
+%! @sp 1
+%! @table @ @var
+%! @item DynareOutput
+%! Matlab/Octave structure (Results reported by Dynare).
+%! @end table
+%! @sp 2
+%! @strong{This function is called by:}
+%! @sp 2
+%! @strong{This function calls:}
+%! @ref{dynTime}
+%!
+%! @end deftypefn
+%@eod:
+
+% Copyright (C) 2012 Dynare Team
+% stephane DOT adjemian AT univ DASH lemans DOT fr
+%
+% 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 DynareModel.maximum_lead
+    error(['simul_backward_nonlinear_model:: The specified model is not backward looking!'])
+end
+
+% Set the covariance matrix of the structural innovations.
+variances = diag(DynareModel.Sigma_e);
+number_of_shocks = length(DynareModel.Sigma_e);
+positive_var_indx = find(variances>0);
+effective_number_of_shocks = length(positive_var_indx);
+covariance_matrix = DynareModel.Sigma_e(positive_var_indx,positive_var_indx);
+covariance_matrix_upper_cholesky = chol(covariance_matrix);
+
+% Set seed to its default state.
+if DynareOptions.bnlms.set_dynare_seed_to_default
+    set_dynare_seed('default');
+end
+
+% Simulate structural innovations.
+switch DynareOptions.bnlms.innovation_distribution
+  case 'gaussian'
+      DynareOutput.bnlms.shocks = randn(sample_size,effective_number_of_shocks)*covariance_matrix_upper_cholesky;
+  otherwise
+    error(['simul_backward_nonlinear_model:: ' DynareOption.bnlms.innovation_distribution ' distribution for the structural innovations is not (yet) implemented!'])
+end
+
+% Put the simulated innovations in DynareOutput.exo_simul.
+DynareOutput.exo_simul = zeros(sample_size,number_of_shocks);
+DynareOutput.exo_simul(:,positive_var_indx) = DynareOutput.bnlms.shocks;
+DynareOutput.exo_simul = [zeros(1,number_of_shocks); DynareOutput.exo_simul];
+
+% Get usefull vector of indices.
+ny0 = nnz(DynareModel.lead_lag_incidence(2,:));
+ny1 = nnz(DynareModel.lead_lag_incidence(1,:));
+iy1 = find(DynareModel.lead_lag_incidence(1,:)>0);
+idx = 1:DynareModel.endo_nbr;
+jdx = idx+ny1;
+hdx = 1:ny1;
+
+% Get the name of the dynamic model routine.
+model_dynamic = str2func([DynareModel.fname,'_dynamic']);
+
+% initialization of vector y.
+y = NaN(length(idx)+ny1,1);
+
+% initialization of the returned simulations.
+DynareOutput.endo_simul = NaN(DynareModel.endo_nbr,sample_size+1);
+DynareOutput.endo_simul(:,1) = DynareOutput.steady_state;
+
+% Simulations (call a Newton-like algorithm for each period).
+for it = 2:sample_size+1
+    y(jdx) = DynareOutput.endo_simul(:,it-1); % A good guess for the initial conditions is the previous values for the endogenous variables.
+    y(hdx) = y(jdx(iy1));                     % Set lagged variables.
+    y(jdx) = solve1(model_dynamic, y, idx, jdx, 1, 1, DynareOutput.exo_simul, DynareModel.params, DynareOutput.steady_state, it);
+    DynareOutput.endo_simul(:,it) = y(jdx);
+end
\ No newline at end of file
diff --git a/matlab/simulated_moment_uncertainty.m b/matlab/simulated_moment_uncertainty.m
index f40be9497715f1f4c53764d824b01b1359ae616b..0815c7a6b00cb8c71c333b7a90df366275b1454b 100644
--- a/matlab/simulated_moment_uncertainty.m
+++ b/matlab/simulated_moment_uncertainty.m
@@ -1,7 +1,7 @@
 function [cmm, mm] = simulated_moment_uncertainty(indx, periods, replic)
 
 %
-% Copyright (C) 2009-2010 Dynare Team
+% Copyright (C) 2009-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/simult.m b/matlab/simult.m
index 0c277ae4ea27c7d67b1afe0e9a06389b07c6e0c8..31c594cf53171da1edc106cb5957ddc61e5b980f 100644
--- a/matlab/simult.m
+++ b/matlab/simult.m
@@ -1,19 +1,51 @@
-function y_=simult(y0, dr)
-% function y_=simult(y0, dr)
-% Recursive Monte Carlo simulations
-%
-% INPUTS
-%    y0:    vector of variables in initial period of the simulation
-%    dr:    structure of decisions rules for stochastic simulations
-%
-% OUTPUTS
-%    y_:    stochastic simulations results
-%
-% SPECIAL REQUIREMENTS
-%    none
-%  
+function [y_,DynareResults] =simult(y0, dr,DynareModel,DynareOptions,DynareResults)
+% Simulate a DSGE model (perturbation approach).
+
+%@info:
+%! @deftypefn {Function File} {[@var{y_}, @var{DynareResults}] =} simult (@var{y0},@var{dr},@var{DynareModel},@var{DynareOptions},@var{DynareResults})
+%! @anchor{simult}
+%! @sp 1
+%! Simulate a DSGE model (perturbation approach).
+%! @sp 2
+%! @strong{Inputs}
+%! @sp 1
+%! @table @ @var
+%! @item y0
+%! Vector of doubles, initial conditions.
+%! @item dr
+%! Matlab's structure describing decision and transition rules.
+%! @item DynareModel
+%! Matlab's structure describing the model (initialized by dynare, see @ref{M_})
+%! @item DynareOptions
+%! Matlab's structure describing the current options (initialized by dynare, see @ref{options_}).
+%! @item DynareResults
+%! Matlab's structure gathering the results (see @ref{oo_}).
+%! @end table
+%! @sp 2
+%! @strong{Outputs}
+%! @sp 1
+%! @table @ @var
+%! @item y_
+%! Matrix of doubles, simulated time series for all the endogenous variables (one per row).
+%! @item DynareResults
+%! Matlab's structure gathering the results (see @ref{oo_}).
+%! @end table
+%! @sp 2
+%! @strong{This function is called by:}
+%! @sp 1
+%! @ref{non_linear_dsge_likelihood}, @ref{pea/pea_initialization}, @ref{stoch_simul}
+%! @sp 2
+%! @strong{This function calls:}
+%! @sp 1
+%! @ref{simult_}
+%! @sp 2
+%! @strong{Remarks}
+%! @sp 1
+%! If the routine is called with only one output argument, then field exo_simul (structural innovations) is not updated.
+%! @end deftypefn
+%@eod:
 
-% Copyright (C) 2001-2011 Dynare Team
+% Copyright (C) 2001-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -30,31 +62,27 @@ function y_=simult(y0, dr)
 % 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_ oo_
-
-order = options_.order;
-replic = options_.replic;
-
-if replic == 0
-    replic = 1;
-end
+order = DynareOptions.order;
+replic = DynareOptions.simul_replic;
 
 if replic > 1
-    fname = [M_.fname,'_simul'];
+    fname = [DynareModel.fname,'_simul'];
     fh = fopen(fname,'w+');
 end
 
 % eliminate shocks with 0 variance
-i_exo_var = setdiff([1:M_.exo_nbr],find(diag(M_.Sigma_e) == 0));
+i_exo_var = setdiff([1:DynareModel.exo_nbr],find(diag(DynareModel.Sigma_e) == 0));
 nxs = length(i_exo_var);
-oo_.exo_simul = zeros(options_.periods,M_.exo_nbr);
-chol_S = chol(M_.Sigma_e(i_exo_var,i_exo_var));
+DynareResults.exo_simul = zeros(DynareOptions.periods,DynareModel.exo_nbr);
+chol_S = chol(DynareModel.Sigma_e(i_exo_var,i_exo_var));
 
 for i=1:replic
-    if ~isempty(M_.Sigma_e)
-        oo_.exo_simul(:,i_exo_var) = randn(options_.periods,nxs)*chol_S;
+    if ~isempty(DynareModel.Sigma_e)
+        % we fill the shocks row wise to have the same values
+        % independently of the length of the simulation
+        DynareResults.exo_simul(:,i_exo_var) = randn(nxs,DynareOptions.periods)'*chol_S;
     end
-    y_ = simult_(y0,dr,oo_.exo_simul,order);
+    y_ = simult_(y0,dr,DynareResults.exo_simul,order);
     % elimninating initial value
     y_ = y_(:,2:end);
     if replic > 1
@@ -64,4 +92,4 @@ end
 
 if replic > 1
     fclose(fh);
-end
+end
\ No newline at end of file
diff --git a/matlab/simult_.m b/matlab/simult_.m
index 1bcc12725bcab40b7e894e9564b41cf311dc4124..4e5f23ee90e19fcc457af7d2694f696f9184177f 100644
--- a/matlab/simult_.m
+++ b/matlab/simult_.m
@@ -35,6 +35,8 @@ function y_=simult_(y0,dr,ex_,iorder)
 global M_ options_
 
 iter = size(ex_,1);
+endo_nbr = M_.endo_nbr;
+exo_nbr = M_.exo_nbr;
 
 y_ = zeros(size(y0,1),iter+M_.maximum_lag);
 y_(:,1) = y0;
@@ -51,19 +53,19 @@ if ~options_.k_order_solver
     end
 end
 
-if options_.k_order_solver% Call dynare++ routines.
-    ex_ = [zeros(1,M_.exo_nbr); ex_];
+if options_.k_order_solver && ~options_.pruning % Call dynare++ routines.
+    ex_ = [zeros(1,exo_nbr); ex_];
     switch options_.order
       case 1
-        [err, y_] = dynare_simul_(1,dr.nstatic,dr.npred-dr.nboth,dr.nboth,dr.nfwrd,M_.exo_nbr, ...
+        [err, y_] = dynare_simul_(1,dr.nstatic,dr.npred-dr.nboth,dr.nboth,dr.nfwrd,exo_nbr, ...
                                   y_(dr.order_var,1),ex_',M_.Sigma_e,options_.DynareRandomStreams.seed,dr.ys(dr.order_var),...
-                                  zeros(M_.endo_nbr,1),dr.g_1);
+                                  zeros(endo_nbr,1),dr.g_1);
       case 2
-        [err, y_] = dynare_simul_(2,dr.nstatic,dr.npred-dr.nboth,dr.nboth,dr.nfwrd,M_.exo_nbr, ...
+        [err, y_] = dynare_simul_(2,dr.nstatic,dr.npred-dr.nboth,dr.nboth,dr.nfwrd,exo_nbr, ...
                                   y_(dr.order_var,1),ex_',M_.Sigma_e,options_.DynareRandomStreams.seed,dr.ys(dr.order_var),dr.g_0, ...
                                   dr.g_1,dr.g_2);
       case 3
-        [err, y_] = dynare_simul_(3,dr.nstatic,dr.npred-dr.nboth,dr.nboth,dr.nfwrd,M_.exo_nbr, ...
+        [err, y_] = dynare_simul_(3,dr.nstatic,dr.npred-dr.nboth,dr.nboth,dr.nfwrd,exo_nbr, ...
                                   y_(dr.order_var,1),ex_',M_.Sigma_e,options_.DynareRandomStreams.seed,dr.ys(dr.order_var),dr.g_0, ...
                                   dr.g_1,dr.g_2,dr.g_3);
       otherwise
@@ -78,11 +80,11 @@ else
         else
             k2 = [];
         end;
-        order_var = 1:M_.endo_nbr;
+        order_var = 1:endo_nbr;
         dr.order_var = order_var;
     else
         k2 = dr.kstate(find(dr.kstate(:,2) <= M_.maximum_lag+1),[1 2]);
-        k2 = k2(:,1)+(M_.maximum_lag+1-k2(:,2))*M_.endo_nbr;
+        k2 = k2(:,1)+(M_.maximum_lag+1-k2(:,2))*endo_nbr;
         order_var = dr.order_var;
     end;
     
@@ -134,6 +136,56 @@ else
                 y_(dr.order_var,i) = constant + dr.ghx*yhat + dr.ghu*epsilon ...
                     + abcOut1 + abcOut2 + abcOut3;
             end
+         end
+      case 3
+        % only with pruning
+        ghx = dr.ghx;
+        ghu = dr.ghu;
+        ghxx = dr.ghxx;
+        ghxu = dr.ghxu;
+        ghuu = dr.ghuu;
+        ghs2 = dr.ghs2;
+        ghxxx = dr.ghxxx;
+        ghxxu = dr.ghxxu;
+        ghxuu = dr.ghxuu;
+        ghuuu = dr.ghuuu;
+        ghxss = dr.ghxss;
+        ghuss = dr.ghuss;
+        threads = options_.threads.kronecker.A_times_B_kronecker_C;
+        npred = dr.npred;
+        ipred = dr.nstatic+(1:npred);
+        yhat1 = y0(order_var(k2))-dr.ys(order_var(k2));
+        yhat2 = zeros(npred,1);
+        yhat3 = zeros(npred,1);
+        for i=2:iter+M_.maximum_lag
+            u = ex_(i-1,:)';
+            [gyy, err] = A_times_B_kronecker_C(ghxx,yhat1,threads);
+            mexErrCheck('A_times_B_kronecker_C', err);
+            [guu, err] = A_times_B_kronecker_C(ghuu,u,threads);
+            mexErrCheck('A_times_B_kronecker_C', err);
+            [gyu, err] = A_times_B_kronecker_C(ghxu,yhat1,u,threads);
+            mexErrCheck('A_times_B_kronecker_C', err);
+            y2a = kron(yhat1,yhat1);
+            [gyyy, err] = A_times_B_kronecker_C(ghxxx,y2a,yhat1,threads);
+            mexErrCheck('A_times_B_kronecker_C', err);
+            u2a = kron(u,u);
+            [guuu, err] = A_times_B_kronecker_C(ghuuu,u2a,u,threads);
+            mexErrCheck('A_times_B_kronecker_C', err);
+            yu = kron(yhat1,u);
+            [gyyu, err] = A_times_B_kronecker_C(ghxxu,yhat1,yu,threads);
+            mexErrCheck('A_times_B_kronecker_C', err);
+            [gyuu, err] = A_times_B_kronecker_C(ghxuu,yu,u,threads);
+            mexErrCheck('A_times_B_kronecker_C', err);
+            [gyy12, err] = A_times_B_kronecker_C(ghxx,yhat1,yhat2,threads);
+            mexErrCheck('A_times_B_kronecker_C', err);
+            yhat3 = ghx*yhat3 + gyyy + guuu + 3*(gyyu + gyuu  ...
+                    + gyy12 + ghxss*yhat1 + ghuss*u);
+            yhat2 = ghx*yhat2 + gyy + guu + 2*gyu + ghs2;
+            yhat1 = ghx*yhat1 + ghu*u;
+            y_(order_var,i) = yhat1 + (1/2)*yhat2 + (1/6)*yhat3;
+            yhat1 = yhat1(ipred);
+            yhat2 = yhat2(ipred);
+            yhat3 = yhat3(ipred);
         end
     end
 end
\ No newline at end of file
diff --git a/matlab/solve1.m b/matlab/solve1.m
index 5705e2c7932fe98fb87a211bc6138d947e9a57a8..74111276f6468499888ea48c1f86f46792d75f02 100644
--- a/matlab/solve1.m
+++ b/matlab/solve1.m
@@ -20,7 +20,7 @@ function [x,check] = solve1(func,x,j1,j2,jacobian_flag,bad_cond_flag,varargin)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2001-2010 Dynare Team
+% Copyright (C) 2001-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/solve_perfect_foresight_model.m b/matlab/solve_perfect_foresight_model.m
index f6543fc822e4d51856b2296e5798d9417a8767c4..2f0dade88329f623a65595757b0abe8ae0f99039 100644
--- a/matlab/solve_perfect_foresight_model.m
+++ b/matlab/solve_perfect_foresight_model.m
@@ -1,5 +1,22 @@
 function [flag,endo_simul,err] = solve_perfect_foresight_model(endo_simul,exo_simul,pfm)
 
+% Copyright (C) 2012 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/>.
+
     flag = 0;
     err = 0;
     stop = 0;
diff --git a/matlab/solve_stochastic_perfect_foresight_model.m b/matlab/solve_stochastic_perfect_foresight_model.m
index d2ce4e59a07f86ab2647e09c42df8266c3d249d0..525ed9f2d4d7c9dc5bc82ed5ac834ba8d218a768 100644
--- a/matlab/solve_stochastic_perfect_foresight_model.m
+++ b/matlab/solve_stochastic_perfect_foresight_model.m
@@ -1,5 +1,22 @@
 function [flag,endo_simul,err] = solve_stochastic_perfect_foresight_model(endo_simul,exo_simul,pfm,nnodes,order)
 
+% Copyright (C) 2012 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/>.
+
     flag = 0;
     err = 0;
     stop = 0;
@@ -193,8 +210,8 @@ function [flag,endo_simul,err] = solve_stochastic_perfect_foresight_model(endo_s
             end
             flag = 0;% Convergency obtained.
             endo_simul = reshape(Y(:,1),ny,periods+2);%Y(ny+(1:ny),1);
-            figure;plot(Y(16:ny:(periods+2)*ny,:))
-            pause
+                                                      %            figure;plot(Y(16:ny:(periods+2)*ny,:))
+                                                      %            pause
             break
         end
         dy = -A\res;
diff --git a/matlab/steady.m b/matlab/steady.m
index 4b1d14f04534f5a81ef71b6aed09ec3b519fd490..54af1e7cd67a2a6bf333184d444e662345940254 100644
--- a/matlab/steady.m
+++ b/matlab/steady.m
@@ -11,7 +11,7 @@ function steady()
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2001-2010 Dynare Team
+% Copyright (C) 2001-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/stoch_simul.m b/matlab/stoch_simul.m
index 2295c6d0f13c661bf113b67a44cf66024c47aaf6..519f4df7aa0af8d9fe05f687b0b6a397fd2cdcf6 100644
--- a/matlab/stoch_simul.m
+++ b/matlab/stoch_simul.m
@@ -1,6 +1,6 @@
 function info=stoch_simul(var_list)
 
-% Copyright (C) 2001-2011 Dynare Team
+% Copyright (C) 2001-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -60,9 +60,9 @@ if M_.exo_nbr > 0
     oo_.exo_simul= ones(iter_ + M_.maximum_lag + M_.maximum_lead,1) * oo_.exo_steady_state';
 end
 
-check_model;
+check_model(M_);
 
-oo_.dr=set_state_space(dr,M_);
+oo_.dr=set_state_space(dr,M_,options_);
 
 if PI_PCL_solver
     [oo_.dr, info] = PCL_resol(oo_.steady_state,0);
@@ -138,7 +138,8 @@ if options_.periods > 0 && ~PI_PCL_solver
     else
         y0 = M_.endo_histval;
     end
-    oo_.endo_simul = simult(y0,oo_.dr);
+    [ys, oo_] = simult(y0,oo_.dr,M_,options_,oo_);
+    oo_.endo_simul = ys;
     dyn2vec;
 end
 
diff --git a/matlab/stoch_simul_sparse.m b/matlab/stoch_simul_sparse.m
index 1eef7ba2b32ef6c0b3c83af54f289ca871edea25..ecfad0a4d9a9f7ccc112bc5be9e214b1091a5173 100644
--- a/matlab/stoch_simul_sparse.m
+++ b/matlab/stoch_simul_sparse.m
@@ -1,7 +1,7 @@
 function info=stoch_simul_sparse(var_list)
 % This file is a modified version of stoch_simul.m: common parts should be factorized!
 
-% Copyright (C) 2001-2010 Dynare Team
+% Copyright (C) 2001-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -36,7 +36,7 @@ if M_.exo_nbr > 0
     oo_.exo_simul= ones(iter_ + M_.maximum_lag + M_.maximum_lead,1) * oo_.exo_steady_state';
 end
 
-check_model;
+check_model(M_);
 
 [oo_.dr,info,M_,options_,oo_] = resol(0,M_,options_,oo_);
 
@@ -87,7 +87,8 @@ elseif options_.periods ~= 0
     else
         y0 = M_.endo_histval;
     end
-    oo_.endo_simul = simult(y0,oo_.dr);
+    [ys,oo_] = simult(y0,oo_.dr,M_,options_,M_,options_,oo_);
+    oo_.endo_simul = ys;
     dyn2vec;
     if options_.nomoments == 0
         disp_moments(oo_.endo_simul,var_list);
diff --git a/matlab/stochastic_solvers.m b/matlab/stochastic_solvers.m
index 044cc223214a83ac57e4fcd6878b2d3c684fe032..84f2c312fe7cb9f1082ef18db45e79baac3ee49b 100644
--- a/matlab/stochastic_solvers.m
+++ b/matlab/stochastic_solvers.m
@@ -29,7 +29,7 @@ function [dr,info] = stochastic_solvers(dr,task,M_,options_,oo_)
 %   none.
 %  
 
-% Copyright (C) 1996-2009 Dynare Team
+% Copyright (C) 1996-2012 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -48,6 +48,10 @@ function [dr,info] = stochastic_solvers(dr,task,M_,options_,oo_)
 
 info = 0;
 
+if options_.linear
+    options_.order = 1;
+end
+
 if (options_.aim_solver == 1) && (options_.order > 1)
         error('Option "aim_solver" is incompatible with order >= 2')
 end
@@ -57,7 +61,7 @@ if options_.k_order_solver;
         [dr,info] = dyn_risky_steadystate_solver(oo_.steady_state,M_,dr, ...
                                              options_,oo_);
     else
-        dr = set_state_space(dr,M_);
+        dr = set_state_space(dr,M_,options_);
         [dr,info] = k_order_pert(dr,M_,options_,oo_);
     end
     return;
@@ -156,12 +160,6 @@ if M_.maximum_endo_lead == 0
         error(['2nd and 3rd order approximation not implemented for purely ' ...
                'backward models'])
     end
-elseif M_.maximum_endo_lag == 0
-    % purely forward model
-    dr.ghx = [];
-    dr.ghu = -b\jacobia_(:,nz+1:end);
-    dr.eigval = [];
-    dr.rank = 0;
 elseif options_.risky_steadystate
     [dr,info] = dyn_risky_steadystate_solver(oo_.steady_state,M_,dr, ...
                                              options_,oo_);
diff --git a/matlab/thet2tau.m b/matlab/thet2tau.m
index 2ae5b2c5cb6bb47ee1e134012f6f7c814a63f978..79c593fad8b9e50bf8f6cc8da21da07e39cb57fd 100644
--- a/matlab/thet2tau.m
+++ b/matlab/thet2tau.m
@@ -1,4 +1,4 @@
-function tau = thet2tau(params, indx, indexo, flagmoments,mf,nlags,useautocorr)
+function tau = thet2tau(params, M_, oo_, indx, indexo, flagmoments,mf,nlags,useautocorr)
 
 %
 % Copyright (C) 2011 Dynare Team
@@ -18,17 +18,17 @@ function tau = thet2tau(params, indx, indexo, flagmoments,mf,nlags,useautocorr)
 % 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_ oo_ options_
+global options_
 
 if nargin==1,
     indx = [1:M_.param_nbr];
     indexo = [];
 end
 
-if nargin<4,
+if nargin<6,
     flagmoments=0;
 end
-if nargin<7 || isempty(useautocorr),
+if nargin<9 || isempty(useautocorr),
     useautocorr=0;
 end
 
@@ -39,6 +39,13 @@ end
 [A,B,tele,tubbies,M_,options_,oo_] = dynare_resolve(M_,options_,oo_);
 if flagmoments==0,
     tau = [oo_.dr.ys(oo_.dr.order_var); A(:); dyn_vech(B*M_.Sigma_e*B')];
+elseif flagmoments==-1
+    [I,J]=find(M_.lead_lag_incidence');
+    yy0=oo_.dr.ys(I);
+    [residual, g1] = feval([M_.fname,'_dynamic'],yy0, oo_.exo_steady_state', ...
+        M_.params, oo_.dr.ys, 1);
+    tau=[oo_.dr.ys(oo_.dr.order_var); g1(:)];
+
 else
     GAM =  lyapunov_symm(A,B*M_.Sigma_e*B',options_.qz_criterium,options_.lyapunov_complex_threshold);
     k = find(abs(GAM) < 1e-12);
diff --git a/matlab/trace_plot.m b/matlab/trace_plot.m
index 588eadb91a60680b6509648ba9eb0dd57844316c..6554ebc18adfd7a51bbee036b24b71121c24d64b 100644
--- a/matlab/trace_plot.m
+++ b/matlab/trace_plot.m
@@ -17,7 +17,7 @@ function trace_plot(options_,M_,estim_params_,type,blck,name1,name2)
 %        
 % SPECIAL REQUIREMENTS
 
-% Copyright (C) 2003-2009 Dynare Team
+% Copyright (C) 2003-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/uniform_specification.m b/matlab/uniform_specification.m
index 7bd6560684a13ea500c146586932efacdbeb200a..5af782162f3e180209ede22413f3c3463658c27d 100644
--- a/matlab/uniform_specification.m
+++ b/matlab/uniform_specification.m
@@ -16,7 +16,7 @@ function [m,s,p6,p7] = uniform_specification(m,s,p3,p4)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2004-2009 Dynare Team
+% Copyright (C) 2004-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/utilities/tests/dynTest.m b/matlab/utilities/tests/dynTest.m
index fdb530b56c6c63d73db3494c9dfd8d542ab97604..bf59e5b55206cc061df8b209e2bbb1d201ff713d 100644
--- a/matlab/utilities/tests/dynTest.m
+++ b/matlab/utilities/tests/dynTest.m
@@ -32,7 +32,7 @@ function dynTest(fun,dynare_path)
 %! @end deftypefn
 %@eod:
 
-% Copyright (C) 2011 Dynare Team
+% Copyright (C) 2011-2012 Dynare Team
 % stephane DOT adjemian AT univ DASH lemans DOT fr
 %
 % This file is part of Dynare.
diff --git a/matlab/vnorm.m b/matlab/vnorm.m
index 99983f9acadceb6f16e977c9bc7b990595535051..b6bb123d944da1b125d58402e5e90e40e767fe14 100644
--- a/matlab/vnorm.m
+++ b/matlab/vnorm.m
@@ -35,7 +35,7 @@ function y = vnorm(A,varargin)
 %       vnorm(A,[],inf)     % Correct
 %
 %
-% Copyright (C) 2009 Dynare Team
+% Copyright (C) 2009-2011 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/mex/build/matlab/configure.ac b/mex/build/matlab/configure.ac
index 337d39ac0bbe011c6faf28cfe766152d4762e562..4a3f115d79d463506c0a6457f20042f1971fd699 100644
--- a/mex/build/matlab/configure.ac
+++ b/mex/build/matlab/configure.ac
@@ -18,7 +18,7 @@ dnl You should have received a copy of the GNU General Public License
 dnl along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 AC_PREREQ([2.61])
-AC_INIT([dynare], [4.3-unstable])
+AC_INIT([dynare], [4.4-unstable])
 AC_CONFIG_SRCDIR([configure.ac])
 AM_INIT_AUTOMAKE([-Wall -Werror foreign])
 
diff --git a/mex/build/octave/configure.ac b/mex/build/octave/configure.ac
index 6762daefbe9d760a95c15485d71c009885f13356..34855798155da65422b3d43aaead3a97fbdbeaed 100644
--- a/mex/build/octave/configure.ac
+++ b/mex/build/octave/configure.ac
@@ -18,7 +18,7 @@ dnl You should have received a copy of the GNU General Public License
 dnl along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 AC_PREREQ([2.61])
-AC_INIT([dynare], [4.3-unstable])
+AC_INIT([dynare], [4.4-unstable])
 AC_CONFIG_SRCDIR([configure.ac])
 AM_INIT_AUTOMAKE([-Wall -Werror foreign])
 
diff --git a/mex/sources/block_kalman_filter/block_kalman_filter.cc b/mex/sources/block_kalman_filter/block_kalman_filter.cc
index 8b147ecb06525b338ab74332e9fa8ca5ce22b146..207f9e59635202414c96231f4804986de23265c0 100644
--- a/mex/sources/block_kalman_filter/block_kalman_filter.cc
+++ b/mex/sources/block_kalman_filter/block_kalman_filter.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2011 Dynare Team
+ * Copyright (C) 2007-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -21,22 +21,14 @@
 #include <iostream>
 #include <fstream>
 #include <vector>
-
+#ifdef USE_OMP
+# include <omp.h>
+#endif
+#include "block_kalman_filter.h"
 using namespace std;
 //#define BLAS
-
 #define DIRECT
 
-#ifndef DEBUG_EX
-# include <dynmex.h>
-#else
-# include "mex_interface.hh"
-#endif
-
-#include <dynblas.h>
-#include <dynlapack.h>
-
-#define BLOCK
 
 void
 mexDisp(mxArray* P)
@@ -52,66 +44,24 @@ mexDisp(mxArray* P)
         mexPrintf(" %9.4f",M[i+ j * m]);
       mexPrintf("\n");
     }
+  mexEvalString("drawnow;");
 }
 
-/*
-(T,R,Q,H,P,Y,start,mf,kalman_tol,riccati_tol, block)
-% Computes the likelihood of a stationnary state space model.
-%
-% INPUTS
-%    T                      [double]    n*n transition matrix of the state equation.
-%    R                      [double]    n*rr matrix, mapping structural innovations to state variables.
-%    Q                      [double]    rr*rr covariance matrix of the structural innovations.
-%    H                      [double]    pp*pp (or 1*1 =0 if no measurement error) covariance matrix of the measurement errors. 
-%    P                      [double]    n*n variance-covariance matrix with stationary variables
-%    Y                      [double]    pp*smpl matrix of (detrended) data, where pp is the maximum number of observed variables.
-%    start                  [integer]   scalar, likelihood evaluation starts at 'start'.
-%    mf                     [integer]   pp*1 vector of indices.
-%    kalman_tol             [double]    scalar, tolerance parameter (rcond).
-%    riccati_tol            [double]    scalar, tolerance parameter (riccati iteration).
-%
-% OUTPUTS
-%    LIK        [double]    scalar, MINUS loglikelihood
-%    lik        [double]    vector, density of observations in each period.
-%
-% REFERENCES
-%   See "Filtering and Smoothing of State Vector for Diffuse State Space
-%   Models", S.J. Koopman and J. Durbin (2003, in Journal of Time Series
-%   Analysis, vol. 24(1), pp. 85-98).
-%
-% NOTES
-%   The vector "lik" is used to evaluate the jacobian of the likelihood.
-
-% Copyright (C) 2004-2011 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 options_
-smpl = size(Y,2);                               % Sample size.
-n   = size(T,2);                               % Number of state variables.
-pp   = size(Y,1);                               % Maximum number of observed variables.
-a    = zeros(n,1);                             % State vector.
-dF   = 1;                                       % det(F).
-QQ   = R*Q*transpose(R);                        % Variance of R times the vector of structural innovations.
-t    = 0;                                       % Initialization of the time index.
-lik  = zeros(smpl,1);                           % Initialization of the vector gathering the densities.
-LIK  = Inf;                                     % Default value of the log likelihood.
-oldK = Inf;
-notsteady   = 1;                                % Steady state flag.
-F_singular  = 1;
-if block
+
+void
+mexDisp(double* M, int m, int n)
+{
+  mexPrintf("%d x %d\n", m, n);
+  mexEvalString("drawnow;");
+  for (int i = 0; i < m; i++)
+    {
+      for (int j = 0; j < n; j++)
+        mexPrintf(" %9.4f",M[i+ j * m]);
+      mexPrintf("\n");
+    }
+  mexEvalString("drawnow;");
+}
+/*if block
     %nz_state_var = M_.nz_state_var;
     while notsteady && t<smpl
         t  = t+1;
@@ -163,28 +113,7 @@ else
         end
     end
 end
-
-if F_singular
-    error('The variance of the forecast error remains singular until the end of the sample')
-end
-
-if t < smpl
-    t0 = t+1;
-    while t < smpl
-        t = t+1;
-        v = Y(:,t)-a(mf);
-        a = T*(a+K*v);
-        lik(t) = transpose(v)*iF*v;
-    end
-    lik(t0:smpl) = lik(t0:smpl) + log(dF);
-end    
-
-% adding log-likelihhod constants
-lik = (lik + pp*log(2*pi))/2;
-
-LIK = sum(lik(start:end)); % Minus the log-likelihood.*/
-
-
+*/
 
 bool
 not_all_abs_F_bellow_crit(double* F, int size, double crit)
@@ -212,116 +141,116 @@ det(double* F, int dim, lapack_int* ipiv)
       det *= -F[i + i * dim];
   return det;
 }
-void
-mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
+
+
+
+BlockKalmanFilter::BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[], double *P_mf[], double *v_pp[], double *K[], double *v_n[], double *a[], double *K_P[], double *P_t_t1[], double *tmp[], double *P[])
 {
   if (nlhs > 3)
-    DYN_MEX_FUNC_ERR_MSG_TXT("kalman_filter provides at most 3 output argument.");
-  if (nrhs != 13)
-    DYN_MEX_FUNC_ERR_MSG_TXT("kalman_filter requires exactly 13 input arguments.");
-//(T,R,Q,H,P,Y,start,mf,kalman_tol,riccati_tol, block)
-  mxArray *pT = mxDuplicateArray(prhs[0]);
-  mxArray *pR = mxDuplicateArray(prhs[1]);
-  mxArray *pQ = mxDuplicateArray(prhs[2]);
-  mxArray *pH = mxDuplicateArray(prhs[3]);
-  mxArray *pP = mxDuplicateArray(prhs[4]);
-  mxArray *pY = mxDuplicateArray(prhs[5]);
+    DYN_MEX_FUNC_ERR_MSG_TXT("block_kalman_filter provides at most 3 output argument.");
+  if (nrhs != 13 && nrhs != 16)
+    DYN_MEX_FUNC_ERR_MSG_TXT("block_kalman_filter requires exactly \n  13 input arguments for standard Kalman filter \nor\n  16 input arguments for missing observations Kalman filter.");
+  if (nrhs == 16) 
+    missing_observations = true;
+  else
+    missing_observations = false;
+  if (missing_observations)
+    {
+      if (! mxIsCell (prhs[0]))
+        DYN_MEX_FUNC_ERR_MSG_TXT("the first input argument of block_missing_observations_kalman_filter must be a Call Array.");
+      pdata_index = prhs[0];
+      if (! mxIsDouble (prhs[1]))
+        DYN_MEX_FUNC_ERR_MSG_TXT("the second input argument of block_missing_observations_kalman_filter must be a scalar.");
+      number_of_observations = ceil(mxGetScalar(prhs[1]));
+      if (! mxIsDouble (prhs[2]))
+        DYN_MEX_FUNC_ERR_MSG_TXT("the third input argument of block_missing_observations_kalman_filter must be a scalar.");
+      no_more_missing_observations = ceil(mxGetScalar(prhs[2]));
+      pT = mxDuplicateArray(prhs[3]);
+      pR = mxDuplicateArray(prhs[4]);
+      pQ = mxDuplicateArray(prhs[5]);
+      pH = mxDuplicateArray(prhs[6]);
+      pP = mxDuplicateArray(prhs[7]);
+      pY = mxDuplicateArray(prhs[8]);
+      start = mxGetScalar(prhs[9]);
+      mfd = (double*)mxGetData(prhs[10]);
+      kalman_tol = mxGetScalar(prhs[11]);
+      riccati_tol = mxGetScalar(prhs[12]);
+      nz_state_var = (double*)mxGetData(prhs[13]);
+      n_diag = mxGetScalar(prhs[14]);
+      pure_obs = mxGetScalar(prhs[15]);
+    }
+  else
+    {
+      no_more_missing_observations = 0;
+      pT = mxDuplicateArray(prhs[0]);
+      pR = mxDuplicateArray(prhs[1]);
+      pQ = mxDuplicateArray(prhs[2]);
+      pH = mxDuplicateArray(prhs[3]);
+      pP = mxDuplicateArray(prhs[4]);
+      pY = mxDuplicateArray(prhs[5]);
+      start = mxGetScalar(prhs[6]);
+      /*Defining the initials values*/
+      n   = mxGetN(pT);           // Number of state variables.
+      pp   = mxGetM(pY);          // Maximum number of observed variables.
+      smpl = mxGetN(pY);          // Sample size.          ;
+      mfd = (double*)mxGetData(prhs[7]);
+      kalman_tol = mxGetScalar(prhs[8]);
+      riccati_tol = mxGetScalar(prhs[9]);
+      nz_state_var = (double*)mxGetData(prhs[10]);
+      n_diag = mxGetScalar(prhs[11]);
+      pure_obs = mxGetScalar(prhs[12]);
+    }
+  T = mxGetPr(pT);
+  R = mxGetPr(pR);
+  Q = mxGetPr(pQ);
+  H = mxGetPr(pH);
+  *P = mxGetPr(pP);
+  Y = mxGetPr(pY);
   
-  double *T = mxGetPr(pT);
-  double *R = mxGetPr(pR);
-  double *Q = mxGetPr(pQ);
-  double *H = mxGetPr(pH);
-  double *P = mxGetPr(pP);
-  double *Y = mxGetPr(pY);
-  int start = mxGetScalar(prhs[6]);
-  double* mfd = (double*)mxGetData(prhs[7]);
+  n   = mxGetN(pT);           // Number of state variables.
+  pp   = mxGetM(pY);          // Maximum number of observed variables.
+  smpl = mxGetN(pY);          // Sample size.          ;
+  n_state = n - pure_obs;
+
   
-    
-  double kalman_tol = mxGetScalar(prhs[8]);
-  double riccati_tol = mxGetScalar(prhs[9]);
-  int pure_obs = mxGetScalar(prhs[12]);
   
-  /* Reading the sparse structure of matrix in (§A) */
-  typedef struct 
-  {
-      int indx_1;
-      int indx_2;
-      int indx_3;
-  } t_Var;
-
-  /*Defining the initials values*/
-  int smpl = mxGetN(pY);                                 // Sample size.          ;
-  int n   = mxGetN(pT);                                  // Number of state variables.
-  lapack_int pp   = mxGetM(pY);                          // Maximum number of observed variables.
-  int n_state = n - pure_obs;
-  int n_shocks = mxGetM(pQ);
-
-
-#ifdef DIRECT  
-  double* nz_state_var = (double*)mxGetData(prhs[10]);
-  int *i_nz_state_var = (int*)mxMalloc(n*sizeof(int));
-  for (int i = 0; i < n; i++)
-    i_nz_state_var[i] = nz_state_var[i];
+  /*mexPrintf("T\n");
+  mexDisp(pT);*/
 
-  int n_diag = mxGetScalar(prhs[11]);
-#else
-  mxArray *M_;
-  M_ = mexGetVariable("global", "M_");
-  if (M_ == NULL)
-    mexErrMsgTxt(" in main, global variable not found: M_\n");
-  mxArray *mxa = mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "fname"));
-  int buflen = mxGetM(mxa) * mxGetN(mxa) + 1;
-  char *fname;
-  fname = (char *) mxCalloc(buflen+1, sizeof(char));
-  int status = mxGetString(mxa, fname, buflen);
-  fname[buflen] = ' ';
-  if (status != 0)
-    mexWarnMsgTxt("Not enough space. Filename is truncated.");
-  string file_name = fname;
-  file_name.append(".kfi");
+  H_size = mxGetN(pH) * mxGetM(pH);
   
-  ifstream KF_index_file;
-  KF_index_file.open(file_name.c_str(), ios::in | ios::binary);
-  int n_diag;
-  KF_index_file.read(reinterpret_cast<char *>(&n_diag), sizeof(n_diag));
-  /*mexPrintf("n_diag=%d\n",n_diag);*/
   
-  int size_index_KF;
-  KF_index_file.read(reinterpret_cast<char *>(&size_index_KF), sizeof(size_index_KF));
-  //mexPrintf("size_index_KF=%d\n", size_index_KF);
-  t_Var *Var = (t_Var*)mxMalloc(size_index_KF * sizeof(t_Var));
-  KF_index_file.read(reinterpret_cast<char *>(Var), size_index_KF * sizeof(t_Var));
+  n_shocks = mxGetM(pQ);
   
-  int size_index_KF_2;
-  KF_index_file.read(reinterpret_cast<char *>(&size_index_KF_2), sizeof(size_index_KF_2));
-  //mexPrintf("size_index_KF_2=%d\n", size_index_KF_2);
-  t_Var *Var_2 = (t_Var*)mxMalloc(size_index_KF_2 * sizeof(t_Var));
-  KF_index_file.read(reinterpret_cast<char *>(Var_2), size_index_KF_2 * sizeof(t_Var));
-  KF_index_file.close();
-#endif
+  if (missing_observations)
+    if (mxGetNumberOfElements(pdata_index) != (unsigned int)smpl)
+      DYN_MEX_FUNC_ERR_MSG_TXT("the number of element in the cell array passed to block_missing_observation_kalman_filter as first argument has to be equal to the smpl size");
+  
+  i_nz_state_var = (int*)mxMalloc(n*sizeof(int));
+  for (int i = 0; i < n; i++)
+    i_nz_state_var[i] = nz_state_var[i];
 
-  mxArray* pa = mxCreateDoubleMatrix(n, 1, mxREAL);         // State vector.
-  double* a = mxGetPr(pa);
-  double* tmp_a = (double*)mxMalloc(n * sizeof(double));
-  double dF = 0.0;                                            // det(F).
-  mxArray* p_tmp = mxCreateDoubleMatrix(n, n_state, mxREAL);
-  double *tmp = mxGetPr(p_tmp);
-  mxArray* p_tmp1 = mxCreateDoubleMatrix(n, n_shocks, mxREAL);
-  double *tmp1 = mxGetPr(p_tmp1);
-  int t = 0;                                               // Initialization of the time index.
-  mxArray* plik  = mxCreateDoubleMatrix(smpl, 1, mxREAL);
-  double* lik = mxGetPr(plik);
-  double Inf =  mxGetInf();                                   
-  double LIK  = 0.0;                                          // Default value of the log likelihood.
-
-  bool notsteady   = true;                                 // Steady state flag.
-  bool F_singular  = true;
-  double* v_pp = (double*)mxMalloc(pp * sizeof(double));
-  double* v_n = (double*)mxMalloc(n * sizeof(double));
-  int* mf = (int*)mxMalloc(pp * sizeof(int));
+  pa = mxCreateDoubleMatrix(n, 1, mxREAL);         // State vector.
+  *a = mxGetPr(pa);
+  tmp_a = (double*)mxMalloc(n * sizeof(double));
+  dF = 0.0;                                            // det(F).
+  p_tmp = mxCreateDoubleMatrix(n, n_state, mxREAL);
+  *tmp = mxGetPr(p_tmp);
+  p_tmp1 = mxCreateDoubleMatrix(n, n_shocks, mxREAL);
+  tmp1 = mxGetPr(p_tmp1);
+  t = 0;                                               // Initialization of the time index.
+  plik  = mxCreateDoubleMatrix(smpl, 1, mxREAL);
+  lik = mxGetPr(plik);
+  Inf =  mxGetInf();                                   
+  LIK  = 0.0;                                          // Default value of the log likelihood.
+  notsteady   = true;                                 // Steady state flag.
+  F_singular  = true;
+  *v_pp = (double*)mxMalloc(pp * sizeof(double));
+  *v_n = (double*)mxMalloc(n * sizeof(double));
+  mf = (int*)mxMalloc(pp * sizeof(int));
   for (int i = 0; i < pp; i++)
     mf[i] = mfd[i] - 1;
-  double pi = atan2((double)0.0,(double)-1.0);
+  pi = atan2((double)0.0,(double)-1.0);
   
   /*compute QQ = R*Q*transpose(R)*/                        // Variance of R times the vector of structural innovations.;
   // tmp = R * Q;
@@ -335,8 +264,8 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
       }
 
   // QQ = tmp * transpose(R)
-  mxArray* pQQ = mxCreateDoubleMatrix(n, n, mxREAL);
-  double* QQ = mxGetPr(pQQ);
+  pQQ = mxCreateDoubleMatrix(n, n, mxREAL);
+  QQ = mxGetPr(pQQ);
   for (int i = 0; i < n; i++)
     for (int j = i; j < n; j++)
       {
@@ -346,112 +275,185 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
         QQ[i + j * n] = QQ[j + i * n] = res;
       }
   mxDestroyArray(p_tmp1);
-
-  mxArray* pv = mxCreateDoubleMatrix(pp, 1, mxREAL);
-  double* v = mxGetPr(pv);
-  mxArray* pF =  mxCreateDoubleMatrix(pp, pp, mxREAL);
-  double* F = mxGetPr(pF);
-  mxArray* piF =  mxCreateDoubleMatrix(pp, pp, mxREAL);
-  double* iF = mxGetPr(piF);
-  lapack_int lw = pp * 4;
-  double* w = (double*)mxMalloc(lw * sizeof(double));
-  lapack_int* iw = (lapack_int*)mxMalloc(pp * sizeof(lapack_int));
-  lapack_int* ipiv = (lapack_int*)mxMalloc(pp * sizeof(lapack_int));
-  lapack_int info = 0;
-  double anorm, rcond;
-  #ifdef BLAS
-  mxArray* p_P_t_t1 = mxCreateDoubleMatrix(n, n, mxREAL);
-  #else
-  mxArray* p_P_t_t1 = mxCreateDoubleMatrix(n_state, n_state, mxREAL);
-  #endif
-  double* P_t_t1 = mxGetPr(p_P_t_t1);
-  mxArray* pK = mxCreateDoubleMatrix(n, pp, mxREAL);
-  double* K = mxGetPr(pK);
-  #ifdef BLAS
-  mxArray* p_K_P = mxCreateDoubleMatrix(n, n, mxREAL);
-  #else
-  mxArray* p_K_P = mxCreateDoubleMatrix(n_state, n_state, mxREAL);
-  #endif
-  double* K_P = mxGetPr(p_K_P);
-  double* oldK  = (double*)mxMalloc(n * pp * sizeof(double));
-  double* P_mf = (double*)mxMalloc(n * pp * sizeof(double));
-  for (int i = 0; i < pp; i++)
-    oldK[i] = Inf;
   
+  pv = mxCreateDoubleMatrix(pp, 1, mxREAL);
+  v = mxGetPr(pv);
+  pF =  mxCreateDoubleMatrix(pp, pp, mxREAL);
+  F = mxGetPr(pF);
+  piF =  mxCreateDoubleMatrix(pp, pp, mxREAL);
+  iF = mxGetPr(piF);
+  lw = pp * 4;
+  w = (double*)mxMalloc(lw * sizeof(double));
+  iw = (lapack_int*)mxMalloc(pp * sizeof(lapack_int));
+  ipiv = (lapack_int*)mxMalloc(pp * sizeof(lapack_int));
+  info = 0;
+  p_P_t_t1 = mxCreateDoubleMatrix(n_state, n_state, mxREAL);
+  *P_t_t1 = mxGetPr(p_P_t_t1);
+  pK = mxCreateDoubleMatrix(n, pp, mxREAL);
+  *K = mxGetPr(pK);
+  p_K_P = mxCreateDoubleMatrix(n_state, n_state, mxREAL);
+  *K_P = mxGetPr(p_K_P);
+  oldK  = (double*)mxMalloc(n * pp * sizeof(double));
+  *P_mf = (double*)mxMalloc(n * pp * sizeof(double));
+  for (int i = 0; i < n  * pp; i++)
+    oldK[i] = Inf;
+}
+
+void 
+BlockKalmanFilter::block_kalman_filter_ss(double *P_mf, double *v_pp, double *K, double *v_n, double *a, double *K_P, double *P_t_t1, double *tmp, double *P)
+{
+  if (t+1 < smpl)
+    {
+      while (t < smpl)
+        {
+          //v = Y(:,t)-a(mf);
+          for (int i = 0; i < pp; i++)
+            v[i]  = Y[i + t * pp] - a[mf[i]];
+          
+          //a = T*(a+K*v);
+          for (int i = pure_obs; i < n; i++)
+            {
+              double res = 0.0;
+              for (int j = 0; j < pp; j++)
+                res += K[j  * n + i] * v[j];
+              v_n[i] = res + a[i];
+            }
+          for (int i = 0; i < n; i++)
+            {
+              double res = 0.0;
+              for (int j = pure_obs; j < n; j++)
+                res += T[j  * n + i] * v_n[j];
+              a[i] = res;
+            }
+        
+          //lik(t) = transpose(v)*iF*v;
+          for (int i = 0; i < pp; i++)
+            {
+              double res = 0.0;
+              for (int j = 0; j < pp; j++)
+                res += v[j] * iF[j * pp + i];
+              v_pp[i] = res;
+            }
+          double res = 0.0;
+          for (int i = 0; i < pp; i++)
+            res += v_pp[i] * v[i];
+
+          lik[t] = (log(dF) + res + pp * log(2.0*pi))/2;
+          if (t + 1 > start)
+            LIK += lik[t];
+
+          t++;
+        }
+    }
+}
+
+bool
+BlockKalmanFilter::block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, double *v_pp, double *K, double *v_n, double *a, double *K_P, double *P_t_t1, double *tmp, double *P)
+{
   while (notsteady && t < smpl)
     {
-      //v = Y(:,t) - a(mf)
-      for (int i = 0; i < pp; i++)
-        v[i]  = Y[i + t * pp] - a[mf[i]];
-      
-      //F  = P(mf,mf) + H;
-      for (int i = 0; i < pp; i++)
-        for (int j = 0; j < pp; j++)
-          iF[i + j * pp] = F[i + j * pp] = P[mf[i] + mf[j] * n] + H[i + j * pp];
+      if(missing_observations)
+        {
+
+          // retrieve the d_index
+          pd_index = mxGetCell( pdata_index, t);
+          dd_index = (double*)mxGetData(pd_index);
+          size_d_index = mxGetM(pd_index);
+          d_index.resize(size_d_index);
+          for (int i = 0; i < size_d_index; i++)
+            {
+              d_index[i] = ceil(dd_index[i]) - 1;
+            }
+          
+          //v = Y(:,t) - a(mf)
+          int i_i = 0;
+          //#pragma omp parallel for shared(v, i_i, d_index) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+          for (vector<int>::const_iterator i = d_index.begin(); i != d_index.end(); i++)
+            {
+              //mexPrintf("i_i=%d, omp_get_max_threads()=%d\n",i_i,omp_get_max_threads());
+              v[i_i]  = Y[*i + t * pp] - a[mf[*i]];
+              i_i++;
+            }
+            
+          
+          //F  = P(mf,mf) + H;
+          i_i = 0;
+          if (H_size == 1)
+            {
+              //#pragma omp parallel for shared(iF, F, i_i) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+              for (vector<int>::const_iterator i = d_index.begin(); i != d_index.end(); i++, i_i++)
+                {
+                  int j_j = 0;
+                  for (vector<int>::const_iterator j = d_index.begin(); j != d_index.end(); j++, j_j++)
+                    iF[i_i + j_j * size_d_index] = F[i_i + j_j * size_d_index] = P[mf[*i] + mf[*j] * n] + H[0];
+                }
+            }
+          else
+            {
+              //#pragma omp parallel for shared(iF, F, P, H, mf, i_i) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+              for (vector<int>::const_iterator i = d_index.begin(); i != d_index.end(); i++, i_i++)
+                {
+                  int j_j = 0;
+                  for (vector<int>::const_iterator j = d_index.begin(); j != d_index.end(); j++, j_j++)
+                    iF[i_i + j_j * size_d_index] = F[i_i + j_j * size_d_index] = P[mf[*i] + mf[*j] * n] + H[*i + *j * pp];
+                }
+            }
+            
+        }
+      else
+        {
+          size_d_index = pp;
+          
+          //v = Y(:,t) - a(mf)
+          for (int i = 0; i < pp; i++)
+            v[i]  = Y[i + t * pp] - a[mf[i]];
+          
+          //F  = P(mf,mf) + H;
+          if (H_size == 1)
+            {
+              for (int i = 0; i < pp; i++)
+                for (int j = 0; j < pp; j++)
+                  iF[i + j * pp] = F[i + j * pp] = P[mf[i] + mf[j] * n] + H[0];
+            }
+          else
+            {
+              for (int i = 0; i < pp; i++)
+                for (int j = 0; j < pp; j++)
+                  iF[i + j * pp] = F[i + j * pp] = P[mf[i] + mf[j] * n] + H[i + j * pp];
+            }
+        }
       
-      /* Computes the norm of x */ 
-      double anorm = dlange("1", &pp, &pp, iF, &pp, w); 
+     
+      /* Computes the norm of iF */ 
+      double anorm = dlange("1", &size_d_index, &size_d_index, iF, &size_d_index, w); 
+      //mexPrintf("anorm = %f\n",anorm);
 
       /* Modifies F in place with a LU decomposition */ 
-      dgetrf(&pp, &pp, iF, &pp, ipiv, &info); 
+      dgetrf(&size_d_index, &size_d_index, iF, &size_d_index, ipiv, &info); 
       if (info != 0) fprintf(stderr, "dgetrf failure with error %d\n", (int) info); 
  
       /* Computes the reciprocal norm */ 
-      dgecon("1", &pp, iF, &pp, &anorm, &rcond, w, iw, &info); 
+      dgecon("1", &size_d_index, iF, &size_d_index, &anorm, &rcond, w, iw, &info); 
       if (info != 0) fprintf(stderr, "dgecon failure with error %d\n", (int) info); 
       
       if (rcond < kalman_tol)
-        if (not_all_abs_F_bellow_crit(F, pp * pp, kalman_tol))   //~all(abs(F(:))<kalman_tol)
+        if (not_all_abs_F_bellow_crit(F, size_d_index * size_d_index, kalman_tol))   //~all(abs(F(:))<kalman_tol)
           {
             mexPrintf("error: F singular\n");
-            double LIK  = Inf;
-            // info = 0
-            plhs[0] = mxCreateDoubleScalar(0);
-            if (nlhs >= 2)
-              {
-                plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL);
-                double* pind = mxGetPr(plhs[1]);
-                pind[0] = LIK;
-              }
-
+            LIK  = Inf;
             if (nlhs == 3)
               {
                 for (int i = t; i < smpl; i++)
                   lik[i] = Inf;
-                plhs[2] = plik;
               }
-            else
-              mxDestroyArray(plik);
-            mxFree(w);
-#ifdef DIRECT
-            mxFree(i_nz_state_var);
-#else
-            mxFree(Var);
-            mxFree(Var_2);
-#endif
-            mxFree(tmp_a);
-            mxFree(v_pp);
-            mxFree(v_n);
-            mxFree(mf);
-            mxFree(w);
-            mxFree(iw);
-            mxFree(ipiv);
-            mxFree(oldK);
-            mxFree(P_mf);
-            mxDestroyArray(pa);
-            mxDestroyArray(p_tmp);
-            mxDestroyArray(pQQ);
-            mxDestroyArray(pv);
-            mxDestroyArray(pF);
-            mxDestroyArray(piF);
-            mxDestroyArray(p_P_t_t1);
-            mxDestroyArray(pK);
-            mxDestroyArray(p_K_P);
-            return;
+            // info = 0
+            return_results_and_clean(nlhs, plhs, &P_mf, &v_pp, &K, &K_P, &a, &K_P, &P_t_t1, &tmp, &P);
+            return false;
           }
         else
           {
             mexPrintf("F singular\n");
+
             //a = T*a;
             for (int i = 0; i < n; i++)
               {
@@ -464,57 +466,27 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
 
            //P = T*P*transpose(T)+QQ;
            memset(tmp, 0, n * n_state * sizeof(double));
-#ifdef DIRECT
+
            for (int i = 0; i < n; i++)
             for (int j = pure_obs; j < n; j++)
               {
                 int j1 = j - pure_obs;
                 int j1_n_state = j1 * n_state - pure_obs;
-                //if ((i < pp) || (i >= n_diag + pp) || (j1 >= n_diag))
-                  for (int k = pure_obs; k < i_nz_state_var[i]; k++)
-                    {
-                      tmp[i + j1 * n ] += T[i + k * n] * P[k + j1_n_state];
-                    }
+                for (int k = pure_obs; k < i_nz_state_var[i]; k++)
+                  tmp[i + j1 * n ] += T[i + k * n] * P[k + j1_n_state];
               }
-          /*for (int i = pp; i < pp + n_diag; i++)
-             for (int j = pp; j < pp + n_diag; j++)
-               tmp[i + (j - pp) * n] = T[i + i * n] * P_t_t1[j - pp + (i - pp) * n_state];*/
+
           memset(P, 0, n * n * sizeof(double));
           int n_n_obs = n * pure_obs;
           for (int i = 0; i < n; i++)
             for (int j = i; j < n; j++)
               {
-                //if ((i < pp) || (i >= n_diag + pp) || (j < pp) || (j >= n_diag + pp))
-                  for (int k = pure_obs; k < i_nz_state_var[j]; k++)
-                    {
-                      int k_n = k * n;
-                      P[i * n + j] += tmp[i + k_n - n_n_obs] * T[j + k_n];
-                    }
+                for (int k = pure_obs; k < i_nz_state_var[j]; k++)
+                  {
+                    int k_n = k * n;
+                    P[i * n + j] += tmp[i + k_n - n_n_obs] * T[j + k_n];
+                  }
               }
-#else
-           #pragma omp parallel for shared(T, P_t_t1, tmp, Var) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
-           //for (int i = 0; i < n; i++)
-             for (int j = 0; j < size_index_KF; j++)
-               {
-                 t_Var *s_Var = &Var[j];
-                 tmp[s_Var->indx_1 ] += T[s_Var->indx_2] * P[s_Var->indx_3];
-               }
-           for (int i = pp; i < pp + n_diag; i++)
-             for (int j = pp; j < pp + n_diag; j++)
-               tmp[i + (j - pp) * n] = T[i + i * n] * P[j + i * n];
-           memset(P, 0, n * n * sizeof(double));
-           #pragma omp parallel for shared(T, tmp, P, Var_2) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
-           //for (int i = 0; i < n; i++)
-             for (int j = 0; j < size_index_KF_2; j++)
-               {
-                 t_Var *s_Var = &Var_2[j];
-                 P[s_Var->indx_1 /*+ i*/] += tmp[s_Var->indx_2 /*+ i*/] * T[s_Var->indx_3];
-               }
-#endif
-          /*for (int i = pp; i < pp + n_diag; i++)
-            for (int j = i; j < pp + n_diag; j++)
-              P[j + i * n] = T[i + i * n] * T[j + j * n] * P[j + i * n];*/
-              //P[j + i * n] = tmp[i +]
           
           for ( int i = 0; i < n; i++)
             {
@@ -529,52 +501,82 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
           F_singular = false;
           
           //dF     = det(F);
-          dF     = det(iF, pp, ipiv);
+          dF     = det(iF, size_d_index, ipiv);
 
           //iF     = inv(F);
           //int lwork = 4/*2*/* pp;
-          dgetri(&pp, iF, &pp, ipiv, w, &lw, &info);
+          dgetri(&size_d_index, iF, &size_d_index, ipiv, w, &lw, &info);
           if (info != 0) fprintf(stderr, "dgetri failure with error %d\n", (int) info); 
 
           //lik(t) = log(dF)+transpose(v)*iF*v;
-          for (int i = 0; i < pp; i++)
+#ifdef USE_OMP
+#pragma omp parallel for shared(v_pp) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+#endif
+          for (int i = 0; i < size_d_index; i++)
             {
               double res = 0.0;
-              for (int j = 0; j < pp; j++)
-                res += v[j] * iF[j  * pp + i];
+              for (int j = 0; j < size_d_index; j++)
+                res += v[j] * iF[j  * size_d_index + i];
               v_pp[i] = res;
             }
           double res = 0.0;
-          for (int i = 0; i < pp; i++)
+          for (int i = 0; i < size_d_index; i++)
             res += v_pp[i] * v[i];
 
-          lik[t] = (log(dF) + res + pp * log(2.0*pi))/2;
+          lik[t] = (log(dF) + res + size_d_index * log(2.0*pi))/2;
           if (t + 1 >= start)
             LIK += lik[t];
 
-          //K      = P(:,mf)*iF;
-          for (int i = 0; i < n; i++)
-            for (int j = 0; j < pp; j++)
-              P_mf[i + j * n] = P[i + mf[j] * n];
+          if (missing_observations)
+            {
+              //K      = P(:,mf)*iF;
+#ifdef USE_OMP
+#pragma omp parallel for shared(P_mf) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+#endif
+              for (int i = 0; i < n; i++)
+                {
+                  int j_j = 0;
+                  //for (int j = 0; j < pp; j++)
+                  for (vector<int>::const_iterator j = d_index.begin(); j != d_index.end(); j++, j_j++)
+                    P_mf[i + j_j * n] = P[i + mf[*j] * n];
+                }
+            }
+          else
+            {
+              //K      = P(:,mf)*iF;
+              for (int i = 0; i < n; i++)
+                for (int j = 0; j < pp; j++)
+                  P_mf[i + j * n] = P[i + mf[j] * n];
+            }
+          
+#ifdef USE_OMP
+#pragma omp parallel for shared(K) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+#endif
           for (int i = 0; i < n; i++)
-            for (int j = 0; j < pp; j++)
+            for (int j = 0; j < size_d_index; j++)
               {
                 double res = 0.0;
-                int j_pp = j * pp;
-                for (int k = 0; k < pp; k++)
+                int j_pp = j * size_d_index;
+                for (int k = 0; k < size_d_index; k++)
                   res += P_mf[i + k * n] * iF[j_pp + k];
                 K[i + j * n] = res;
               }
-
+          
           //a      = T*(a+K*v);
+#ifdef USE_OMP
+#pragma omp parallel for shared(v_n) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+#endif
           for (int i = pure_obs; i < n; i++)
             {
               double res = 0.0;
-              for (int j = 0; j < pp; j++)
+              for (int j = 0; j < size_d_index; j++)
                 res += K[j  * n + i] * v[j];
               v_n[i] = res + a[i];
             }
           
+#ifdef USE_OMP
+#pragma omp parallel for shared(a) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+#endif
           for (int i = 0; i < n; i++)
             {
               double res = 0.0;
@@ -582,24 +584,42 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
                 res += T[j  * n + i] * v_n[j];
               a[i] = res;
             }
-
-          //P      = T*(P-K*P(mf,:))*transpose(T)+QQ;
-          for (int i = 0; i < pp; i++)
-            for (int j = pure_obs; j < n; j++)
-              P_mf[i + j * pp] = P[mf[i] + j * n];
+          
+          if (missing_observations)
+            {
+              //P      = T*(P-K*P(mf,:))*transpose(T)+QQ;
+              int i_i = 0;
+              //#pragma omp parallel for shared(P_mf) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+              for (vector<int>::const_iterator i = d_index.begin(); i != d_index.end(); i++, i_i++)
+                for (int j = pure_obs; j < n; j++)
+                  P_mf[i_i + j * size_d_index] = P[mf[*i] + j * n];
+            }
+          else
+            {
+              //P      = T*(P-K*P(mf,:))*transpose(T)+QQ;
+#ifdef USE_OMP
+#pragma omp parallel for shared(P_mf) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+#endif
+              for (int i = 0; i < pp; i++)
+                for (int j = pure_obs; j < n; j++)
+                  P_mf[i + j * pp] = P[mf[i] + j * n];
+            }
+          
 #ifdef BLAS
-          #pragma omp parallel for shared(K, P, K_P) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+#ifdef USE_OMP
+#pragma omp parallel for shared(K_P) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+#endif
           for (int i = 0; i < n; i++)
             for (int j = i; j < n; j++)
               {
                 double res = 0.0;
                 //int j_pp = j * pp;
-                for (int k = 0; k < pp; k++)
-                  res += K[i + k * n] * P_mf[k + j * pp];
+                for (int k = 0; k < size_d_index; k++)
+                  res += K[i + k * n] * P_mf[k + j * size_d_index];
                 K_P[i * n + j] = K_P[j * n + i] = res;
               }
           //#pragma omp parallel for shared(P, K_P, P_t_t1)
-          for (int i = pp; i < n; i++)
+          for (int i = size_d_index; i < n; i++)
             for (int j = i; j < n; j++)
               {
                 unsigned int k = i * n + j;
@@ -616,11 +636,10 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
                 &n, &one, tmp, &n,
                 T, &n, &one,
                 P, &n);
-          mexPrintf("P\n");
-          mexDisp(pP);
 #else
-          //#pragma omp parallel for shared(K, P, K_P) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
-          
+#ifdef USE_OMP
+#pragma omp parallel for shared(K_P) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+#endif
           for (int i = pure_obs; i < n; i++)
             {
               unsigned int i1 = i - pure_obs;
@@ -628,32 +647,16 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
                 {
                   unsigned int j1 = j - pure_obs;
                   double res = 0.0;
-                  int j_pp = j * pp;
-                  for (int k = 0; k < pp; k++)
+                  int j_pp = j * size_d_index;
+                  for (int k = 0; k < size_d_index; k++)
                     res += K[i + k * n] * P_mf[k + j_pp];
                   K_P[i1 * n_state + j1] = K_P[j1 * n_state + i1] = res;
                 }
             }
-          /*for (int j = pp; j < n; j++)
-            {
-              unsigned int j1 = j - pp;
-              double res = P[mf[j] + j * n]
-              for (int i = 0; i < n; i++)
-                {
-                  unsigned int i1 = i - pp;
-                  K_P[i1 * n_state + j1] = res * K[i + j * n];
-                }
-              for (int i = pp; i < n; i++)
-                {
-                  unsigned int i1 = i - pp;
-                  double res = 0.0;
-                  for (int k = 0; k < pp; k++)
-                    res += K[i + k * n] * P[mf[k] + j * n];
-                  K_P[i1 * n_state + j1] = K_P[j1 * n_state + i1] = res;
-                }
-            }*/
-            
-          //#pragma omp parallel for shared(P, K_P, P_t_t1)
+
+#ifdef USE_OMP
+#pragma omp parallel for shared(P_t_t1) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+#endif
           for (int i = pure_obs; i < n; i++)
             {
               unsigned int i1 = i - pure_obs;
@@ -664,9 +667,12 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
                   P_t_t1[j1 * n_state + i1] = P_t_t1[k1] = P[i * n + j] - K_P[k1];
                 }
             }
-          
+
           memset(tmp, 0, n * n_state * sizeof(double));
-#ifdef DIRECT
+
+#ifdef USE_OMP
+#pragma omp parallel for shared(tmp) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+#endif
           for (int i = 0; i < n; i++)
             {
               int max_k = i_nz_state_var[i];
@@ -675,21 +681,23 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
                   int j1 = j - pure_obs;
                   int j1_n_state = j1 * n_state - pure_obs;
                   int indx_tmp = i + j1 * n ;
-                  //if ((i < pp) || (i >= n_diag + pp) || (j1 >= n_diag))
-                  for (int k = pp; k < max_k; k++)
+                  for (int k = pure_obs; k < max_k; k++)
                     tmp[indx_tmp] += T[i + k * n] * P_t_t1[k + j1_n_state];
                 }
             }
+
           memset(P, 0, n * n * sizeof(double));
-          
+
+          int n_n_obs = - n * pure_obs;
+#ifdef USE_OMP
+#pragma omp parallel for shared(P) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
+#endif
           for (int i = 0; i < n; i++)
             {
-              int n_n_obs = - n * pure_obs;
               for (int j = i; j < n; j++)
                 {
                   int max_k = i_nz_state_var[j];
                   int P_indx = i * n + j;
-                  //if ((i < pp) || (i >= n_diag + pp) || (j < pp) || (j >= n_diag + pp))
                   for (int k = pure_obs; k < max_k; k++)
                     {
                       int k_n = k * n;
@@ -697,23 +705,9 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
                     }
                 }
             }
-#else
-          //#pragma omp parallel for shared(T, P_t_t1, tmp, Var) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
-          for (int j = 0; j < size_index_KF; j++)
-            {
-              t_Var *s_Var = &Var[j];
-              tmp[s_Var->indx_1 ] += T[s_Var->indx_2 ] * P_t_t1[s_Var->indx_3];
-            }
-         for (int i = pp; i < pp + n_diag; i++)
-           for (int j = pp; j < pp + n_diag; j++)
-             tmp[i + (j - pp) * n] = T[i + i * n] * P_t_t1[j - pp + (i - pp) * n_state];
-         memset(P, 0, n * n * sizeof(double));
-         //#pragma omp parallel for shared(T, tmp, P, Var_2) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
-         for (int j = 0; j < size_index_KF_2; j++)
-           {
-             t_Var *s_Var = &Var_2[j];
-             P[s_Var->indx_1 /*+ i*/] += tmp[s_Var->indx_2 /*+ i*/] * T[s_Var->indx_3];
-           }
+
+#ifdef USE_OMP
+#pragma omp parallel for shared(P) num_threads(atoi(getenv("DYNARE_NUM_THREADS")))
 #endif
           for ( int i = 0; i < n; i++)
             {
@@ -723,72 +717,39 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
                 P[i + j * n] = P[j + i * n];
             }
 #endif
-          //notsteady = max(abs(K(:)-oldK)) > riccati_tol;
-          double max_abs = 0.0;
-          for (int i = 0; i < n * pp; i++)
+          
+          if (t >= no_more_missing_observations)
             {
-              double res = abs(K[i] - oldK[i]);
-              if (res > max_abs)
-                max_abs = res;
-            }
-          notsteady = max_abs > riccati_tol;
+              double max_abs = 0.0;
+              for (int i = 0; i < n * size_d_index; i++)
+                {
+                  double res = abs(K[i] - oldK[i]);
+                  if (res > max_abs)
+                    max_abs = res;
+                }
+              notsteady = max_abs > riccati_tol;
 
-          //oldK = K(:);
-          memcpy(oldK, K, n * pp * sizeof(double));
+              //oldK = K(:);
+             
+              memcpy(oldK, K, n * pp * sizeof(double));
+            }
         }
       t++;
     }
 
   if (F_singular)
     mexErrMsgTxt("The variance of the forecast error remains singular until the end of the sample\n");
+  if (t < smpl)
+    block_kalman_filter_ss(P_mf, v_pp, K, K_P, a, K_P, P_t_t1, tmp, P);
+  return true;
+}
 
-  if (t+1 < smpl)
-    {
-      while (t < smpl)
-        {
-          //v = Y(:,t)-a(mf);
-          for (int i = 0; i < pp; i++)
-            v[i]  = Y[i + t * pp] - a[mf[i]];
-          
-          //a = T*(a+K*v);
-          for (int i = pure_obs; i < n; i++)
-            {
-              double res = 0.0;
-              for (int j = 0; j < pp; j++)
-                res += K[j  * n + i] * v[j];
-              v_n[i] = res + a[i];
-            }
-          for (int i = 0; i < n; i++)
-            {
-              double res = 0.0;
-              for (int j = pure_obs; j < n; j++)
-                res += T[j  * n + i] * v_n[j];
-              a[i] = res;
-            }
-        
-          //lik(t) = transpose(v)*iF*v;
-          for (int i = 0; i < pp; i++)
-            {
-              double res = 0.0;
-              for (int j = 0; j < pp; j++)
-                res += v[j] * iF[j * pp + i];
-              v_pp[i] = res;
-            }
-          double res = 0.0;
-          for (int i = 0; i < pp; i++)
-            res += v_pp[i] * v[i];
-
-          lik[t] = (log(dF) + res + pp * log(2.0*pi))/2;
-          if (t + 1 > start)
-            LIK += lik[t];
-
-          t++;
-        }
-    }
 
-  // info = 0
+void 
+BlockKalmanFilter::return_results_and_clean(int nlhs, mxArray *plhs[], double *P_mf[], double *v_pp[], double *K[], double *v_n[], double *a[], double *K_P[], double *P_t_t1[], double *tmp[], double *P[])
+{
   plhs[0] = mxCreateDoubleScalar(0);
-  
+
   if (nlhs >= 2)
     {
       plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL);
@@ -800,23 +761,18 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
     plhs[2] = plik;
   else
     mxDestroyArray(plik);
-  
+
   mxFree(w);
-#ifdef DIRECT
   mxFree(i_nz_state_var);
-#else
-  mxFree(Var);
-  mxFree(Var_2);
-#endif
   mxFree(tmp_a);
-  mxFree(v_pp);
-  mxFree(v_n);
+  //mxFree(v_pp);
+  //mxFree(v_n);
   mxFree(mf);
-  mxFree(w);
   mxFree(iw);
   mxFree(ipiv);
   mxFree(oldK);
-  mxFree(P_mf);
+  //mxFree(P_mf);
+  
   mxDestroyArray(pa);
   mxDestroyArray(p_tmp);
   mxDestroyArray(pQQ);
@@ -828,3 +784,12 @@ mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
   mxDestroyArray(p_K_P);
 }
 
+void
+mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
+{
+  double *P_mf, * v_pp, *v_n, *a, *K, *K_P, *P_t_t1, *tmp, *P;
+  BlockKalmanFilter block_kalman_filter(nlhs, plhs, nrhs, prhs, &P_mf, &v_pp, &K, &v_n, &a, &K_P, &P_t_t1, &tmp, &P);
+  if (block_kalman_filter.block_kalman_filter(nlhs, plhs, P_mf, v_pp, K, K_P, a, K_P, P_t_t1, tmp, P))
+    block_kalman_filter.return_results_and_clean(nlhs, plhs, &P_mf, &v_pp, &K, &K_P, &a, &K_P, &P_t_t1, &tmp, &P);
+}
+
diff --git a/mex/sources/block_kalman_filter/block_kalman_filter.h b/mex/sources/block_kalman_filter/block_kalman_filter.h
new file mode 100644
index 0000000000000000000000000000000000000000..501e3820bdaff5be9505dbf4e50b1756e6b56649
--- /dev/null
+++ b/mex/sources/block_kalman_filter/block_kalman_filter.h
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2007-2011 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/>.
+ */
+
+#ifndef BLOCK_KALMAN_FILTER
+#define BLOCK_KALMAN_FILTER
+
+#ifndef DEBUG_EX
+# include <dynmex.h>
+#else
+# include "mex_interface.hh"
+#endif
+
+#include <dynblas.h>
+#include <dynlapack.h>
+using namespace std;
+
+class BlockKalmanFilter
+{
+  public:
+  mxArray *pT , *pR, *pQ, *pH, *pP, *pY, *pQQ, *pv, *pF, *piF, *p_P_t_t1, *pK, *p_K_P;
+  double *T , *R, *Q , *H, *Y, *mfd, *QQ, *v, *F, *iF;
+  int start, pure_obs, smpl, n, n_state, n_shocks, H_size;
+  double kalman_tol, riccati_tol, dF, LIK, Inf, pi;
+  lapack_int pp, lw, info;
+
+  double* nz_state_var;
+  int *i_nz_state_var, *mf;
+  int n_diag, t;
+  mxArray *M_;
+  mxArray* pa, *p_tmp, *p_tmp1, *plik;
+  double *tmp_a, *tmp1, *lik, *v_n, *w, *oldK;
+  bool notsteady, F_singular, missing_observations;
+  lapack_int *iw, *ipiv;
+  double anorm, rcond;
+  lapack_int size_d_index;
+  int no_more_missing_observations, number_of_observations;
+  const mxArray* pdata_index;
+  vector<int> d_index;
+  const mxArray* pd_index;
+  double* dd_index;
+
+  public:
+  BlockKalmanFilter(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[], double *P_mf[], double *v_pp[], double *K[], double *v_n[], double *a[], double *K_P[], double *P_t_t1[], double *tmp[], double *P[]);
+  bool block_kalman_filter(int nlhs, mxArray *plhs[], double *P_mf, double *v_pp, double *K, double *v_n, double *a, double *K_P, double *P_t_t1, double *tmp, double *P);
+  void block_kalman_filter_ss(double *P_mf, double *v_pp, double *K, double *v_n, double *a, double *K_P, double *P_t_t1, double *tmp, double *P);
+  void return_results_and_clean(int nlhs, mxArray *plhs[], double *P_mf[], double *v_pp[], double *K[], double *v_n[], double *a[], double *K_P[], double *P_t_t1[], double *tmp[], double *P[]);
+};
+#endif
diff --git a/mex/sources/bytecode/ErrorHandling.hh b/mex/sources/bytecode/ErrorHandling.hh
index a6bc1acaec1e1356620509fa762bcc98ae5fdd28..9c6717d0e9095c1ace960999b7e99ca57c3a8ce5 100644
--- a/mex/sources/bytecode/ErrorHandling.hh
+++ b/mex/sources/bytecode/ErrorHandling.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2011 Dynare Team
+ * Copyright (C) 2007-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/bytecode/Interpreter.cc b/mex/sources/bytecode/Interpreter.cc
index 8adf84491ebd1b3bb4fa5a695789bc7a9f84b8c2..a50a0eff9f75d0bac8610775a44bb9f576461d3d 100644
--- a/mex/sources/bytecode/Interpreter.cc
+++ b/mex/sources/bytecode/Interpreter.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2011 Dynare Team
+ * Copyright (C) 2007-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/bytecode/Interpreter.hh b/mex/sources/bytecode/Interpreter.hh
index 22778b14dbaf97193635c1db1e513e20e1111353..18fefd89cc6d8e34661a692d52314278d7c9b7a0 100644
--- a/mex/sources/bytecode/Interpreter.hh
+++ b/mex/sources/bytecode/Interpreter.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2011 Dynare Team
+ * Copyright (C) 2007-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/bytecode/SparseMatrix.cc b/mex/sources/bytecode/SparseMatrix.cc
index 10840d15a5c1c4597e3a18781b68e9685429807a..d7c4ab466c6453f6aaeb60cfead514ac5a2e332f 100644
--- a/mex/sources/bytecode/SparseMatrix.cc
+++ b/mex/sources/bytecode/SparseMatrix.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2011 Dynare Team
+ * Copyright (C) 2007-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -2179,7 +2179,7 @@ SparseMatrix::Singular_display(int block, int Size, bool steady_state, it_code_t
   mexCallMATLAB(3, lhs, 1, rhs, "svd");
   mxArray* SVD_u = lhs[0];
   mxArray* SVD_s = lhs[1];
-  mxArray* SVD_v = lhs[2];
+  //mxArray* SVD_v = lhs[2];
   double *SVD_ps = mxGetPr(SVD_s);
   double *SVD_pu = mxGetPr(SVD_u);
   for (int i = 0; i < Size; i++)
@@ -3001,11 +3001,15 @@ SparseMatrix::Simulate_Newton_One_Boundary(int blck, int y_size, int it_, int y_
         {
           for (j = 0; j < y_size; j++)
             {
+#ifdef DEBUG
               bool select = false;
+#endif
               for (int i = 0; i < Size; i++)
                 if (j == index_vara[i])
                   {
+#ifdef DEBUG
                     select = true;
+#endif
                     break;
                   }
 #ifdef DEBUG
diff --git a/mex/sources/bytecode/SparseMatrix.hh b/mex/sources/bytecode/SparseMatrix.hh
index e6df80e9492ae7c159b6b6f81009ba104d648d88..5303b186f896291774d75ff4756d7eb454371120 100644
--- a/mex/sources/bytecode/SparseMatrix.hh
+++ b/mex/sources/bytecode/SparseMatrix.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2011 Dynare Team
+ * Copyright (C) 2007-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/bytecode/bytecode.cc b/mex/sources/bytecode/bytecode.cc
index b3ff8c1bba45d60359830e194290f23515168dd5..9d3e9321e5860b72fd2cb259fa0951a1cb4134e4 100644
--- a/mex/sources/bytecode/bytecode.cc
+++ b/mex/sources/bytecode/bytecode.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2011 Dynare Team
+ * Copyright (C) 2007-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -439,9 +439,12 @@ main(int nrhs, const char *prhs[])
                       for (int i = 0; i < nb_blocks; i++)
                         {
                           mxSetFieldByNumber(plhs[2], i, jacob_field_number, interprete.get_jacob(i));
-                          mxSetFieldByNumber(plhs[2], i, jacob_exo_field_number, interprete.get_jacob_exo(i));
-                          mxSetFieldByNumber(plhs[2], i, jacob_exo_det_field_number, interprete.get_jacob_exo_det(i));
-                          mxSetFieldByNumber(plhs[2], i, jacob_other_endo_field_number, interprete.get_jacob_other_endo(i));
+                          if (!steady_state)
+                            {
+                              mxSetFieldByNumber(plhs[2], i, jacob_exo_field_number, interprete.get_jacob_exo(i));
+                              mxSetFieldByNumber(plhs[2], i, jacob_exo_det_field_number, interprete.get_jacob_exo_det(i));
+                              mxSetFieldByNumber(plhs[2], i, jacob_other_endo_field_number, interprete.get_jacob_other_endo(i));
+                            }
                         }
                     }
                 }
diff --git a/mex/sources/estimation/InitializeKalmanFilter.cc b/mex/sources/estimation/InitializeKalmanFilter.cc
index 182b6c24b4c3b2ed81c3729829414f88bff2eaad..57373820a034f351ed2b39f315696bef70213615 100644
--- a/mex/sources/estimation/InitializeKalmanFilter.cc
+++ b/mex/sources/estimation/InitializeKalmanFilter.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/estimation/InitializeKalmanFilter.hh b/mex/sources/estimation/InitializeKalmanFilter.hh
index 39993425512c65c42fdde90e35c262f00913034a..25c6f6eb2b7b206d4180a7821aaf74c089a5091f 100644
--- a/mex/sources/estimation/InitializeKalmanFilter.hh
+++ b/mex/sources/estimation/InitializeKalmanFilter.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/estimation/KalmanFilter.cc b/mex/sources/estimation/KalmanFilter.cc
index 77e8d0804c2d07abcfdf0e3246bdc7bf58a7ae49..5b416e1e921273ceb484f581e3da09b79649d815 100644
--- a/mex/sources/estimation/KalmanFilter.cc
+++ b/mex/sources/estimation/KalmanFilter.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2011 Dynare Team
+ * Copyright (C) 2009-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/estimation/KalmanFilter.hh b/mex/sources/estimation/KalmanFilter.hh
index 64fb03a863db805bc8b0335df251c1d70be4c18f..6a688e2f1ff95a198a443832ffce54ef713f3337 100644
--- a/mex/sources/estimation/KalmanFilter.hh
+++ b/mex/sources/estimation/KalmanFilter.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2011 Dynare Team
+ * Copyright (C) 2009-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/estimation/LogLikelihoodMain.cc b/mex/sources/estimation/LogLikelihoodMain.cc
index 5371acd040ce8f642b0aacdc394f9a024f756611..47318726d961b82b3d5e249269ee22aa3b214ec0 100644
--- a/mex/sources/estimation/LogLikelihoodMain.cc
+++ b/mex/sources/estimation/LogLikelihoodMain.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2011 Dynare Team
+ * Copyright (C) 2009-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/estimation/LogLikelihoodMain.hh b/mex/sources/estimation/LogLikelihoodMain.hh
index 546e122df80de8f00f17fc70506317a85d611f0a..88a2b5bfa3cfa64874008a7b1dcb0beb38ef4cf7 100644
--- a/mex/sources/estimation/LogLikelihoodMain.hh
+++ b/mex/sources/estimation/LogLikelihoodMain.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2011 Dynare Team
+ * Copyright (C) 2009-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/estimation/LogLikelihoodSubSample.cc b/mex/sources/estimation/LogLikelihoodSubSample.cc
index 4c5063db20bdf16e0772519ae5ca91a57781953b..77ad440a40188058a92828d1cb5bb62257ff9b2a 100644
--- a/mex/sources/estimation/LogLikelihoodSubSample.cc
+++ b/mex/sources/estimation/LogLikelihoodSubSample.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2011 Dynare Team
+ * Copyright (C) 2009-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/estimation/LogLikelihoodSubSample.hh b/mex/sources/estimation/LogLikelihoodSubSample.hh
index 9df4f5fd6b1c30338999ed427d99a784cf62d980..ca388c2748c4a7109381c68c6042c40ddfb89f0b 100644
--- a/mex/sources/estimation/LogLikelihoodSubSample.hh
+++ b/mex/sources/estimation/LogLikelihoodSubSample.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2011 Dynare Team
+ * Copyright (C) 2009-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/estimation/LogPosteriorDensity.cc b/mex/sources/estimation/LogPosteriorDensity.cc
index b99e0b8ee841a6c1cbb1754c04c15fa98cc93660..d938b956580eea8df000ee7323c2175c12ad1ca9 100644
--- a/mex/sources/estimation/LogPosteriorDensity.cc
+++ b/mex/sources/estimation/LogPosteriorDensity.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2011 Dynare Team
+ * Copyright (C) 2009-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/estimation/LogPosteriorDensity.hh b/mex/sources/estimation/LogPosteriorDensity.hh
index 5c378c8225f779f63dc8c20504241a6e1f9b57a0..4ff4a0d59e372b30f8576230c882d32dc9eff546 100644
--- a/mex/sources/estimation/LogPosteriorDensity.hh
+++ b/mex/sources/estimation/LogPosteriorDensity.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2011 Dynare Team
+ * Copyright (C) 2009-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/estimation/LogPriorDensity.cc b/mex/sources/estimation/LogPriorDensity.cc
index 55364d5c71bcaba5df8cbc9ba3d445c66ea1b54e..fbdcdc5ac771231b00084fe17bd3db41c0210a2f 100644
--- a/mex/sources/estimation/LogPriorDensity.cc
+++ b/mex/sources/estimation/LogPriorDensity.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2011 Dynare Team
+ * Copyright (C) 2009-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/estimation/LogPriorDensity.hh b/mex/sources/estimation/LogPriorDensity.hh
index ef0858e52a8282baa88cec4561d122a330603e70..5a07402be09a93de0b3cbba76da30ddbde03477f 100644
--- a/mex/sources/estimation/LogPriorDensity.hh
+++ b/mex/sources/estimation/LogPriorDensity.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/estimation/ModelSolution.cc b/mex/sources/estimation/ModelSolution.cc
index 4eb8842a4854a4d17c151847d4b56d039cfbabed..73066a795d04588ab026f99e6a750822830af43a 100644
--- a/mex/sources/estimation/ModelSolution.cc
+++ b/mex/sources/estimation/ModelSolution.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/estimation/ModelSolution.hh b/mex/sources/estimation/ModelSolution.hh
index 36be5b43aa2652dd9b5e8736b4ca35694f030bd8..3e690ffa66450a7ca24f8011c7e37f8bd34ab408 100644
--- a/mex/sources/estimation/ModelSolution.hh
+++ b/mex/sources/estimation/ModelSolution.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/estimation/RandomWalkMetropolisHastings.hh b/mex/sources/estimation/RandomWalkMetropolisHastings.hh
index 38866e76cc4e2a74a2b552f65820c4ff208ddd46..5b5c02e9b4a5afe9b72b63903ca254ae7b9a713b 100644
--- a/mex/sources/estimation/RandomWalkMetropolisHastings.hh
+++ b/mex/sources/estimation/RandomWalkMetropolisHastings.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/estimation/tests/DsgeLikelihood.m b/mex/sources/estimation/tests/DsgeLikelihood.m
index a22501b58770feb5b317699d6441ab426931ad8f..6de151c6d82ac409c138fd174e7ccbdb2421cf66 100644
--- a/mex/sources/estimation/tests/DsgeLikelihood.m
+++ b/mex/sources/estimation/tests/DsgeLikelihood.m
@@ -1,345 +1,345 @@
-function [fval,cost_flag,ys,trend_coeff,info] = DsgeLikelihood(xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations)
-% function [fval,cost_flag,ys,trend_coeff,info] = DsgeLikelihood(xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations)
-% Evaluates the posterior kernel of a dsge model. 
-% 
-% INPUTS 
-%   xparam1                        [double]   vector of model parameters.
-%   gend                           [integer]  scalar specifying the number of observations.
-%   data                           [double]   matrix of data
-%   data_index                     [cell]     cell of column vectors
-%   number_of_observations         [integer]
-%   no_more_missing_observations   [integer] 
-% OUTPUTS 
-%   fval        :     value of the posterior kernel at xparam1.
-%   cost_flag   :     zero if the function returns a penalty, one otherwise.
-%   ys          :     steady state of original endogenous variables
-%   trend_coeff :
-%   info        :     vector of informations about the penalty:
-%                     41: one (many) parameter(s) do(es) not satisfied the lower bound
-%                     42: one (many) parameter(s) do(es) not satisfied the upper bound
-%               
-% SPECIAL REQUIREMENTS
-%
-
-% Copyright (C) 2004-2010 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 bayestopt_ estim_params_ options_ trend_coeff_ M_ oo_
-fval            = [];
-ys              = [];
-trend_coeff     = [];
-cost_flag       = 1;
-nobs            = size(options_.varobs,1);
-%------------------------------------------------------------------------------
-% 1. Get the structural parameters & define penalties
-%------------------------------------------------------------------------------
-if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb)
-    k = find(xparam1 < bayestopt_.lb);
-    fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2);
-    cost_flag = 0;
-    info = 41;
-    return;
-end
-if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub)
-    k = find(xparam1 > bayestopt_.ub);
-    fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2);
-    cost_flag = 0;
-    info = 42;
-    return;
-end
-Q = M_.Sigma_e;
-H = M_.H;
-for i=1:estim_params_.nvx
-    k =estim_params_.var_exo(i,1);
-    Q(k,k) = xparam1(i)*xparam1(i);
-end
-offset = estim_params_.nvx;
-if estim_params_.nvn
-    for i=1:estim_params_.nvn
-        k = estim_params_.var_endo(i,1);
-        H(k,k) = xparam1(i+offset)*xparam1(i+offset);
-    end
-    offset = offset+estim_params_.nvn;
-end
-if estim_params_.ncx
-    for i=1:estim_params_.ncx
-        k1 =estim_params_.corrx(i,1);
-        k2 =estim_params_.corrx(i,2);
-        Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2));
-        Q(k2,k1) = Q(k1,k2);
-    end
-    [CholQ,testQ] = chol(Q);
-    if testQ    %% The variance-covariance matrix of the structural innovations is not definite positive.
-        %% We have to compute the eigenvalues of this matrix in order to build the penalty.
-        a = diag(eig(Q));
-        k = find(a < 0);
-        if k > 0
-            fval = bayestopt_.penalty+sum(-a(k));
-            cost_flag = 0;
-            info = 43;
-            return
-        end
-    end
-    offset = offset+estim_params_.ncx;
-end
-if estim_params_.ncn 
-    for i=1:estim_params_.ncn
-        k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1));
-        k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2));
-        H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2));
-        H(k2,k1) = H(k1,k2);
-    end
-    [CholH,testH] = chol(H);
-    if testH
-        a = diag(eig(H));
-        k = find(a < 0);
-        if k > 0
-            fval = bayestopt_.penalty+sum(-a(k));
-            cost_flag = 0;
-            info = 44;
-            return
-        end
-    end
-    offset = offset+estim_params_.ncn;
-end
-if estim_params_.np > 0
-    M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end);
-end
-M_.Sigma_e = Q;
-M_.H = H;
-%------------------------------------------------------------------------------
-% 2. call model setup & reduction program
-%------------------------------------------------------------------------------
-[T,R,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,...
-                                        bayestopt_.restrict_columns,...
-                                        bayestopt_.restrict_aux);
-if info(1) == 1 || info(1) == 2 || info(1) == 5
-    fval = bayestopt_.penalty+1;
-    cost_flag = 0;
-    return
-elseif info(1) == 3 || info(1) == 4 || info(1)==6 ||info(1) == 19 || info(1) == 20 || info(1) == 21
-    fval = bayestopt_.penalty+info(2);
-    cost_flag = 0;
-    return
-end
-bayestopt_.mf = bayestopt_.mf1;
-if options_.noconstant
-    constant = zeros(nobs,1);  
-else    
-    if options_.loglinear
-        constant = log(SteadyState(bayestopt_.mfys));
-    else
-        constant = SteadyState(bayestopt_.mfys);
-    end
-end
-if bayestopt_.with_trend
-    trend_coeff = zeros(nobs,1);
-    t = options_.trend_coeffs;
-    for i=1:length(t)
-        if ~isempty(t{i})
-            trend_coeff(i) = evalin('base',t{i});
-        end
-    end
-    trend = repmat(constant,1,gend)+trend_coeff*[1:gend];
-else
-    trend = repmat(constant,1,gend);
-end
-start = options_.presample+1;
-np    = size(T,1);
-mf    = bayestopt_.mf;
-no_missing_data_flag = (number_of_observations==gend*nobs);
-%------------------------------------------------------------------------------
-% 3. Initial condition of the Kalman filter
-%------------------------------------------------------------------------------
-T
-R
-Q
-R*Q*R'
-pause
-options_.lik_init = 1;
-kalman_algo = options_.kalman_algo;
-if options_.lik_init == 1               % Kalman filter
-    if kalman_algo ~= 2
-        kalman_algo = 1;
-    end
-    Pstar = lyapunov_symm(T,R*Q*R',options_.qz_criterium,options_.lyapunov_complex_threshold);
-    Pinf        = [];
-elseif options_.lik_init == 2   % Old Diffuse Kalman filter
-    if kalman_algo ~= 2
-        kalman_algo = 1;
-    end
-    Pstar = options_.Harvey_scale_factor*eye(np);
-    Pinf = [];
-elseif options_.lik_init == 3   % Diffuse Kalman filter
-    if kalman_algo ~= 4
-        kalman_algo = 3;
-    end
-    [QT,ST] = schur(T);
-    e1 = abs(ordeig(ST)) > 2-options_.qz_criterium;
-    [QT,ST] = ordschur(QT,ST,e1);
-    k = find(abs(ordeig(ST)) > 2-options_.qz_criterium);
-    nk = length(k);
-    nk1 = nk+1;
-    Pinf = zeros(np,np);
-    Pinf(1:nk,1:nk) = eye(nk);
-    Pstar = zeros(np,np);
-    B = QT'*R*Q*R'*QT;
-    for i=np:-1:nk+2
-        if ST(i,i-1) == 0
-            if i == np
-                c = zeros(np-nk,1);
-            else
-                c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+...
-                    ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
-            end
-            q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i);
-            Pstar(nk1:i,i) = q\(B(nk1:i,i)+c);
-            Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
-        else
-            if i == np
-                c = zeros(np-nk,1);
-                c1 = zeros(np-nk,1);
-            else
-                c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+...
-                    ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i)+...
-                    ST(i,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1);
-                c1 = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i-1,i+1:end)')+...
-                     ST(i-1,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1)+...
-                     ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
-            end
-            q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);...
-                 -ST(nk1:i,nk1:i)*ST(i-1,i) eye(i-nk)-ST(nk1:i,nk1:i)*ST(i-1,i-1)];
-            z =  q\[B(nk1:i,i)+c;B(nk1:i,i-1)+c1];
-            Pstar(nk1:i,i) = z(1:(i-nk));
-            Pstar(nk1:i,i-1) = z(i-nk+1:end);
-            Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
-            Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)';
-            i = i - 1;
-        end
-    end
-    if i == nk+2
-        c = ST(nk+1,:)*(Pstar(:,nk+2:end)*ST(nk1,nk+2:end)')+ST(nk1,nk1)*ST(nk1,nk+2:end)*Pstar(nk+2:end,nk1);
-        Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1));
-    end
-    Z = QT(mf,:);
-    R1 = QT'*R;
-    [QQ,RR,EE] = qr(Z*ST(:,1:nk),0);
-    k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8);
-    if length(k) > 0
-        k1 = EE(:,k);
-        dd =ones(nk,1);
-        dd(k1) = zeros(length(k1),1);
-        Pinf(1:nk,1:nk) = diag(dd);
-    end
-end
-if kalman_algo == 2
-end
-kalman_tol = options_.kalman_tol;
-riccati_tol = options_.riccati_tol;
-mf = bayestopt_.mf1;
-Y   = data-trend;
-Pstar
-pause
-%------------------------------------------------------------------------------
-% 4. Likelihood evaluation
-%------------------------------------------------------------------------------
-if (kalman_algo==1)% Multivariate Kalman Filter
-    if no_missing_data_flag
-        LIK = kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol); 
-    else
-        LIK = ...
-            missing_observations_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol, ...
-                                               data_index,number_of_observations,no_more_missing_observations);
-    end
-    if isinf(LIK)
-        kalman_algo = 2;
-    end
-end
-if (kalman_algo==2)% Univariate Kalman Filter
-    no_correlation_flag = 1;
-    if length(H)==1 & H == 0
-        H = zeros(nobs,1);
-    else
-        if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
-            H = diag(H);
-        else
-            no_correlation_flag = 0;
-        end
-    end
-    if no_correlation_flag
-        LIK = univariate_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations);
-    else
-        LIK = univariate_kalman_filter_corr(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations);
-    end
-end
-if (kalman_algo==3)% Multivariate Diffuse Kalman Filter
-    if no_missing_data_flag
-        LIK = diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol, ...
-                                    riccati_tol);
-    else
-        LIK = missing_observations_diffuse_kalman_filter(ST,R1,Q,H,Pinf, ...
-                                                         Pstar,Y,start,Z,kalman_tol,riccati_tol,...
-                                                         data_index,number_of_observations,...
-                                                         no_more_missing_observations);
-    end
-    if isinf(LIK)
-        kalman_algo = 4;
-    end
-end
-if (kalman_algo==4)% Univariate Diffuse Kalman Filter
-    no_correlation_flag = 1;
-    if length(H)==1 & H == 0
-        H = zeros(nobs,1);
-    else
-        if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
-            H = diag(H);
-        else
-            no_correlation_flag = 0;
-        end
-    end
-    if no_correlation_flag
-        LIK = univariate_diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y, ...
-                                               start,Z,kalman_tol,riccati_tol,data_index,...
-                                               number_of_observations,no_more_missing_observations);
-    else
-        LIK = univariate_diffuse_kalman_filter_corr(ST,R1,Q,H,Pinf,Pstar, ...
-                                                    Y,start,Z,kalman_tol,riccati_tol,...
-                                                    data_index,number_of_observations,...
-                                                    no_more_missing_observations);
-    end
-end
-if isnan(LIK)
-    cost_flag = 0;
-    return
-end
-if imag(LIK)~=0
-    likelihood = bayestopt_.penalty;
-else
-    likelihood = LIK;
-end
-% ------------------------------------------------------------------------------
-% Adds prior if necessary
-% ------------------------------------------------------------------------------
-lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4);
-fval    = (likelihood-lnprior);
-likelihood
-lnprior
-fval
-pause
-LIKDLL=logposterior(xparam1,Y,mexext)
-pause
-options_.kalman_algo = kalman_algo;
+function [fval,cost_flag,ys,trend_coeff,info] = DsgeLikelihood(xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations)
+% function [fval,cost_flag,ys,trend_coeff,info] = DsgeLikelihood(xparam1,gend,data,data_index,number_of_observations,no_more_missing_observations)
+% Evaluates the posterior kernel of a dsge model. 
+% 
+% INPUTS 
+%   xparam1                        [double]   vector of model parameters.
+%   gend                           [integer]  scalar specifying the number of observations.
+%   data                           [double]   matrix of data
+%   data_index                     [cell]     cell of column vectors
+%   number_of_observations         [integer]
+%   no_more_missing_observations   [integer] 
+% OUTPUTS 
+%   fval        :     value of the posterior kernel at xparam1.
+%   cost_flag   :     zero if the function returns a penalty, one otherwise.
+%   ys          :     steady state of original endogenous variables
+%   trend_coeff :
+%   info        :     vector of informations about the penalty:
+%                     41: one (many) parameter(s) do(es) not satisfied the lower bound
+%                     42: one (many) parameter(s) do(es) not satisfied the upper bound
+%               
+% SPECIAL REQUIREMENTS
+%
+
+% Copyright (C) 2004-2010 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 bayestopt_ estim_params_ options_ trend_coeff_ M_ oo_
+fval            = [];
+ys              = [];
+trend_coeff     = [];
+cost_flag       = 1;
+nobs            = size(options_.varobs,1);
+%------------------------------------------------------------------------------
+% 1. Get the structural parameters & define penalties
+%------------------------------------------------------------------------------
+if options_.mode_compute ~= 1 & any(xparam1 < bayestopt_.lb)
+    k = find(xparam1 < bayestopt_.lb);
+    fval = bayestopt_.penalty+sum((bayestopt_.lb(k)-xparam1(k)).^2);
+    cost_flag = 0;
+    info = 41;
+    return;
+end
+if options_.mode_compute ~= 1 & any(xparam1 > bayestopt_.ub)
+    k = find(xparam1 > bayestopt_.ub);
+    fval = bayestopt_.penalty+sum((xparam1(k)-bayestopt_.ub(k)).^2);
+    cost_flag = 0;
+    info = 42;
+    return;
+end
+Q = M_.Sigma_e;
+H = M_.H;
+for i=1:estim_params_.nvx
+    k =estim_params_.var_exo(i,1);
+    Q(k,k) = xparam1(i)*xparam1(i);
+end
+offset = estim_params_.nvx;
+if estim_params_.nvn
+    for i=1:estim_params_.nvn
+        k = estim_params_.var_endo(i,1);
+        H(k,k) = xparam1(i+offset)*xparam1(i+offset);
+    end
+    offset = offset+estim_params_.nvn;
+end
+if estim_params_.ncx
+    for i=1:estim_params_.ncx
+        k1 =estim_params_.corrx(i,1);
+        k2 =estim_params_.corrx(i,2);
+        Q(k1,k2) = xparam1(i+offset)*sqrt(Q(k1,k1)*Q(k2,k2));
+        Q(k2,k1) = Q(k1,k2);
+    end
+    [CholQ,testQ] = chol(Q);
+    if testQ    %% The variance-covariance matrix of the structural innovations is not definite positive.
+        %% We have to compute the eigenvalues of this matrix in order to build the penalty.
+        a = diag(eig(Q));
+        k = find(a < 0);
+        if k > 0
+            fval = bayestopt_.penalty+sum(-a(k));
+            cost_flag = 0;
+            info = 43;
+            return
+        end
+    end
+    offset = offset+estim_params_.ncx;
+end
+if estim_params_.ncn 
+    for i=1:estim_params_.ncn
+        k1 = options_.lgyidx2varobs(estim_params_.corrn(i,1));
+        k2 = options_.lgyidx2varobs(estim_params_.corrn(i,2));
+        H(k1,k2) = xparam1(i+offset)*sqrt(H(k1,k1)*H(k2,k2));
+        H(k2,k1) = H(k1,k2);
+    end
+    [CholH,testH] = chol(H);
+    if testH
+        a = diag(eig(H));
+        k = find(a < 0);
+        if k > 0
+            fval = bayestopt_.penalty+sum(-a(k));
+            cost_flag = 0;
+            info = 44;
+            return
+        end
+    end
+    offset = offset+estim_params_.ncn;
+end
+if estim_params_.np > 0
+    M_.params(estim_params_.param_vals(:,1)) = xparam1(offset+1:end);
+end
+M_.Sigma_e = Q;
+M_.H = H;
+%------------------------------------------------------------------------------
+% 2. call model setup & reduction program
+%------------------------------------------------------------------------------
+[T,R,SteadyState,info] = dynare_resolve(bayestopt_.restrict_var_list,...
+                                        bayestopt_.restrict_columns,...
+                                        bayestopt_.restrict_aux);
+if info(1) == 1 || info(1) == 2 || info(1) == 5
+    fval = bayestopt_.penalty+1;
+    cost_flag = 0;
+    return
+elseif info(1) == 3 || info(1) == 4 || info(1)==6 ||info(1) == 19 || info(1) == 20 || info(1) == 21
+    fval = bayestopt_.penalty+info(2);
+    cost_flag = 0;
+    return
+end
+bayestopt_.mf = bayestopt_.mf1;
+if options_.noconstant
+    constant = zeros(nobs,1);  
+else    
+    if options_.loglinear
+        constant = log(SteadyState(bayestopt_.mfys));
+    else
+        constant = SteadyState(bayestopt_.mfys);
+    end
+end
+if bayestopt_.with_trend
+    trend_coeff = zeros(nobs,1);
+    t = options_.trend_coeffs;
+    for i=1:length(t)
+        if ~isempty(t{i})
+            trend_coeff(i) = evalin('base',t{i});
+        end
+    end
+    trend = repmat(constant,1,gend)+trend_coeff*[1:gend];
+else
+    trend = repmat(constant,1,gend);
+end
+start = options_.presample+1;
+np    = size(T,1);
+mf    = bayestopt_.mf;
+no_missing_data_flag = (number_of_observations==gend*nobs);
+%------------------------------------------------------------------------------
+% 3. Initial condition of the Kalman filter
+%------------------------------------------------------------------------------
+T
+R
+Q
+R*Q*R'
+pause
+options_.lik_init = 1;
+kalman_algo = options_.kalman_algo;
+if options_.lik_init == 1               % Kalman filter
+    if kalman_algo ~= 2
+        kalman_algo = 1;
+    end
+    Pstar = lyapunov_symm(T,R*Q*R',options_.qz_criterium,options_.lyapunov_complex_threshold);
+    Pinf        = [];
+elseif options_.lik_init == 2   % Old Diffuse Kalman filter
+    if kalman_algo ~= 2
+        kalman_algo = 1;
+    end
+    Pstar = options_.Harvey_scale_factor*eye(np);
+    Pinf = [];
+elseif options_.lik_init == 3   % Diffuse Kalman filter
+    if kalman_algo ~= 4
+        kalman_algo = 3;
+    end
+    [QT,ST] = schur(T);
+    e1 = abs(ordeig(ST)) > 2-options_.qz_criterium;
+    [QT,ST] = ordschur(QT,ST,e1);
+    k = find(abs(ordeig(ST)) > 2-options_.qz_criterium);
+    nk = length(k);
+    nk1 = nk+1;
+    Pinf = zeros(np,np);
+    Pinf(1:nk,1:nk) = eye(nk);
+    Pstar = zeros(np,np);
+    B = QT'*R*Q*R'*QT;
+    for i=np:-1:nk+2
+        if ST(i,i-1) == 0
+            if i == np
+                c = zeros(np-nk,1);
+            else
+                c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+...
+                    ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
+            end
+            q = eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i);
+            Pstar(nk1:i,i) = q\(B(nk1:i,i)+c);
+            Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
+        else
+            if i == np
+                c = zeros(np-nk,1);
+                c1 = zeros(np-nk,1);
+            else
+                c = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i,i+1:end)')+...
+                    ST(i,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i)+...
+                    ST(i,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1);
+                c1 = ST(nk1:i,:)*(Pstar(:,i+1:end)*ST(i-1,i+1:end)')+...
+                     ST(i-1,i-1)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i-1)+...
+                     ST(i-1,i)*ST(nk1:i,i+1:end)*Pstar(i+1:end,i);
+            end
+            q = [eye(i-nk)-ST(nk1:i,nk1:i)*ST(i,i) -ST(nk1:i,nk1:i)*ST(i,i-1);...
+                 -ST(nk1:i,nk1:i)*ST(i-1,i) eye(i-nk)-ST(nk1:i,nk1:i)*ST(i-1,i-1)];
+            z =  q\[B(nk1:i,i)+c;B(nk1:i,i-1)+c1];
+            Pstar(nk1:i,i) = z(1:(i-nk));
+            Pstar(nk1:i,i-1) = z(i-nk+1:end);
+            Pstar(i,nk1:i-1) = Pstar(nk1:i-1,i)';
+            Pstar(i-1,nk1:i-2) = Pstar(nk1:i-2,i-1)';
+            i = i - 1;
+        end
+    end
+    if i == nk+2
+        c = ST(nk+1,:)*(Pstar(:,nk+2:end)*ST(nk1,nk+2:end)')+ST(nk1,nk1)*ST(nk1,nk+2:end)*Pstar(nk+2:end,nk1);
+        Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1));
+    end
+    Z = QT(mf,:);
+    R1 = QT'*R;
+    [QQ,RR,EE] = qr(Z*ST(:,1:nk),0);
+    k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8);
+    if length(k) > 0
+        k1 = EE(:,k);
+        dd =ones(nk,1);
+        dd(k1) = zeros(length(k1),1);
+        Pinf(1:nk,1:nk) = diag(dd);
+    end
+end
+if kalman_algo == 2
+end
+kalman_tol = options_.kalman_tol;
+riccati_tol = options_.riccati_tol;
+mf = bayestopt_.mf1;
+Y   = data-trend;
+Pstar
+pause
+%------------------------------------------------------------------------------
+% 4. Likelihood evaluation
+%------------------------------------------------------------------------------
+if (kalman_algo==1)% Multivariate Kalman Filter
+    if no_missing_data_flag
+        LIK = kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol); 
+    else
+        LIK = ...
+            missing_observations_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol, ...
+                                               data_index,number_of_observations,no_more_missing_observations);
+    end
+    if isinf(LIK)
+        kalman_algo = 2;
+    end
+end
+if (kalman_algo==2)% Univariate Kalman Filter
+    no_correlation_flag = 1;
+    if length(H)==1 & H == 0
+        H = zeros(nobs,1);
+    else
+        if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
+            H = diag(H);
+        else
+            no_correlation_flag = 0;
+        end
+    end
+    if no_correlation_flag
+        LIK = univariate_kalman_filter(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations);
+    else
+        LIK = univariate_kalman_filter_corr(T,R,Q,H,Pstar,Y,start,mf,kalman_tol,riccati_tol,data_index,number_of_observations,no_more_missing_observations);
+    end
+end
+if (kalman_algo==3)% Multivariate Diffuse Kalman Filter
+    if no_missing_data_flag
+        LIK = diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y,start,Z,kalman_tol, ...
+                                    riccati_tol);
+    else
+        LIK = missing_observations_diffuse_kalman_filter(ST,R1,Q,H,Pinf, ...
+                                                         Pstar,Y,start,Z,kalman_tol,riccati_tol,...
+                                                         data_index,number_of_observations,...
+                                                         no_more_missing_observations);
+    end
+    if isinf(LIK)
+        kalman_algo = 4;
+    end
+end
+if (kalman_algo==4)% Univariate Diffuse Kalman Filter
+    no_correlation_flag = 1;
+    if length(H)==1 & H == 0
+        H = zeros(nobs,1);
+    else
+        if all(all(abs(H-diag(diag(H)))<1e-14))% ie, the covariance matrix is diagonal...
+            H = diag(H);
+        else
+            no_correlation_flag = 0;
+        end
+    end
+    if no_correlation_flag
+        LIK = univariate_diffuse_kalman_filter(ST,R1,Q,H,Pinf,Pstar,Y, ...
+                                               start,Z,kalman_tol,riccati_tol,data_index,...
+                                               number_of_observations,no_more_missing_observations);
+    else
+        LIK = univariate_diffuse_kalman_filter_corr(ST,R1,Q,H,Pinf,Pstar, ...
+                                                    Y,start,Z,kalman_tol,riccati_tol,...
+                                                    data_index,number_of_observations,...
+                                                    no_more_missing_observations);
+    end
+end
+if isnan(LIK)
+    cost_flag = 0;
+    return
+end
+if imag(LIK)~=0
+    likelihood = bayestopt_.penalty;
+else
+    likelihood = LIK;
+end
+% ------------------------------------------------------------------------------
+% Adds prior if necessary
+% ------------------------------------------------------------------------------
+lnprior = priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7,bayestopt_.p3,bayestopt_.p4);
+fval    = (likelihood-lnprior);
+likelihood
+lnprior
+fval
+pause
+LIKDLL=logposterior(xparam1,Y,mexext)
+pause
+options_.kalman_algo = kalman_algo;
diff --git a/mex/sources/estimation/tests/logposterior_dll_test/rawdata_euromodel_1.m b/mex/sources/estimation/tests/logposterior_dll_test/rawdata_euromodel_1.m
index cde44abc9432e8fd593f938d741b9cac45f9a24d..25bbc92414efddc7adf66d5ab4cc8545af1e71f7 100644
--- a/mex/sources/estimation/tests/logposterior_dll_test/rawdata_euromodel_1.m
+++ b/mex/sources/estimation/tests/logposterior_dll_test/rawdata_euromodel_1.m
@@ -1,967 +1,967 @@
-C =[
-   -7.4073
-   -6.1860
-   -6.5983
-   -5.6088
-   -5.0547
-   -4.4774
-   -3.8081
-   -3.8425
-   -2.4178
-   -1.9835
-   -1.0395
-   -0.1583
-   -0.0397
-    0.3505
-   -0.1879
-   -0.0067
-    0.0478
-   -1.2247
-   -1.4349
-   -0.7973
-   -0.0461
-    0.5844
-    1.1372
-    1.3801
-    1.8023
-    2.2972
-    2.0469
-    2.5435
-    2.8169
-    3.2007
-    2.6705
-    3.0518
-    3.2445
-    3.8443
-    3.8525
-    4.9494
-    4.2770
-    4.9532
-    5.1441
-    3.7124
-    3.9880
-    3.6926
-    2.6005
-    1.8679
-    1.9085
-    1.5563
-    1.2308
-    0.3264
-   -0.2208
-   -0.2483
-   -0.4082
-   -1.0315
-   -1.6030
-   -1.5499
-   -1.3777
-   -2.1675
-   -2.5138
-   -2.8820
-   -2.6958
-   -2.4719
-   -1.9854
-   -1.7954
-   -2.2362
-   -1.0595
-   -0.8808
-   -0.8548
-   -1.2839
-   -0.1363
-    0.2104
-    0.8810
-    0.3555
-    0.4766
-    1.3269
-    1.4506
-    1.4308
-    1.6263
-    1.9842
-    2.3948
-    2.8710
-    3.0177
-    2.9305
-    3.1739
-    3.7380
-    3.8285
-    3.3342
-    3.7447
-    3.7830
-    3.1039
-    2.8413
-    3.0338
-    0.3669
-    0.0847
-    0.0104
-    0.2115
-   -0.6649
-   -0.9625
-   -0.7330
-   -0.8664
-   -1.4441
-   -1.0179
-   -1.2729
-   -1.9539
-   -1.4427
-   -2.0371
-   -1.9764
-   -2.5654
-   -2.8570
-   -2.5842
-   -3.0427
-   -2.8312
-   -2.3320
-   -2.2768
-   -2.1816
-   -2.1043
-   -1.8969
-   -2.2388
-   -2.1679
-   -2.1172
-];
-
-E =[
-    0.6263
-    0.7368
-    0.7477
-    1.0150
-    0.6934
-    0.4135
-    0.3845
-    0.2380
-    0.2853
-    0.5999
-    0.8622
-    1.2116
-    1.4921
-    1.5816
-    1.7259
-    1.6276
-    1.2422
-    0.8084
-    0.4710
-   -0.3704
-   -0.6427
-   -0.5323
-   -0.5562
-   -0.3651
-   -0.4356
-   -0.7164
-   -0.5816
-   -0.4635
-   -0.8456
-   -0.9708
-   -0.7138
-   -0.7499
-   -0.6941
-   -0.6656
-   -0.2912
-   -0.1650
-    0.0774
-    0.2307
-    0.4484
-    0.4942
-    0.4653
-    0.2196
-    0.1736
-   -0.1595
-   -0.3918
-   -0.4611
-   -0.8493
-   -0.7384
-   -1.0604
-   -1.2166
-   -1.7187
-   -1.6932
-   -1.7830
-   -1.7035
-   -2.2079
-   -2.3769
-   -2.2511
-   -2.1093
-   -2.4638
-   -2.4027
-   -2.1313
-   -1.9199
-   -1.7941
-   -1.4661
-   -1.2269
-   -1.0392
-   -1.0725
-   -0.7156
-   -0.4778
-   -0.4233
-   -0.0409
-    0.1620
-    0.4280
-    0.5873
-    1.0323
-    1.3420
-    1.6902
-    2.0680
-    2.8219
-    3.2511
-    3.2930
-    3.5633
-    3.8992
-    3.6874
-    3.2849
-    3.1614
-    2.6221
-    2.5067
-    1.9223
-    1.1777
-    0.4483
-   -0.0661
-   -0.4424
-   -0.9000
-   -1.1478
-   -1.2047
-   -1.1412
-   -1.2383
-   -1.1048
-   -0.9716
-   -0.9287
-   -1.0057
-   -1.0827
-   -1.0200
-   -1.0072
-   -1.1740
-   -1.2809
-   -1.1086
-   -0.9866
-   -0.8947
-   -0.5875
-   -0.2329
-    0.1493
-    0.4906
-    0.8400
-    1.0720
-    1.2648
-    1.5431
-];
-
-I =[
-    2.6617
-    2.4325
-    1.9592
-    3.2530
-    2.9949
-    3.7918
-    4.7444
-    4.8289
-    5.5983
-    7.8923
-    9.4297
-    9.5010
-   10.0150
-   10.0413
-    9.6046
-    6.4766
-    5.9647
-    3.0114
-    0.5683
-   -2.1226
-   -2.1855
-   -0.8329
-   -1.5207
-   -1.3419
-   -1.7897
-   -0.1476
-    0.4675
-   -1.6516
-   -1.5419
-   -1.3050
-   -1.2451
-   -0.7815
-   -0.7796
-   -0.3612
-   -2.4072
-    1.1162
-    1.1383
-    3.4132
-    5.0356
-    2.8016
-    2.1734
-    0.9366
-   -0.7050
-   -1.5021
-   -2.9868
-   -6.0237
-   -6.2589
-   -6.9138
-   -8.2340
-   -9.2589
-   -9.2465
-   -9.6988
-   -9.7782
-  -10.5645
-  -10.7544
-  -13.1583
-  -12.2718
-  -12.0131
-  -13.5983
-  -12.3579
-  -10.9146
-  -11.1572
-  -12.4935
-   -9.4393
-   -8.5535
-   -7.3723
-  -10.0169
-   -6.6088
-   -5.2045
-   -4.1024
-   -2.8472
-   -1.3139
-    0.0477
-    1.5629
-    3.6947
-    4.0327
-    4.1320
-    7.1400
-    9.1036
-    8.5609
-    7.6576
-    8.8022
-    8.9611
-   10.0871
-    9.4797
-    9.3964
-   10.0363
-    8.6340
-    6.6522
-    4.4471
-    0.2854
-   -2.1879
-   -2.9879
-   -4.1021
-   -2.7713
-   -2.2281
-   -1.2908
-   -0.3250
-    0.6534
-    0.3942
-    0.3534
-   -0.1532
-   -1.7936
-    0.4909
-    0.3634
-    0.4290
-   -0.9709
-    0.1942
-    0.6103
-    1.4426
-    2.7225
-    1.7525
-    3.2780
-    3.5985
-    4.9011
-    5.3312
-    6.4402
-    6.6529
-];
-
-L =[
-    0.6263
-    0.7368
-    0.7477
-    1.0150
-    0.6934
-    0.4135
-    0.3845
-    0.2380
-    0.2853
-    0.5999
-    0.8622
-    1.2116
-    1.4921
-    1.5816
-    1.7259
-    1.6276
-    1.2422
-    0.8084
-    0.4710
-   -0.3704
-   -0.6427
-   -0.5323
-   -0.5562
-   -0.3651
-   -0.4356
-   -0.7164
-   -0.5816
-   -0.4635
-   -0.8456
-   -0.9708
-   -0.7138
-   -0.7499
-   -0.6941
-   -0.6656
-   -0.2912
-   -0.1650
-    0.0774
-    0.2307
-    0.4484
-    0.4942
-    0.4653
-    0.2196
-    0.1736
-   -0.1595
-   -0.3918
-   -0.4611
-   -0.8493
-   -0.7384
-   -1.0604
-   -1.2166
-   -1.7187
-   -1.6932
-   -1.7830
-   -1.7035
-   -2.2079
-   -2.3769
-   -2.2511
-   -2.1093
-   -2.4638
-   -2.4027
-   -2.1313
-   -1.9199
-   -1.7941
-   -1.4661
-   -1.2269
-   -1.0392
-   -1.0725
-   -0.7156
-   -0.4778
-   -0.4233
-   -0.0409
-    0.1620
-    0.4280
-    0.5873
-    1.0323
-    1.3420
-    1.6902
-    2.0680
-    2.8219
-    3.2511
-    3.2930
-    3.5633
-    3.8992
-    3.6874
-    3.2849
-    3.1614
-    2.6221
-    2.5067
-    1.9223
-    1.1777
-    0.4483
-   -0.0661
-   -0.4424
-   -0.9000
-   -1.1478
-   -1.2047
-   -1.1412
-   -1.2383
-   -1.1048
-   -0.9716
-   -0.9287
-   -1.0057
-   -1.0827
-   -1.0200
-   -1.0072
-   -1.1740
-   -1.2809
-   -1.1086
-   -0.9866
-   -0.8947
-   -0.5875
-   -0.2329
-    0.1493
-    0.4906
-    0.8400
-    1.0720
-    1.2648
-    1.5431
-];
-
-PIE =[
-   -1.0113
-   -0.8305
-    0.2332
-   -0.8746
-   -0.7978
-   -0.9220
-   -0.2487
-   -0.7749
-   -0.5460
-   -0.5347
-    0.5050
-   -0.0334
-    0.6756
-    0.8791
-    0.7267
-    1.0997
-    1.1750
-    1.1927
-    0.4420
-    0.5357
-    0.0345
-    0.0196
-    0.3371
-    0.9379
-    1.2160
-    0.3393
-    0.5813
-    0.7410
-    0.3374
-    0.2616
-    0.4025
-    0.4799
-    0.5981
-   -0.1523
-    0.4458
-    0.2182
-    0.9793
-    0.7562
-    1.0064
-    0.8203
-    0.6966
-    0.3352
-    0.6581
-    0.6111
-    0.9833
-    1.1991
-    0.9562
-    0.3868
-    0.2939
-    0.2471
-    0.8331
-    0.0715
-    0.3910
-    0.3301
-    0.2547
-   -0.2702
-   -0.2998
-   -0.1953
-   -0.2293
-   -0.3284
-    0.0480
-   -0.0374
-    0.3253
-   -0.3434
-   -0.3892
-   -0.7178
-   -0.4758
-   -0.6794
-   -0.8505
-   -0.3512
-   -0.4436
-   -0.5101
-   -0.4574
-   -0.2696
-   -0.1047
-   -0.5745
-   -0.2989
-   -0.0063
-    0.0088
-   -0.1184
-   -0.1506
-   -0.4073
-    0.2674
-    0.2896
-    0.0669
-    0.1166
-   -0.1699
-   -0.2518
-   -0.0562
-   -0.3269
-   -0.0703
-   -0.1046
-   -0.4888
-   -0.3524
-   -0.2485
-   -0.5870
-   -0.4546
-   -0.3970
-   -0.2353
-   -0.0352
-   -0.2171
-   -0.3754
-   -0.4322
-   -0.4572
-   -0.4903
-   -0.4518
-   -0.6435
-   -0.6304
-   -0.4148
-   -0.2892
-   -0.4318
-   -0.6010
-   -0.4148
-   -0.4315
-   -0.3531
-   -0.8053
-   -0.4680
-   -0.4263
-];
-
-R =[
-   -1.0750
-   -1.1540
-   -1.3682
-   -1.4569
-   -1.3490
-   -1.4011
-   -1.6486
-   -1.6968
-   -1.6976
-   -1.2567
-   -1.1392
-   -0.7783
-   -0.3021
-   -0.0435
-    0.0066
-   -0.0043
-    0.1029
-   -0.0628
-   -0.5358
-   -0.9627
-   -1.1079
-   -1.0918
-   -0.9966
-   -0.6223
-   -0.3616
-   -0.2711
-   -0.0997
-   -0.2810
-   -0.3710
-   -0.3167
-   -0.5301
-   -0.5826
-   -0.3194
-   -0.2713
-   -0.5287
-   -0.2432
-    0.1098
-    0.5349
-    0.7094
-    0.8415
-    0.6226
-    0.7376
-    0.9316
-    1.4370
-    1.5853
-    1.4267
-    1.1783
-    1.2046
-    0.9689
-    0.7918
-    0.6315
-    0.5950
-    0.6853
-    0.7171
-    0.5887
-    0.4873
-    0.4027
-    0.3489
-    0.2934
-    0.3060
-    0.1741
-    0.0348
-    0.0771
-   -0.1005
-   -0.1518
-   -0.1104
-   -0.0681
-   -0.0059
-    0.0256
-    0.0404
-   -0.1721
-   -0.2002
-    0.0015
-    0.1249
-    0.3738
-    0.4320
-    0.5579
-    0.8186
-    0.8727
-    0.7356
-    0.7243
-    0.8635
-    0.9058
-    0.7656
-    0.7936
-    0.8631
-    0.9074
-    0.9547
-    1.2045
-    1.0850
-    0.9178
-    0.5242
-    0.3178
-    0.1472
-    0.0227
-   -0.0799
-   -0.0611
-   -0.0140
-    0.1132
-    0.1774
-    0.0782
-    0.0436
-   -0.1596
-   -0.2691
-   -0.2895
-   -0.3791
-   -0.4020
-   -0.4166
-   -0.4037
-   -0.3636
-   -0.4075
-   -0.4311
-   -0.4470
-   -0.5111
-   -0.6274
-   -0.7261
-   -0.6974
-   -0.5012
-];
-
-W =[
-  -14.8791
-  -13.2300
-  -13.5037
-  -13.0249
-  -11.2546
-  -10.0148
-   -8.8586
-   -8.5739
-   -7.7851
-   -6.7136
-   -5.5878
-   -4.6881
-   -3.8039
-   -3.0366
-   -2.7342
-   -1.3135
-   -0.7387
-   -0.1131
-   -0.2769
-    0.8696
-    1.8855
-    2.3667
-    2.4942
-    3.2049
-    3.9682
-    5.1500
-    4.7047
-    4.7827
-    5.3377
-    5.6614
-    5.2813
-    5.2967
-    5.5175
-    6.1526
-    5.6627
-    6.0694
-    6.5824
-    6.9032
-    6.7849
-    6.6896
-    6.6201
-    6.9933
-    5.8959
-    6.7419
-    6.9999
-    6.4009
-    5.5083
-    5.1054
-    5.2813
-    4.5790
-    3.9589
-    3.8599
-    3.8978
-    2.7957
-    3.2480
-    1.4634
-    1.9219
-    1.8398
-    1.9279
-    1.8316
-    1.6092
-    1.2741
-    0.2031
-   -0.0236
-   -0.1004
-   -0.3034
-   -1.0273
-   -0.2205
-    0.0458
-    0.2386
-   -0.0977
-   -0.3145
-   -0.1416
-   -0.7009
-   -0.9082
-   -0.8802
-   -0.5644
-   -0.5852
-   -0.5346
-    0.0652
-    0.1301
-    0.3444
-   -0.3592
-    0.8096
-    0.9644
-    1.0289
-    1.2781
-    1.2298
-    2.2134
-    2.0808
-    0.4925
-    0.6506
-    0.5531
-    0.2456
-   -0.5351
-   -0.8183
-   -0.8967
-   -0.7268
-   -1.0738
-   -1.2844
-   -1.4338
-   -1.6995
-   -1.7085
-   -2.2889
-   -2.1018
-   -2.4273
-   -2.4609
-   -2.1407
-   -2.3847
-   -3.1689
-   -4.5581
-   -4.1027
-   -4.2436
-   -4.8836
-   -5.9660
-   -4.9971
-   -5.2386
-   -5.6618
-];
-
-Y =[
-   -4.9347
-   -4.6205
-   -5.2198
-   -4.5937
-   -3.8015
-   -3.6643
-   -2.7239
-   -2.7524
-   -2.0634
-   -1.0112
-    0.0530
-    0.7623
-    1.7927
-    2.1486
-    2.4866
-    2.1456
-    2.1671
-   -0.0254
-   -1.6716
-   -1.9673
-   -1.6109
-   -1.0292
-   -0.1222
-    0.7329
-    1.1234
-    2.0603
-    1.7998
-    1.4820
-    1.1732
-    1.6424
-    1.5382
-    2.1399
-    2.0127
-    2.7210
-    2.4966
-    3.5249
-    3.6237
-    4.2011
-    4.5634
-    3.3442
-    2.7761
-    1.9812
-    1.3779
-    1.4616
-    1.3029
-    0.7594
-    0.3695
-    0.0832
-   -0.8118
-   -1.4557
-   -1.4850
-   -1.2346
-   -1.5696
-   -1.3785
-   -0.7682
-   -2.0308
-   -1.7778
-   -1.7801
-   -2.1711
-   -1.7469
-   -1.3413
-   -1.3352
-   -2.4390
-   -1.2125
-   -1.1695
-   -1.0891
-   -2.4753
-   -1.3503
-   -0.9412
-   -0.1470
-    0.0026
-    0.1108
-    0.6890
-    1.3520
-    1.6018
-    2.0667
-    1.7625
-    2.6658
-    3.4048
-    3.2507
-    3.4251
-    3.2174
-    3.1903
-    3.3396
-    3.1358
-    2.8625
-    3.3546
-    2.4609
-    1.9534
-    0.9962
-   -0.7904
-   -1.1672
-   -1.2586
-   -1.3593
-   -1.3443
-   -0.9413
-   -0.6023
-   -0.4516
-   -0.5129
-   -0.8741
-   -1.0784
-   -1.4091
-   -1.3627
-   -1.5731
-   -1.6037
-   -1.8814
-   -2.1482
-   -1.3597
-   -1.1855
-   -1.1122
-   -0.8424
-   -0.9747
-   -1.1385
-   -1.4548
-   -1.4284
-   -1.4633
-   -1.0621
-   -0.7871
-];
+C =[
+   -7.4073
+   -6.1860
+   -6.5983
+   -5.6088
+   -5.0547
+   -4.4774
+   -3.8081
+   -3.8425
+   -2.4178
+   -1.9835
+   -1.0395
+   -0.1583
+   -0.0397
+    0.3505
+   -0.1879
+   -0.0067
+    0.0478
+   -1.2247
+   -1.4349
+   -0.7973
+   -0.0461
+    0.5844
+    1.1372
+    1.3801
+    1.8023
+    2.2972
+    2.0469
+    2.5435
+    2.8169
+    3.2007
+    2.6705
+    3.0518
+    3.2445
+    3.8443
+    3.8525
+    4.9494
+    4.2770
+    4.9532
+    5.1441
+    3.7124
+    3.9880
+    3.6926
+    2.6005
+    1.8679
+    1.9085
+    1.5563
+    1.2308
+    0.3264
+   -0.2208
+   -0.2483
+   -0.4082
+   -1.0315
+   -1.6030
+   -1.5499
+   -1.3777
+   -2.1675
+   -2.5138
+   -2.8820
+   -2.6958
+   -2.4719
+   -1.9854
+   -1.7954
+   -2.2362
+   -1.0595
+   -0.8808
+   -0.8548
+   -1.2839
+   -0.1363
+    0.2104
+    0.8810
+    0.3555
+    0.4766
+    1.3269
+    1.4506
+    1.4308
+    1.6263
+    1.9842
+    2.3948
+    2.8710
+    3.0177
+    2.9305
+    3.1739
+    3.7380
+    3.8285
+    3.3342
+    3.7447
+    3.7830
+    3.1039
+    2.8413
+    3.0338
+    0.3669
+    0.0847
+    0.0104
+    0.2115
+   -0.6649
+   -0.9625
+   -0.7330
+   -0.8664
+   -1.4441
+   -1.0179
+   -1.2729
+   -1.9539
+   -1.4427
+   -2.0371
+   -1.9764
+   -2.5654
+   -2.8570
+   -2.5842
+   -3.0427
+   -2.8312
+   -2.3320
+   -2.2768
+   -2.1816
+   -2.1043
+   -1.8969
+   -2.2388
+   -2.1679
+   -2.1172
+];
+
+E =[
+    0.6263
+    0.7368
+    0.7477
+    1.0150
+    0.6934
+    0.4135
+    0.3845
+    0.2380
+    0.2853
+    0.5999
+    0.8622
+    1.2116
+    1.4921
+    1.5816
+    1.7259
+    1.6276
+    1.2422
+    0.8084
+    0.4710
+   -0.3704
+   -0.6427
+   -0.5323
+   -0.5562
+   -0.3651
+   -0.4356
+   -0.7164
+   -0.5816
+   -0.4635
+   -0.8456
+   -0.9708
+   -0.7138
+   -0.7499
+   -0.6941
+   -0.6656
+   -0.2912
+   -0.1650
+    0.0774
+    0.2307
+    0.4484
+    0.4942
+    0.4653
+    0.2196
+    0.1736
+   -0.1595
+   -0.3918
+   -0.4611
+   -0.8493
+   -0.7384
+   -1.0604
+   -1.2166
+   -1.7187
+   -1.6932
+   -1.7830
+   -1.7035
+   -2.2079
+   -2.3769
+   -2.2511
+   -2.1093
+   -2.4638
+   -2.4027
+   -2.1313
+   -1.9199
+   -1.7941
+   -1.4661
+   -1.2269
+   -1.0392
+   -1.0725
+   -0.7156
+   -0.4778
+   -0.4233
+   -0.0409
+    0.1620
+    0.4280
+    0.5873
+    1.0323
+    1.3420
+    1.6902
+    2.0680
+    2.8219
+    3.2511
+    3.2930
+    3.5633
+    3.8992
+    3.6874
+    3.2849
+    3.1614
+    2.6221
+    2.5067
+    1.9223
+    1.1777
+    0.4483
+   -0.0661
+   -0.4424
+   -0.9000
+   -1.1478
+   -1.2047
+   -1.1412
+   -1.2383
+   -1.1048
+   -0.9716
+   -0.9287
+   -1.0057
+   -1.0827
+   -1.0200
+   -1.0072
+   -1.1740
+   -1.2809
+   -1.1086
+   -0.9866
+   -0.8947
+   -0.5875
+   -0.2329
+    0.1493
+    0.4906
+    0.8400
+    1.0720
+    1.2648
+    1.5431
+];
+
+I =[
+    2.6617
+    2.4325
+    1.9592
+    3.2530
+    2.9949
+    3.7918
+    4.7444
+    4.8289
+    5.5983
+    7.8923
+    9.4297
+    9.5010
+   10.0150
+   10.0413
+    9.6046
+    6.4766
+    5.9647
+    3.0114
+    0.5683
+   -2.1226
+   -2.1855
+   -0.8329
+   -1.5207
+   -1.3419
+   -1.7897
+   -0.1476
+    0.4675
+   -1.6516
+   -1.5419
+   -1.3050
+   -1.2451
+   -0.7815
+   -0.7796
+   -0.3612
+   -2.4072
+    1.1162
+    1.1383
+    3.4132
+    5.0356
+    2.8016
+    2.1734
+    0.9366
+   -0.7050
+   -1.5021
+   -2.9868
+   -6.0237
+   -6.2589
+   -6.9138
+   -8.2340
+   -9.2589
+   -9.2465
+   -9.6988
+   -9.7782
+  -10.5645
+  -10.7544
+  -13.1583
+  -12.2718
+  -12.0131
+  -13.5983
+  -12.3579
+  -10.9146
+  -11.1572
+  -12.4935
+   -9.4393
+   -8.5535
+   -7.3723
+  -10.0169
+   -6.6088
+   -5.2045
+   -4.1024
+   -2.8472
+   -1.3139
+    0.0477
+    1.5629
+    3.6947
+    4.0327
+    4.1320
+    7.1400
+    9.1036
+    8.5609
+    7.6576
+    8.8022
+    8.9611
+   10.0871
+    9.4797
+    9.3964
+   10.0363
+    8.6340
+    6.6522
+    4.4471
+    0.2854
+   -2.1879
+   -2.9879
+   -4.1021
+   -2.7713
+   -2.2281
+   -1.2908
+   -0.3250
+    0.6534
+    0.3942
+    0.3534
+   -0.1532
+   -1.7936
+    0.4909
+    0.3634
+    0.4290
+   -0.9709
+    0.1942
+    0.6103
+    1.4426
+    2.7225
+    1.7525
+    3.2780
+    3.5985
+    4.9011
+    5.3312
+    6.4402
+    6.6529
+];
+
+L =[
+    0.6263
+    0.7368
+    0.7477
+    1.0150
+    0.6934
+    0.4135
+    0.3845
+    0.2380
+    0.2853
+    0.5999
+    0.8622
+    1.2116
+    1.4921
+    1.5816
+    1.7259
+    1.6276
+    1.2422
+    0.8084
+    0.4710
+   -0.3704
+   -0.6427
+   -0.5323
+   -0.5562
+   -0.3651
+   -0.4356
+   -0.7164
+   -0.5816
+   -0.4635
+   -0.8456
+   -0.9708
+   -0.7138
+   -0.7499
+   -0.6941
+   -0.6656
+   -0.2912
+   -0.1650
+    0.0774
+    0.2307
+    0.4484
+    0.4942
+    0.4653
+    0.2196
+    0.1736
+   -0.1595
+   -0.3918
+   -0.4611
+   -0.8493
+   -0.7384
+   -1.0604
+   -1.2166
+   -1.7187
+   -1.6932
+   -1.7830
+   -1.7035
+   -2.2079
+   -2.3769
+   -2.2511
+   -2.1093
+   -2.4638
+   -2.4027
+   -2.1313
+   -1.9199
+   -1.7941
+   -1.4661
+   -1.2269
+   -1.0392
+   -1.0725
+   -0.7156
+   -0.4778
+   -0.4233
+   -0.0409
+    0.1620
+    0.4280
+    0.5873
+    1.0323
+    1.3420
+    1.6902
+    2.0680
+    2.8219
+    3.2511
+    3.2930
+    3.5633
+    3.8992
+    3.6874
+    3.2849
+    3.1614
+    2.6221
+    2.5067
+    1.9223
+    1.1777
+    0.4483
+   -0.0661
+   -0.4424
+   -0.9000
+   -1.1478
+   -1.2047
+   -1.1412
+   -1.2383
+   -1.1048
+   -0.9716
+   -0.9287
+   -1.0057
+   -1.0827
+   -1.0200
+   -1.0072
+   -1.1740
+   -1.2809
+   -1.1086
+   -0.9866
+   -0.8947
+   -0.5875
+   -0.2329
+    0.1493
+    0.4906
+    0.8400
+    1.0720
+    1.2648
+    1.5431
+];
+
+PIE =[
+   -1.0113
+   -0.8305
+    0.2332
+   -0.8746
+   -0.7978
+   -0.9220
+   -0.2487
+   -0.7749
+   -0.5460
+   -0.5347
+    0.5050
+   -0.0334
+    0.6756
+    0.8791
+    0.7267
+    1.0997
+    1.1750
+    1.1927
+    0.4420
+    0.5357
+    0.0345
+    0.0196
+    0.3371
+    0.9379
+    1.2160
+    0.3393
+    0.5813
+    0.7410
+    0.3374
+    0.2616
+    0.4025
+    0.4799
+    0.5981
+   -0.1523
+    0.4458
+    0.2182
+    0.9793
+    0.7562
+    1.0064
+    0.8203
+    0.6966
+    0.3352
+    0.6581
+    0.6111
+    0.9833
+    1.1991
+    0.9562
+    0.3868
+    0.2939
+    0.2471
+    0.8331
+    0.0715
+    0.3910
+    0.3301
+    0.2547
+   -0.2702
+   -0.2998
+   -0.1953
+   -0.2293
+   -0.3284
+    0.0480
+   -0.0374
+    0.3253
+   -0.3434
+   -0.3892
+   -0.7178
+   -0.4758
+   -0.6794
+   -0.8505
+   -0.3512
+   -0.4436
+   -0.5101
+   -0.4574
+   -0.2696
+   -0.1047
+   -0.5745
+   -0.2989
+   -0.0063
+    0.0088
+   -0.1184
+   -0.1506
+   -0.4073
+    0.2674
+    0.2896
+    0.0669
+    0.1166
+   -0.1699
+   -0.2518
+   -0.0562
+   -0.3269
+   -0.0703
+   -0.1046
+   -0.4888
+   -0.3524
+   -0.2485
+   -0.5870
+   -0.4546
+   -0.3970
+   -0.2353
+   -0.0352
+   -0.2171
+   -0.3754
+   -0.4322
+   -0.4572
+   -0.4903
+   -0.4518
+   -0.6435
+   -0.6304
+   -0.4148
+   -0.2892
+   -0.4318
+   -0.6010
+   -0.4148
+   -0.4315
+   -0.3531
+   -0.8053
+   -0.4680
+   -0.4263
+];
+
+R =[
+   -1.0750
+   -1.1540
+   -1.3682
+   -1.4569
+   -1.3490
+   -1.4011
+   -1.6486
+   -1.6968
+   -1.6976
+   -1.2567
+   -1.1392
+   -0.7783
+   -0.3021
+   -0.0435
+    0.0066
+   -0.0043
+    0.1029
+   -0.0628
+   -0.5358
+   -0.9627
+   -1.1079
+   -1.0918
+   -0.9966
+   -0.6223
+   -0.3616
+   -0.2711
+   -0.0997
+   -0.2810
+   -0.3710
+   -0.3167
+   -0.5301
+   -0.5826
+   -0.3194
+   -0.2713
+   -0.5287
+   -0.2432
+    0.1098
+    0.5349
+    0.7094
+    0.8415
+    0.6226
+    0.7376
+    0.9316
+    1.4370
+    1.5853
+    1.4267
+    1.1783
+    1.2046
+    0.9689
+    0.7918
+    0.6315
+    0.5950
+    0.6853
+    0.7171
+    0.5887
+    0.4873
+    0.4027
+    0.3489
+    0.2934
+    0.3060
+    0.1741
+    0.0348
+    0.0771
+   -0.1005
+   -0.1518
+   -0.1104
+   -0.0681
+   -0.0059
+    0.0256
+    0.0404
+   -0.1721
+   -0.2002
+    0.0015
+    0.1249
+    0.3738
+    0.4320
+    0.5579
+    0.8186
+    0.8727
+    0.7356
+    0.7243
+    0.8635
+    0.9058
+    0.7656
+    0.7936
+    0.8631
+    0.9074
+    0.9547
+    1.2045
+    1.0850
+    0.9178
+    0.5242
+    0.3178
+    0.1472
+    0.0227
+   -0.0799
+   -0.0611
+   -0.0140
+    0.1132
+    0.1774
+    0.0782
+    0.0436
+   -0.1596
+   -0.2691
+   -0.2895
+   -0.3791
+   -0.4020
+   -0.4166
+   -0.4037
+   -0.3636
+   -0.4075
+   -0.4311
+   -0.4470
+   -0.5111
+   -0.6274
+   -0.7261
+   -0.6974
+   -0.5012
+];
+
+W =[
+  -14.8791
+  -13.2300
+  -13.5037
+  -13.0249
+  -11.2546
+  -10.0148
+   -8.8586
+   -8.5739
+   -7.7851
+   -6.7136
+   -5.5878
+   -4.6881
+   -3.8039
+   -3.0366
+   -2.7342
+   -1.3135
+   -0.7387
+   -0.1131
+   -0.2769
+    0.8696
+    1.8855
+    2.3667
+    2.4942
+    3.2049
+    3.9682
+    5.1500
+    4.7047
+    4.7827
+    5.3377
+    5.6614
+    5.2813
+    5.2967
+    5.5175
+    6.1526
+    5.6627
+    6.0694
+    6.5824
+    6.9032
+    6.7849
+    6.6896
+    6.6201
+    6.9933
+    5.8959
+    6.7419
+    6.9999
+    6.4009
+    5.5083
+    5.1054
+    5.2813
+    4.5790
+    3.9589
+    3.8599
+    3.8978
+    2.7957
+    3.2480
+    1.4634
+    1.9219
+    1.8398
+    1.9279
+    1.8316
+    1.6092
+    1.2741
+    0.2031
+   -0.0236
+   -0.1004
+   -0.3034
+   -1.0273
+   -0.2205
+    0.0458
+    0.2386
+   -0.0977
+   -0.3145
+   -0.1416
+   -0.7009
+   -0.9082
+   -0.8802
+   -0.5644
+   -0.5852
+   -0.5346
+    0.0652
+    0.1301
+    0.3444
+   -0.3592
+    0.8096
+    0.9644
+    1.0289
+    1.2781
+    1.2298
+    2.2134
+    2.0808
+    0.4925
+    0.6506
+    0.5531
+    0.2456
+   -0.5351
+   -0.8183
+   -0.8967
+   -0.7268
+   -1.0738
+   -1.2844
+   -1.4338
+   -1.6995
+   -1.7085
+   -2.2889
+   -2.1018
+   -2.4273
+   -2.4609
+   -2.1407
+   -2.3847
+   -3.1689
+   -4.5581
+   -4.1027
+   -4.2436
+   -4.8836
+   -5.9660
+   -4.9971
+   -5.2386
+   -5.6618
+];
+
+Y =[
+   -4.9347
+   -4.6205
+   -5.2198
+   -4.5937
+   -3.8015
+   -3.6643
+   -2.7239
+   -2.7524
+   -2.0634
+   -1.0112
+    0.0530
+    0.7623
+    1.7927
+    2.1486
+    2.4866
+    2.1456
+    2.1671
+   -0.0254
+   -1.6716
+   -1.9673
+   -1.6109
+   -1.0292
+   -0.1222
+    0.7329
+    1.1234
+    2.0603
+    1.7998
+    1.4820
+    1.1732
+    1.6424
+    1.5382
+    2.1399
+    2.0127
+    2.7210
+    2.4966
+    3.5249
+    3.6237
+    4.2011
+    4.5634
+    3.3442
+    2.7761
+    1.9812
+    1.3779
+    1.4616
+    1.3029
+    0.7594
+    0.3695
+    0.0832
+   -0.8118
+   -1.4557
+   -1.4850
+   -1.2346
+   -1.5696
+   -1.3785
+   -0.7682
+   -2.0308
+   -1.7778
+   -1.7801
+   -2.1711
+   -1.7469
+   -1.3413
+   -1.3352
+   -2.4390
+   -1.2125
+   -1.1695
+   -1.0891
+   -2.4753
+   -1.3503
+   -0.9412
+   -0.1470
+    0.0026
+    0.1108
+    0.6890
+    1.3520
+    1.6018
+    2.0667
+    1.7625
+    2.6658
+    3.4048
+    3.2507
+    3.4251
+    3.2174
+    3.1903
+    3.3396
+    3.1358
+    2.8625
+    3.3546
+    2.4609
+    1.9534
+    0.9962
+   -0.7904
+   -1.1672
+   -1.2586
+   -1.3593
+   -1.3443
+   -0.9413
+   -0.6023
+   -0.4516
+   -0.5129
+   -0.8741
+   -1.0784
+   -1.4091
+   -1.3627
+   -1.5731
+   -1.6037
+   -1.8814
+   -2.1482
+   -1.3597
+   -1.1855
+   -1.1122
+   -0.8424
+   -0.9747
+   -1.1385
+   -1.4548
+   -1.4284
+   -1.4633
+   -1.0621
+   -0.7871
+];
diff --git a/mex/sources/estimation/tests/logposterior_dll_test/sweuromodel_dll.mod b/mex/sources/estimation/tests/logposterior_dll_test/sweuromodel_dll.mod
index 999485ee82aeeba8a5e53d5c1fd35cf231ec0f33..a6a19f55b1dde641b63922f58cfee92edee233f1 100644
--- a/mex/sources/estimation/tests/logposterior_dll_test/sweuromodel_dll.mod
+++ b/mex/sources/estimation/tests/logposterior_dll_test/sweuromodel_dll.mod
@@ -1,184 +1,184 @@
-//options_.usePartInfo=1;
-
-var MC E EF R_KF QF CF IF YF LF PIEF WF RF R_K Q C I Y L PIE W R EE_A PIE_BAR EE_B EE_G EE_L EE_I KF K one BIGTHETA;    
-
-varexo E_A E_B E_G E_L E_I ETA_R E_PIE_BAR ETA_Q ETA_P ETA_W  ;  
- 
-parameters 
-xi_e lambda_w alpha czcap beta phi_i tau sig_c hab ccs cinvs phi_y gamma_w xi_w gamma_p xi_p sig_l r_dpi 
-r_pie r_dy r_y rho rho_a rho_pb rho_b rho_g rho_l rho_i LMP  ;
-
-
-
-alpha=.30;
-beta=.99;
-tau=0.025;
-ccs=0.6;
-cinvs=.22;  //% alpha*(tau+ctrend)/R_K   R_K=ctrend/beta-1+tau  
-lambda_w = 0.5;
-phi_i= 6.771;
-sig_c=   1.353; 
-hab=    0.573;    
-xi_w=   0.737;
-sig_l=    2.400;
-xi_p=   0.908;
-xi_e= 0.599;
-gamma_w=    0.763;
-gamma_p=    0.469;
-czcap=    0.169;
-phi_y=    1.408;
-r_pie=     1.684;
-r_dpi=    0.14;
-rho=      0.961;
-r_y=      0.099;
-r_dy=     0.159;
-rho_a=    0.823;
-rho_b=    0.855;
-rho_g=    0.949;
-rho_l=   0.889;
-rho_i=   0.927;
-rho_pb=  0.924;
-LMP = 0.0 ; //NEW.
-
-model(linear, use_dll); 
-          CF = (1/(1+hab))*(CF(1)+hab*CF(-1))-((1-hab)/((1+hab)*sig_c))*(RF-PIEF(1)-EE_B) ;
-	      0 =  alpha*R_KF+(1-alpha)*WF -EE_A ;
-          PIEF = 0*one;
-	      IF = (1/(1+beta))* ((  IF(-1) + beta*(IF(1)))+(1/phi_i)*QF)+0*ETA_Q+EE_I ;
-	      QF = -(RF-PIEF(1))+(1-beta*(1-tau))*((0+czcap)/czcap)*R_KF(1)+beta*(1-tau)*QF(1) +0*EE_I ;
-          KF =  (1-tau)*KF(-1)+tau*IF(-1) ;
-	      YF = (ccs*CF+cinvs*IF)+EE_G  ;
-
-	      YF = 1*phi_y*( alpha*KF+alpha*(1/czcap)*R_KF+(1-alpha)*LF+EE_A ) ;
-	      WF = (sig_c/(1-hab))*(CF-hab*CF(-1)) + sig_l*LF - EE_L ;
-	      LF = R_KF*((1+czcap)/czcap)-WF+KF ;
-          EF = EF(-1)+EF(1)-EF+(LF-EF)*((1-xi_e)*(1-xi_e*beta)/(xi_e));
-         
-	      C = (hab/(1+hab))*C(-1)+(1/(1+hab))*C(1)-((1-hab)/((1+hab)*sig_c))*(R-PIE(1)-EE_B) ;
-	      I = (1/(1+beta))* ((  I(-1) + beta*(I(1)))+(1/phi_i)*Q )+1*ETA_Q+1*EE_I ;
-	      Q = -(R-PIE(1))+(1-beta*(1-tau))*((0+czcap)/czcap)*R_K(1)+beta*(1-tau)*Q(1) +EE_I*0+0*ETA_Q ;
-	      K =  (1-tau)*K(-1)+tau*I(-1) ;
-	      Y = (ccs*C+cinvs*I)+ EE_G   ;
-	      Y = phi_y*( alpha*K+alpha*(1/czcap)*R_K+(1-alpha)*L ) +phi_y*EE_A  ;
-	      PIE = (1/(1+beta*gamma_p))*
-	            ( 
-	            (beta)*(PIE(1)) +(gamma_p)*(PIE(-1)) 
-	            +((1-xi_p)*(1-beta*xi_p)/(xi_p))*(MC)
-	            )  + ETA_P ; 
-	            
-	      MC = alpha*R_K+(1-alpha)*W -EE_A;
-	      W =  (1/(1+beta))*(beta*W(+1)+W(-1))
-                +(beta/(1+beta))*(PIE(+1))
-                -((1+beta*gamma_w)/(1+beta))*(PIE)
-                +(gamma_w/(1+beta))*(PIE(-1))
-                -(1/(1+beta))*(((1-beta*xi_w)*(1-xi_w))/(((1+(((1+lambda_w)*sig_l)/(lambda_w))))*xi_w))*(W-sig_l*L-(sig_c/(1-hab))*(C-hab*C(-1))+EE_L)
-                +ETA_W;
-	      L = R_K*((1+czcap)/czcap)-W+K ;
-
-//	      R = r_dpi*(PIE-PIE(-1))
-//              +(1-rho)*(r_pie*(PIE(-1)-PIE_BAR)+r_y*(Y-YF))
-//              +r_dy*(Y-YF-(Y(-1)-YF(-1)))
-//              +rho*(R(-1)-PIE_BAR)
-//              +PIE_BAR
-//              +ETA_R;
-
-
-	      R = 
-
-r_dpi*(PIE-PIE(-1))
-
-              +(1-rho)*(r_pie*(BIGTHETA)+r_y*(Y-YF))
-              +r_dy*(Y-YF-(Y(-1)-YF(-1)))
-              +rho*(R(-1)-PIE_BAR)
-              +PIE_BAR
-              +ETA_R;
-
-
-          E = E(-1)+E(1)-E+(L-E)*((1-xi_e)*(1-xi_e*beta)/(xi_e));
-          
-          
-          EE_A = (rho_a)*EE_A(-1)  + E_A;
-	      PIE_BAR = rho_pb*PIE_BAR(-1)+ E_PIE_BAR ;
-	      EE_B = rho_b*EE_B(-1) + E_B ;
-	      EE_G = rho_g*EE_G(-1) + E_G ;
-	      EE_L = rho_l*EE_L(-1) + E_L ;
-	      EE_I = rho_i*EE_I(-1) + E_I ;
-	      one = 0*one(-1) ;
-
-		LMP*BIGTHETA(1) = BIGTHETA - (PIE(-1) - PIE_BAR) ; 
-
-end; 
-
- 
-shocks;
-var E_A; stderr 0.598;
-var E_B; stderr 0.336;
-var E_G; stderr 0.325;
-var E_I; stderr 0.085;
-var E_L; stderr 3.520;
-var ETA_P; stderr 0.160;
-var ETA_W; stderr 0.289;
-var ETA_R; stderr 0.081;
-var ETA_Q; stderr 0.604;
-var E_PIE_BAR; stderr 0.017;
-end;
-
-//stoch_simul(irf=20) Y C PIE R W R_K L Q I K ;
-
-// stoch_simul generates what kind of standard errors for the shocks ?
-
-//steady;
-//check;
-//stoch_simul(periods=200,irf=20,simul_seed=3) Y C PIE MC R W R_K E L I ;
-
-//datatomfile('ddd',[]);
-
-// new syntax 
-
-estimated_params;
-// PARAM NAME, INITVAL, LB, UB, PRIOR_SHAPE, PRIOR_P1, PRIOR_P2, PRIOR_P3, PRIOR_P4, JSCALE
-// PRIOR_SHAPE: BETA_PDF, GAMMA_PDF, NORMAL_PDF, INV_GAMMA_PDF
-stderr E_A,0.543,0.01,4,INV_GAMMA_PDF,0.4,2;
-stderr E_PIE_BAR,0.072,0.001,4,INV_GAMMA_PDF,0.02,10;
-stderr E_B,0.2694,0.01,4,INV_GAMMA_PDF,0.2,2;
-stderr E_G,0.3052,0.01,4,INV_GAMMA_PDF,0.3,2;
-stderr E_L,1.4575,0.1,6,INV_GAMMA_PDF,1,2;
-stderr E_I,0.1318,0.01,4,INV_GAMMA_PDF,0.1,2;
-stderr ETA_R,0.1363,0.01,4,INV_GAMMA_PDF,0.1,2;
-stderr ETA_Q,0.4842,0.01,4,INV_GAMMA_PDF,0.4,2;
-stderr ETA_P,0.1731,0.01,4,INV_GAMMA_PDF,0.15,2;
-stderr ETA_W,0.2462,0.1,4,INV_GAMMA_PDF,0.25,2;
-rho_a,.9722,.1,.9999,BETA_PDF,0.85,0.1;
-rho_pb,.85,.1,.999,BETA_PDF,0.85,0.1;
-rho_b,.7647,.1,.99,BETA_PDF,0.85,0.1;
-rho_g,.9502,.1,.9999,BETA_PDF,0.85,0.1;
-rho_l,.9542,.1,.9999,BETA_PDF,0.85,0.1;
-rho_i,.6705,.1,.99,BETA_PDF,0.85,0.1;
-phi_i,5.2083,1,15,NORMAL_PDF,4,1.5;
-sig_c,0.9817,0.25,3,NORMAL_PDF,1,0.375;
-hab,0.5612,0.3,0.95,BETA_PDF,0.7,0.1;
-xi_w,0.7661,0.3,0.9,BETA_PDF,0.75,0.05;
-sig_l,1.7526,0.5,5,NORMAL_PDF,2,0.75;
-xi_p,0.8684,0.3,0.95,BETA_PDF,0.75,0.05;
-xi_e,0.5724,0.1,0.95,BETA_PDF,0.5,0.15;
-gamma_w,0.6202,0.1,0.99,BETA_PDF,0.75,0.15;
-gamma_p,0.6638,0.1,0.99,BETA_PDF,0.75,0.15;
-czcap,0.2516,0.01,2,NORMAL_PDF,0.2,0.075;
-phi_y,1.3011,1.001,2,NORMAL_PDF,1.45,0.125;
-r_pie,1.4616,1.2,2,NORMAL_PDF,1.7,0.1;
-r_dpi,0.1144,0.01,0.5,NORMAL_PDF,0.3,0.1;
-rho,0.8865,0.5,0.99,BETA_PDF,0.8,0.10;
-r_y,0.0571,0.01,0.2,NORMAL_PDF,0.125,0.05;
-r_dy,0.2228,0.05,0.5,NORMAL_PDF,0.0625,0.05;
-end;
-
-varobs Y C I E PIE W R;
-
-//estimation(datafile=rawdata_euromodel_1,presample=40, first_obs=1, nobs=118, lik_init=2, mode_compute=1,mh_replic=0);
-estimation(datafile=rawdata_euromodel_1,presample=40, first_obs=1, nobs=118,mh_jscale=0.2,mh_replic=1000
-//,mode_compute=0,mode_file=sweuromodel_dll_mode
-);
-
-
-//stoch_simul(periods=200,irf=20,simul_seed=3) Y C PIE R W R_K L Q I K ;
-
+//options_.usePartInfo=1;
+
+var MC E EF R_KF QF CF IF YF LF PIEF WF RF R_K Q C I Y L PIE W R EE_A PIE_BAR EE_B EE_G EE_L EE_I KF K one BIGTHETA;    
+
+varexo E_A E_B E_G E_L E_I ETA_R E_PIE_BAR ETA_Q ETA_P ETA_W  ;  
+ 
+parameters 
+xi_e lambda_w alpha czcap beta phi_i tau sig_c hab ccs cinvs phi_y gamma_w xi_w gamma_p xi_p sig_l r_dpi 
+r_pie r_dy r_y rho rho_a rho_pb rho_b rho_g rho_l rho_i LMP  ;
+
+
+
+alpha=.30;
+beta=.99;
+tau=0.025;
+ccs=0.6;
+cinvs=.22;  //% alpha*(tau+ctrend)/R_K   R_K=ctrend/beta-1+tau  
+lambda_w = 0.5;
+phi_i= 6.771;
+sig_c=   1.353; 
+hab=    0.573;    
+xi_w=   0.737;
+sig_l=    2.400;
+xi_p=   0.908;
+xi_e= 0.599;
+gamma_w=    0.763;
+gamma_p=    0.469;
+czcap=    0.169;
+phi_y=    1.408;
+r_pie=     1.684;
+r_dpi=    0.14;
+rho=      0.961;
+r_y=      0.099;
+r_dy=     0.159;
+rho_a=    0.823;
+rho_b=    0.855;
+rho_g=    0.949;
+rho_l=   0.889;
+rho_i=   0.927;
+rho_pb=  0.924;
+LMP = 0.0 ; //NEW.
+
+model(linear, use_dll); 
+          CF = (1/(1+hab))*(CF(1)+hab*CF(-1))-((1-hab)/((1+hab)*sig_c))*(RF-PIEF(1)-EE_B) ;
+	      0 =  alpha*R_KF+(1-alpha)*WF -EE_A ;
+          PIEF = 0*one;
+	      IF = (1/(1+beta))* ((  IF(-1) + beta*(IF(1)))+(1/phi_i)*QF)+0*ETA_Q+EE_I ;
+	      QF = -(RF-PIEF(1))+(1-beta*(1-tau))*((0+czcap)/czcap)*R_KF(1)+beta*(1-tau)*QF(1) +0*EE_I ;
+          KF =  (1-tau)*KF(-1)+tau*IF(-1) ;
+	      YF = (ccs*CF+cinvs*IF)+EE_G  ;
+
+	      YF = 1*phi_y*( alpha*KF+alpha*(1/czcap)*R_KF+(1-alpha)*LF+EE_A ) ;
+	      WF = (sig_c/(1-hab))*(CF-hab*CF(-1)) + sig_l*LF - EE_L ;
+	      LF = R_KF*((1+czcap)/czcap)-WF+KF ;
+          EF = EF(-1)+EF(1)-EF+(LF-EF)*((1-xi_e)*(1-xi_e*beta)/(xi_e));
+         
+	      C = (hab/(1+hab))*C(-1)+(1/(1+hab))*C(1)-((1-hab)/((1+hab)*sig_c))*(R-PIE(1)-EE_B) ;
+	      I = (1/(1+beta))* ((  I(-1) + beta*(I(1)))+(1/phi_i)*Q )+1*ETA_Q+1*EE_I ;
+	      Q = -(R-PIE(1))+(1-beta*(1-tau))*((0+czcap)/czcap)*R_K(1)+beta*(1-tau)*Q(1) +EE_I*0+0*ETA_Q ;
+	      K =  (1-tau)*K(-1)+tau*I(-1) ;
+	      Y = (ccs*C+cinvs*I)+ EE_G   ;
+	      Y = phi_y*( alpha*K+alpha*(1/czcap)*R_K+(1-alpha)*L ) +phi_y*EE_A  ;
+	      PIE = (1/(1+beta*gamma_p))*
+	            ( 
+	            (beta)*(PIE(1)) +(gamma_p)*(PIE(-1)) 
+	            +((1-xi_p)*(1-beta*xi_p)/(xi_p))*(MC)
+	            )  + ETA_P ; 
+	            
+	      MC = alpha*R_K+(1-alpha)*W -EE_A;
+	      W =  (1/(1+beta))*(beta*W(+1)+W(-1))
+                +(beta/(1+beta))*(PIE(+1))
+                -((1+beta*gamma_w)/(1+beta))*(PIE)
+                +(gamma_w/(1+beta))*(PIE(-1))
+                -(1/(1+beta))*(((1-beta*xi_w)*(1-xi_w))/(((1+(((1+lambda_w)*sig_l)/(lambda_w))))*xi_w))*(W-sig_l*L-(sig_c/(1-hab))*(C-hab*C(-1))+EE_L)
+                +ETA_W;
+	      L = R_K*((1+czcap)/czcap)-W+K ;
+
+//	      R = r_dpi*(PIE-PIE(-1))
+//              +(1-rho)*(r_pie*(PIE(-1)-PIE_BAR)+r_y*(Y-YF))
+//              +r_dy*(Y-YF-(Y(-1)-YF(-1)))
+//              +rho*(R(-1)-PIE_BAR)
+//              +PIE_BAR
+//              +ETA_R;
+
+
+	      R = 
+
+r_dpi*(PIE-PIE(-1))
+
+              +(1-rho)*(r_pie*(BIGTHETA)+r_y*(Y-YF))
+              +r_dy*(Y-YF-(Y(-1)-YF(-1)))
+              +rho*(R(-1)-PIE_BAR)
+              +PIE_BAR
+              +ETA_R;
+
+
+          E = E(-1)+E(1)-E+(L-E)*((1-xi_e)*(1-xi_e*beta)/(xi_e));
+          
+          
+          EE_A = (rho_a)*EE_A(-1)  + E_A;
+	      PIE_BAR = rho_pb*PIE_BAR(-1)+ E_PIE_BAR ;
+	      EE_B = rho_b*EE_B(-1) + E_B ;
+	      EE_G = rho_g*EE_G(-1) + E_G ;
+	      EE_L = rho_l*EE_L(-1) + E_L ;
+	      EE_I = rho_i*EE_I(-1) + E_I ;
+	      one = 0*one(-1) ;
+
+		LMP*BIGTHETA(1) = BIGTHETA - (PIE(-1) - PIE_BAR) ; 
+
+end; 
+
+ 
+shocks;
+var E_A; stderr 0.598;
+var E_B; stderr 0.336;
+var E_G; stderr 0.325;
+var E_I; stderr 0.085;
+var E_L; stderr 3.520;
+var ETA_P; stderr 0.160;
+var ETA_W; stderr 0.289;
+var ETA_R; stderr 0.081;
+var ETA_Q; stderr 0.604;
+var E_PIE_BAR; stderr 0.017;
+end;
+
+//stoch_simul(irf=20) Y C PIE R W R_K L Q I K ;
+
+// stoch_simul generates what kind of standard errors for the shocks ?
+
+//steady;
+//check;
+//stoch_simul(periods=200,irf=20,simul_seed=3) Y C PIE MC R W R_K E L I ;
+
+//datatomfile('ddd',[]);
+
+// new syntax 
+
+estimated_params;
+// PARAM NAME, INITVAL, LB, UB, PRIOR_SHAPE, PRIOR_P1, PRIOR_P2, PRIOR_P3, PRIOR_P4, JSCALE
+// PRIOR_SHAPE: BETA_PDF, GAMMA_PDF, NORMAL_PDF, INV_GAMMA_PDF
+stderr E_A,0.543,0.01,4,INV_GAMMA_PDF,0.4,2;
+stderr E_PIE_BAR,0.072,0.001,4,INV_GAMMA_PDF,0.02,10;
+stderr E_B,0.2694,0.01,4,INV_GAMMA_PDF,0.2,2;
+stderr E_G,0.3052,0.01,4,INV_GAMMA_PDF,0.3,2;
+stderr E_L,1.4575,0.1,6,INV_GAMMA_PDF,1,2;
+stderr E_I,0.1318,0.01,4,INV_GAMMA_PDF,0.1,2;
+stderr ETA_R,0.1363,0.01,4,INV_GAMMA_PDF,0.1,2;
+stderr ETA_Q,0.4842,0.01,4,INV_GAMMA_PDF,0.4,2;
+stderr ETA_P,0.1731,0.01,4,INV_GAMMA_PDF,0.15,2;
+stderr ETA_W,0.2462,0.1,4,INV_GAMMA_PDF,0.25,2;
+rho_a,.9722,.1,.9999,BETA_PDF,0.85,0.1;
+rho_pb,.85,.1,.999,BETA_PDF,0.85,0.1;
+rho_b,.7647,.1,.99,BETA_PDF,0.85,0.1;
+rho_g,.9502,.1,.9999,BETA_PDF,0.85,0.1;
+rho_l,.9542,.1,.9999,BETA_PDF,0.85,0.1;
+rho_i,.6705,.1,.99,BETA_PDF,0.85,0.1;
+phi_i,5.2083,1,15,NORMAL_PDF,4,1.5;
+sig_c,0.9817,0.25,3,NORMAL_PDF,1,0.375;
+hab,0.5612,0.3,0.95,BETA_PDF,0.7,0.1;
+xi_w,0.7661,0.3,0.9,BETA_PDF,0.75,0.05;
+sig_l,1.7526,0.5,5,NORMAL_PDF,2,0.75;
+xi_p,0.8684,0.3,0.95,BETA_PDF,0.75,0.05;
+xi_e,0.5724,0.1,0.95,BETA_PDF,0.5,0.15;
+gamma_w,0.6202,0.1,0.99,BETA_PDF,0.75,0.15;
+gamma_p,0.6638,0.1,0.99,BETA_PDF,0.75,0.15;
+czcap,0.2516,0.01,2,NORMAL_PDF,0.2,0.075;
+phi_y,1.3011,1.001,2,NORMAL_PDF,1.45,0.125;
+r_pie,1.4616,1.2,2,NORMAL_PDF,1.7,0.1;
+r_dpi,0.1144,0.01,0.5,NORMAL_PDF,0.3,0.1;
+rho,0.8865,0.5,0.99,BETA_PDF,0.8,0.10;
+r_y,0.0571,0.01,0.2,NORMAL_PDF,0.125,0.05;
+r_dy,0.2228,0.05,0.5,NORMAL_PDF,0.0625,0.05;
+end;
+
+varobs Y C I E PIE W R;
+
+//estimation(datafile=rawdata_euromodel_1,presample=40, first_obs=1, nobs=118, lik_init=2, mode_compute=1,mh_replic=0);
+estimation(datafile=rawdata_euromodel_1,presample=40, first_obs=1, nobs=118,mh_jscale=0.2,mh_replic=1000
+//,mode_compute=0,mode_file=sweuromodel_dll_mode
+);
+
+
+//stoch_simul(periods=200,irf=20,simul_seed=3) Y C PIE R W R_K L Q I K ;
+
diff --git a/mex/sources/estimation/tests/rawdata_euromodel_1.m b/mex/sources/estimation/tests/rawdata_euromodel_1.m
index cde44abc9432e8fd593f938d741b9cac45f9a24d..25bbc92414efddc7adf66d5ab4cc8545af1e71f7 100644
--- a/mex/sources/estimation/tests/rawdata_euromodel_1.m
+++ b/mex/sources/estimation/tests/rawdata_euromodel_1.m
@@ -1,967 +1,967 @@
-C =[
-   -7.4073
-   -6.1860
-   -6.5983
-   -5.6088
-   -5.0547
-   -4.4774
-   -3.8081
-   -3.8425
-   -2.4178
-   -1.9835
-   -1.0395
-   -0.1583
-   -0.0397
-    0.3505
-   -0.1879
-   -0.0067
-    0.0478
-   -1.2247
-   -1.4349
-   -0.7973
-   -0.0461
-    0.5844
-    1.1372
-    1.3801
-    1.8023
-    2.2972
-    2.0469
-    2.5435
-    2.8169
-    3.2007
-    2.6705
-    3.0518
-    3.2445
-    3.8443
-    3.8525
-    4.9494
-    4.2770
-    4.9532
-    5.1441
-    3.7124
-    3.9880
-    3.6926
-    2.6005
-    1.8679
-    1.9085
-    1.5563
-    1.2308
-    0.3264
-   -0.2208
-   -0.2483
-   -0.4082
-   -1.0315
-   -1.6030
-   -1.5499
-   -1.3777
-   -2.1675
-   -2.5138
-   -2.8820
-   -2.6958
-   -2.4719
-   -1.9854
-   -1.7954
-   -2.2362
-   -1.0595
-   -0.8808
-   -0.8548
-   -1.2839
-   -0.1363
-    0.2104
-    0.8810
-    0.3555
-    0.4766
-    1.3269
-    1.4506
-    1.4308
-    1.6263
-    1.9842
-    2.3948
-    2.8710
-    3.0177
-    2.9305
-    3.1739
-    3.7380
-    3.8285
-    3.3342
-    3.7447
-    3.7830
-    3.1039
-    2.8413
-    3.0338
-    0.3669
-    0.0847
-    0.0104
-    0.2115
-   -0.6649
-   -0.9625
-   -0.7330
-   -0.8664
-   -1.4441
-   -1.0179
-   -1.2729
-   -1.9539
-   -1.4427
-   -2.0371
-   -1.9764
-   -2.5654
-   -2.8570
-   -2.5842
-   -3.0427
-   -2.8312
-   -2.3320
-   -2.2768
-   -2.1816
-   -2.1043
-   -1.8969
-   -2.2388
-   -2.1679
-   -2.1172
-];
-
-E =[
-    0.6263
-    0.7368
-    0.7477
-    1.0150
-    0.6934
-    0.4135
-    0.3845
-    0.2380
-    0.2853
-    0.5999
-    0.8622
-    1.2116
-    1.4921
-    1.5816
-    1.7259
-    1.6276
-    1.2422
-    0.8084
-    0.4710
-   -0.3704
-   -0.6427
-   -0.5323
-   -0.5562
-   -0.3651
-   -0.4356
-   -0.7164
-   -0.5816
-   -0.4635
-   -0.8456
-   -0.9708
-   -0.7138
-   -0.7499
-   -0.6941
-   -0.6656
-   -0.2912
-   -0.1650
-    0.0774
-    0.2307
-    0.4484
-    0.4942
-    0.4653
-    0.2196
-    0.1736
-   -0.1595
-   -0.3918
-   -0.4611
-   -0.8493
-   -0.7384
-   -1.0604
-   -1.2166
-   -1.7187
-   -1.6932
-   -1.7830
-   -1.7035
-   -2.2079
-   -2.3769
-   -2.2511
-   -2.1093
-   -2.4638
-   -2.4027
-   -2.1313
-   -1.9199
-   -1.7941
-   -1.4661
-   -1.2269
-   -1.0392
-   -1.0725
-   -0.7156
-   -0.4778
-   -0.4233
-   -0.0409
-    0.1620
-    0.4280
-    0.5873
-    1.0323
-    1.3420
-    1.6902
-    2.0680
-    2.8219
-    3.2511
-    3.2930
-    3.5633
-    3.8992
-    3.6874
-    3.2849
-    3.1614
-    2.6221
-    2.5067
-    1.9223
-    1.1777
-    0.4483
-   -0.0661
-   -0.4424
-   -0.9000
-   -1.1478
-   -1.2047
-   -1.1412
-   -1.2383
-   -1.1048
-   -0.9716
-   -0.9287
-   -1.0057
-   -1.0827
-   -1.0200
-   -1.0072
-   -1.1740
-   -1.2809
-   -1.1086
-   -0.9866
-   -0.8947
-   -0.5875
-   -0.2329
-    0.1493
-    0.4906
-    0.8400
-    1.0720
-    1.2648
-    1.5431
-];
-
-I =[
-    2.6617
-    2.4325
-    1.9592
-    3.2530
-    2.9949
-    3.7918
-    4.7444
-    4.8289
-    5.5983
-    7.8923
-    9.4297
-    9.5010
-   10.0150
-   10.0413
-    9.6046
-    6.4766
-    5.9647
-    3.0114
-    0.5683
-   -2.1226
-   -2.1855
-   -0.8329
-   -1.5207
-   -1.3419
-   -1.7897
-   -0.1476
-    0.4675
-   -1.6516
-   -1.5419
-   -1.3050
-   -1.2451
-   -0.7815
-   -0.7796
-   -0.3612
-   -2.4072
-    1.1162
-    1.1383
-    3.4132
-    5.0356
-    2.8016
-    2.1734
-    0.9366
-   -0.7050
-   -1.5021
-   -2.9868
-   -6.0237
-   -6.2589
-   -6.9138
-   -8.2340
-   -9.2589
-   -9.2465
-   -9.6988
-   -9.7782
-  -10.5645
-  -10.7544
-  -13.1583
-  -12.2718
-  -12.0131
-  -13.5983
-  -12.3579
-  -10.9146
-  -11.1572
-  -12.4935
-   -9.4393
-   -8.5535
-   -7.3723
-  -10.0169
-   -6.6088
-   -5.2045
-   -4.1024
-   -2.8472
-   -1.3139
-    0.0477
-    1.5629
-    3.6947
-    4.0327
-    4.1320
-    7.1400
-    9.1036
-    8.5609
-    7.6576
-    8.8022
-    8.9611
-   10.0871
-    9.4797
-    9.3964
-   10.0363
-    8.6340
-    6.6522
-    4.4471
-    0.2854
-   -2.1879
-   -2.9879
-   -4.1021
-   -2.7713
-   -2.2281
-   -1.2908
-   -0.3250
-    0.6534
-    0.3942
-    0.3534
-   -0.1532
-   -1.7936
-    0.4909
-    0.3634
-    0.4290
-   -0.9709
-    0.1942
-    0.6103
-    1.4426
-    2.7225
-    1.7525
-    3.2780
-    3.5985
-    4.9011
-    5.3312
-    6.4402
-    6.6529
-];
-
-L =[
-    0.6263
-    0.7368
-    0.7477
-    1.0150
-    0.6934
-    0.4135
-    0.3845
-    0.2380
-    0.2853
-    0.5999
-    0.8622
-    1.2116
-    1.4921
-    1.5816
-    1.7259
-    1.6276
-    1.2422
-    0.8084
-    0.4710
-   -0.3704
-   -0.6427
-   -0.5323
-   -0.5562
-   -0.3651
-   -0.4356
-   -0.7164
-   -0.5816
-   -0.4635
-   -0.8456
-   -0.9708
-   -0.7138
-   -0.7499
-   -0.6941
-   -0.6656
-   -0.2912
-   -0.1650
-    0.0774
-    0.2307
-    0.4484
-    0.4942
-    0.4653
-    0.2196
-    0.1736
-   -0.1595
-   -0.3918
-   -0.4611
-   -0.8493
-   -0.7384
-   -1.0604
-   -1.2166
-   -1.7187
-   -1.6932
-   -1.7830
-   -1.7035
-   -2.2079
-   -2.3769
-   -2.2511
-   -2.1093
-   -2.4638
-   -2.4027
-   -2.1313
-   -1.9199
-   -1.7941
-   -1.4661
-   -1.2269
-   -1.0392
-   -1.0725
-   -0.7156
-   -0.4778
-   -0.4233
-   -0.0409
-    0.1620
-    0.4280
-    0.5873
-    1.0323
-    1.3420
-    1.6902
-    2.0680
-    2.8219
-    3.2511
-    3.2930
-    3.5633
-    3.8992
-    3.6874
-    3.2849
-    3.1614
-    2.6221
-    2.5067
-    1.9223
-    1.1777
-    0.4483
-   -0.0661
-   -0.4424
-   -0.9000
-   -1.1478
-   -1.2047
-   -1.1412
-   -1.2383
-   -1.1048
-   -0.9716
-   -0.9287
-   -1.0057
-   -1.0827
-   -1.0200
-   -1.0072
-   -1.1740
-   -1.2809
-   -1.1086
-   -0.9866
-   -0.8947
-   -0.5875
-   -0.2329
-    0.1493
-    0.4906
-    0.8400
-    1.0720
-    1.2648
-    1.5431
-];
-
-PIE =[
-   -1.0113
-   -0.8305
-    0.2332
-   -0.8746
-   -0.7978
-   -0.9220
-   -0.2487
-   -0.7749
-   -0.5460
-   -0.5347
-    0.5050
-   -0.0334
-    0.6756
-    0.8791
-    0.7267
-    1.0997
-    1.1750
-    1.1927
-    0.4420
-    0.5357
-    0.0345
-    0.0196
-    0.3371
-    0.9379
-    1.2160
-    0.3393
-    0.5813
-    0.7410
-    0.3374
-    0.2616
-    0.4025
-    0.4799
-    0.5981
-   -0.1523
-    0.4458
-    0.2182
-    0.9793
-    0.7562
-    1.0064
-    0.8203
-    0.6966
-    0.3352
-    0.6581
-    0.6111
-    0.9833
-    1.1991
-    0.9562
-    0.3868
-    0.2939
-    0.2471
-    0.8331
-    0.0715
-    0.3910
-    0.3301
-    0.2547
-   -0.2702
-   -0.2998
-   -0.1953
-   -0.2293
-   -0.3284
-    0.0480
-   -0.0374
-    0.3253
-   -0.3434
-   -0.3892
-   -0.7178
-   -0.4758
-   -0.6794
-   -0.8505
-   -0.3512
-   -0.4436
-   -0.5101
-   -0.4574
-   -0.2696
-   -0.1047
-   -0.5745
-   -0.2989
-   -0.0063
-    0.0088
-   -0.1184
-   -0.1506
-   -0.4073
-    0.2674
-    0.2896
-    0.0669
-    0.1166
-   -0.1699
-   -0.2518
-   -0.0562
-   -0.3269
-   -0.0703
-   -0.1046
-   -0.4888
-   -0.3524
-   -0.2485
-   -0.5870
-   -0.4546
-   -0.3970
-   -0.2353
-   -0.0352
-   -0.2171
-   -0.3754
-   -0.4322
-   -0.4572
-   -0.4903
-   -0.4518
-   -0.6435
-   -0.6304
-   -0.4148
-   -0.2892
-   -0.4318
-   -0.6010
-   -0.4148
-   -0.4315
-   -0.3531
-   -0.8053
-   -0.4680
-   -0.4263
-];
-
-R =[
-   -1.0750
-   -1.1540
-   -1.3682
-   -1.4569
-   -1.3490
-   -1.4011
-   -1.6486
-   -1.6968
-   -1.6976
-   -1.2567
-   -1.1392
-   -0.7783
-   -0.3021
-   -0.0435
-    0.0066
-   -0.0043
-    0.1029
-   -0.0628
-   -0.5358
-   -0.9627
-   -1.1079
-   -1.0918
-   -0.9966
-   -0.6223
-   -0.3616
-   -0.2711
-   -0.0997
-   -0.2810
-   -0.3710
-   -0.3167
-   -0.5301
-   -0.5826
-   -0.3194
-   -0.2713
-   -0.5287
-   -0.2432
-    0.1098
-    0.5349
-    0.7094
-    0.8415
-    0.6226
-    0.7376
-    0.9316
-    1.4370
-    1.5853
-    1.4267
-    1.1783
-    1.2046
-    0.9689
-    0.7918
-    0.6315
-    0.5950
-    0.6853
-    0.7171
-    0.5887
-    0.4873
-    0.4027
-    0.3489
-    0.2934
-    0.3060
-    0.1741
-    0.0348
-    0.0771
-   -0.1005
-   -0.1518
-   -0.1104
-   -0.0681
-   -0.0059
-    0.0256
-    0.0404
-   -0.1721
-   -0.2002
-    0.0015
-    0.1249
-    0.3738
-    0.4320
-    0.5579
-    0.8186
-    0.8727
-    0.7356
-    0.7243
-    0.8635
-    0.9058
-    0.7656
-    0.7936
-    0.8631
-    0.9074
-    0.9547
-    1.2045
-    1.0850
-    0.9178
-    0.5242
-    0.3178
-    0.1472
-    0.0227
-   -0.0799
-   -0.0611
-   -0.0140
-    0.1132
-    0.1774
-    0.0782
-    0.0436
-   -0.1596
-   -0.2691
-   -0.2895
-   -0.3791
-   -0.4020
-   -0.4166
-   -0.4037
-   -0.3636
-   -0.4075
-   -0.4311
-   -0.4470
-   -0.5111
-   -0.6274
-   -0.7261
-   -0.6974
-   -0.5012
-];
-
-W =[
-  -14.8791
-  -13.2300
-  -13.5037
-  -13.0249
-  -11.2546
-  -10.0148
-   -8.8586
-   -8.5739
-   -7.7851
-   -6.7136
-   -5.5878
-   -4.6881
-   -3.8039
-   -3.0366
-   -2.7342
-   -1.3135
-   -0.7387
-   -0.1131
-   -0.2769
-    0.8696
-    1.8855
-    2.3667
-    2.4942
-    3.2049
-    3.9682
-    5.1500
-    4.7047
-    4.7827
-    5.3377
-    5.6614
-    5.2813
-    5.2967
-    5.5175
-    6.1526
-    5.6627
-    6.0694
-    6.5824
-    6.9032
-    6.7849
-    6.6896
-    6.6201
-    6.9933
-    5.8959
-    6.7419
-    6.9999
-    6.4009
-    5.5083
-    5.1054
-    5.2813
-    4.5790
-    3.9589
-    3.8599
-    3.8978
-    2.7957
-    3.2480
-    1.4634
-    1.9219
-    1.8398
-    1.9279
-    1.8316
-    1.6092
-    1.2741
-    0.2031
-   -0.0236
-   -0.1004
-   -0.3034
-   -1.0273
-   -0.2205
-    0.0458
-    0.2386
-   -0.0977
-   -0.3145
-   -0.1416
-   -0.7009
-   -0.9082
-   -0.8802
-   -0.5644
-   -0.5852
-   -0.5346
-    0.0652
-    0.1301
-    0.3444
-   -0.3592
-    0.8096
-    0.9644
-    1.0289
-    1.2781
-    1.2298
-    2.2134
-    2.0808
-    0.4925
-    0.6506
-    0.5531
-    0.2456
-   -0.5351
-   -0.8183
-   -0.8967
-   -0.7268
-   -1.0738
-   -1.2844
-   -1.4338
-   -1.6995
-   -1.7085
-   -2.2889
-   -2.1018
-   -2.4273
-   -2.4609
-   -2.1407
-   -2.3847
-   -3.1689
-   -4.5581
-   -4.1027
-   -4.2436
-   -4.8836
-   -5.9660
-   -4.9971
-   -5.2386
-   -5.6618
-];
-
-Y =[
-   -4.9347
-   -4.6205
-   -5.2198
-   -4.5937
-   -3.8015
-   -3.6643
-   -2.7239
-   -2.7524
-   -2.0634
-   -1.0112
-    0.0530
-    0.7623
-    1.7927
-    2.1486
-    2.4866
-    2.1456
-    2.1671
-   -0.0254
-   -1.6716
-   -1.9673
-   -1.6109
-   -1.0292
-   -0.1222
-    0.7329
-    1.1234
-    2.0603
-    1.7998
-    1.4820
-    1.1732
-    1.6424
-    1.5382
-    2.1399
-    2.0127
-    2.7210
-    2.4966
-    3.5249
-    3.6237
-    4.2011
-    4.5634
-    3.3442
-    2.7761
-    1.9812
-    1.3779
-    1.4616
-    1.3029
-    0.7594
-    0.3695
-    0.0832
-   -0.8118
-   -1.4557
-   -1.4850
-   -1.2346
-   -1.5696
-   -1.3785
-   -0.7682
-   -2.0308
-   -1.7778
-   -1.7801
-   -2.1711
-   -1.7469
-   -1.3413
-   -1.3352
-   -2.4390
-   -1.2125
-   -1.1695
-   -1.0891
-   -2.4753
-   -1.3503
-   -0.9412
-   -0.1470
-    0.0026
-    0.1108
-    0.6890
-    1.3520
-    1.6018
-    2.0667
-    1.7625
-    2.6658
-    3.4048
-    3.2507
-    3.4251
-    3.2174
-    3.1903
-    3.3396
-    3.1358
-    2.8625
-    3.3546
-    2.4609
-    1.9534
-    0.9962
-   -0.7904
-   -1.1672
-   -1.2586
-   -1.3593
-   -1.3443
-   -0.9413
-   -0.6023
-   -0.4516
-   -0.5129
-   -0.8741
-   -1.0784
-   -1.4091
-   -1.3627
-   -1.5731
-   -1.6037
-   -1.8814
-   -2.1482
-   -1.3597
-   -1.1855
-   -1.1122
-   -0.8424
-   -0.9747
-   -1.1385
-   -1.4548
-   -1.4284
-   -1.4633
-   -1.0621
-   -0.7871
-];
+C =[
+   -7.4073
+   -6.1860
+   -6.5983
+   -5.6088
+   -5.0547
+   -4.4774
+   -3.8081
+   -3.8425
+   -2.4178
+   -1.9835
+   -1.0395
+   -0.1583
+   -0.0397
+    0.3505
+   -0.1879
+   -0.0067
+    0.0478
+   -1.2247
+   -1.4349
+   -0.7973
+   -0.0461
+    0.5844
+    1.1372
+    1.3801
+    1.8023
+    2.2972
+    2.0469
+    2.5435
+    2.8169
+    3.2007
+    2.6705
+    3.0518
+    3.2445
+    3.8443
+    3.8525
+    4.9494
+    4.2770
+    4.9532
+    5.1441
+    3.7124
+    3.9880
+    3.6926
+    2.6005
+    1.8679
+    1.9085
+    1.5563
+    1.2308
+    0.3264
+   -0.2208
+   -0.2483
+   -0.4082
+   -1.0315
+   -1.6030
+   -1.5499
+   -1.3777
+   -2.1675
+   -2.5138
+   -2.8820
+   -2.6958
+   -2.4719
+   -1.9854
+   -1.7954
+   -2.2362
+   -1.0595
+   -0.8808
+   -0.8548
+   -1.2839
+   -0.1363
+    0.2104
+    0.8810
+    0.3555
+    0.4766
+    1.3269
+    1.4506
+    1.4308
+    1.6263
+    1.9842
+    2.3948
+    2.8710
+    3.0177
+    2.9305
+    3.1739
+    3.7380
+    3.8285
+    3.3342
+    3.7447
+    3.7830
+    3.1039
+    2.8413
+    3.0338
+    0.3669
+    0.0847
+    0.0104
+    0.2115
+   -0.6649
+   -0.9625
+   -0.7330
+   -0.8664
+   -1.4441
+   -1.0179
+   -1.2729
+   -1.9539
+   -1.4427
+   -2.0371
+   -1.9764
+   -2.5654
+   -2.8570
+   -2.5842
+   -3.0427
+   -2.8312
+   -2.3320
+   -2.2768
+   -2.1816
+   -2.1043
+   -1.8969
+   -2.2388
+   -2.1679
+   -2.1172
+];
+
+E =[
+    0.6263
+    0.7368
+    0.7477
+    1.0150
+    0.6934
+    0.4135
+    0.3845
+    0.2380
+    0.2853
+    0.5999
+    0.8622
+    1.2116
+    1.4921
+    1.5816
+    1.7259
+    1.6276
+    1.2422
+    0.8084
+    0.4710
+   -0.3704
+   -0.6427
+   -0.5323
+   -0.5562
+   -0.3651
+   -0.4356
+   -0.7164
+   -0.5816
+   -0.4635
+   -0.8456
+   -0.9708
+   -0.7138
+   -0.7499
+   -0.6941
+   -0.6656
+   -0.2912
+   -0.1650
+    0.0774
+    0.2307
+    0.4484
+    0.4942
+    0.4653
+    0.2196
+    0.1736
+   -0.1595
+   -0.3918
+   -0.4611
+   -0.8493
+   -0.7384
+   -1.0604
+   -1.2166
+   -1.7187
+   -1.6932
+   -1.7830
+   -1.7035
+   -2.2079
+   -2.3769
+   -2.2511
+   -2.1093
+   -2.4638
+   -2.4027
+   -2.1313
+   -1.9199
+   -1.7941
+   -1.4661
+   -1.2269
+   -1.0392
+   -1.0725
+   -0.7156
+   -0.4778
+   -0.4233
+   -0.0409
+    0.1620
+    0.4280
+    0.5873
+    1.0323
+    1.3420
+    1.6902
+    2.0680
+    2.8219
+    3.2511
+    3.2930
+    3.5633
+    3.8992
+    3.6874
+    3.2849
+    3.1614
+    2.6221
+    2.5067
+    1.9223
+    1.1777
+    0.4483
+   -0.0661
+   -0.4424
+   -0.9000
+   -1.1478
+   -1.2047
+   -1.1412
+   -1.2383
+   -1.1048
+   -0.9716
+   -0.9287
+   -1.0057
+   -1.0827
+   -1.0200
+   -1.0072
+   -1.1740
+   -1.2809
+   -1.1086
+   -0.9866
+   -0.8947
+   -0.5875
+   -0.2329
+    0.1493
+    0.4906
+    0.8400
+    1.0720
+    1.2648
+    1.5431
+];
+
+I =[
+    2.6617
+    2.4325
+    1.9592
+    3.2530
+    2.9949
+    3.7918
+    4.7444
+    4.8289
+    5.5983
+    7.8923
+    9.4297
+    9.5010
+   10.0150
+   10.0413
+    9.6046
+    6.4766
+    5.9647
+    3.0114
+    0.5683
+   -2.1226
+   -2.1855
+   -0.8329
+   -1.5207
+   -1.3419
+   -1.7897
+   -0.1476
+    0.4675
+   -1.6516
+   -1.5419
+   -1.3050
+   -1.2451
+   -0.7815
+   -0.7796
+   -0.3612
+   -2.4072
+    1.1162
+    1.1383
+    3.4132
+    5.0356
+    2.8016
+    2.1734
+    0.9366
+   -0.7050
+   -1.5021
+   -2.9868
+   -6.0237
+   -6.2589
+   -6.9138
+   -8.2340
+   -9.2589
+   -9.2465
+   -9.6988
+   -9.7782
+  -10.5645
+  -10.7544
+  -13.1583
+  -12.2718
+  -12.0131
+  -13.5983
+  -12.3579
+  -10.9146
+  -11.1572
+  -12.4935
+   -9.4393
+   -8.5535
+   -7.3723
+  -10.0169
+   -6.6088
+   -5.2045
+   -4.1024
+   -2.8472
+   -1.3139
+    0.0477
+    1.5629
+    3.6947
+    4.0327
+    4.1320
+    7.1400
+    9.1036
+    8.5609
+    7.6576
+    8.8022
+    8.9611
+   10.0871
+    9.4797
+    9.3964
+   10.0363
+    8.6340
+    6.6522
+    4.4471
+    0.2854
+   -2.1879
+   -2.9879
+   -4.1021
+   -2.7713
+   -2.2281
+   -1.2908
+   -0.3250
+    0.6534
+    0.3942
+    0.3534
+   -0.1532
+   -1.7936
+    0.4909
+    0.3634
+    0.4290
+   -0.9709
+    0.1942
+    0.6103
+    1.4426
+    2.7225
+    1.7525
+    3.2780
+    3.5985
+    4.9011
+    5.3312
+    6.4402
+    6.6529
+];
+
+L =[
+    0.6263
+    0.7368
+    0.7477
+    1.0150
+    0.6934
+    0.4135
+    0.3845
+    0.2380
+    0.2853
+    0.5999
+    0.8622
+    1.2116
+    1.4921
+    1.5816
+    1.7259
+    1.6276
+    1.2422
+    0.8084
+    0.4710
+   -0.3704
+   -0.6427
+   -0.5323
+   -0.5562
+   -0.3651
+   -0.4356
+   -0.7164
+   -0.5816
+   -0.4635
+   -0.8456
+   -0.9708
+   -0.7138
+   -0.7499
+   -0.6941
+   -0.6656
+   -0.2912
+   -0.1650
+    0.0774
+    0.2307
+    0.4484
+    0.4942
+    0.4653
+    0.2196
+    0.1736
+   -0.1595
+   -0.3918
+   -0.4611
+   -0.8493
+   -0.7384
+   -1.0604
+   -1.2166
+   -1.7187
+   -1.6932
+   -1.7830
+   -1.7035
+   -2.2079
+   -2.3769
+   -2.2511
+   -2.1093
+   -2.4638
+   -2.4027
+   -2.1313
+   -1.9199
+   -1.7941
+   -1.4661
+   -1.2269
+   -1.0392
+   -1.0725
+   -0.7156
+   -0.4778
+   -0.4233
+   -0.0409
+    0.1620
+    0.4280
+    0.5873
+    1.0323
+    1.3420
+    1.6902
+    2.0680
+    2.8219
+    3.2511
+    3.2930
+    3.5633
+    3.8992
+    3.6874
+    3.2849
+    3.1614
+    2.6221
+    2.5067
+    1.9223
+    1.1777
+    0.4483
+   -0.0661
+   -0.4424
+   -0.9000
+   -1.1478
+   -1.2047
+   -1.1412
+   -1.2383
+   -1.1048
+   -0.9716
+   -0.9287
+   -1.0057
+   -1.0827
+   -1.0200
+   -1.0072
+   -1.1740
+   -1.2809
+   -1.1086
+   -0.9866
+   -0.8947
+   -0.5875
+   -0.2329
+    0.1493
+    0.4906
+    0.8400
+    1.0720
+    1.2648
+    1.5431
+];
+
+PIE =[
+   -1.0113
+   -0.8305
+    0.2332
+   -0.8746
+   -0.7978
+   -0.9220
+   -0.2487
+   -0.7749
+   -0.5460
+   -0.5347
+    0.5050
+   -0.0334
+    0.6756
+    0.8791
+    0.7267
+    1.0997
+    1.1750
+    1.1927
+    0.4420
+    0.5357
+    0.0345
+    0.0196
+    0.3371
+    0.9379
+    1.2160
+    0.3393
+    0.5813
+    0.7410
+    0.3374
+    0.2616
+    0.4025
+    0.4799
+    0.5981
+   -0.1523
+    0.4458
+    0.2182
+    0.9793
+    0.7562
+    1.0064
+    0.8203
+    0.6966
+    0.3352
+    0.6581
+    0.6111
+    0.9833
+    1.1991
+    0.9562
+    0.3868
+    0.2939
+    0.2471
+    0.8331
+    0.0715
+    0.3910
+    0.3301
+    0.2547
+   -0.2702
+   -0.2998
+   -0.1953
+   -0.2293
+   -0.3284
+    0.0480
+   -0.0374
+    0.3253
+   -0.3434
+   -0.3892
+   -0.7178
+   -0.4758
+   -0.6794
+   -0.8505
+   -0.3512
+   -0.4436
+   -0.5101
+   -0.4574
+   -0.2696
+   -0.1047
+   -0.5745
+   -0.2989
+   -0.0063
+    0.0088
+   -0.1184
+   -0.1506
+   -0.4073
+    0.2674
+    0.2896
+    0.0669
+    0.1166
+   -0.1699
+   -0.2518
+   -0.0562
+   -0.3269
+   -0.0703
+   -0.1046
+   -0.4888
+   -0.3524
+   -0.2485
+   -0.5870
+   -0.4546
+   -0.3970
+   -0.2353
+   -0.0352
+   -0.2171
+   -0.3754
+   -0.4322
+   -0.4572
+   -0.4903
+   -0.4518
+   -0.6435
+   -0.6304
+   -0.4148
+   -0.2892
+   -0.4318
+   -0.6010
+   -0.4148
+   -0.4315
+   -0.3531
+   -0.8053
+   -0.4680
+   -0.4263
+];
+
+R =[
+   -1.0750
+   -1.1540
+   -1.3682
+   -1.4569
+   -1.3490
+   -1.4011
+   -1.6486
+   -1.6968
+   -1.6976
+   -1.2567
+   -1.1392
+   -0.7783
+   -0.3021
+   -0.0435
+    0.0066
+   -0.0043
+    0.1029
+   -0.0628
+   -0.5358
+   -0.9627
+   -1.1079
+   -1.0918
+   -0.9966
+   -0.6223
+   -0.3616
+   -0.2711
+   -0.0997
+   -0.2810
+   -0.3710
+   -0.3167
+   -0.5301
+   -0.5826
+   -0.3194
+   -0.2713
+   -0.5287
+   -0.2432
+    0.1098
+    0.5349
+    0.7094
+    0.8415
+    0.6226
+    0.7376
+    0.9316
+    1.4370
+    1.5853
+    1.4267
+    1.1783
+    1.2046
+    0.9689
+    0.7918
+    0.6315
+    0.5950
+    0.6853
+    0.7171
+    0.5887
+    0.4873
+    0.4027
+    0.3489
+    0.2934
+    0.3060
+    0.1741
+    0.0348
+    0.0771
+   -0.1005
+   -0.1518
+   -0.1104
+   -0.0681
+   -0.0059
+    0.0256
+    0.0404
+   -0.1721
+   -0.2002
+    0.0015
+    0.1249
+    0.3738
+    0.4320
+    0.5579
+    0.8186
+    0.8727
+    0.7356
+    0.7243
+    0.8635
+    0.9058
+    0.7656
+    0.7936
+    0.8631
+    0.9074
+    0.9547
+    1.2045
+    1.0850
+    0.9178
+    0.5242
+    0.3178
+    0.1472
+    0.0227
+   -0.0799
+   -0.0611
+   -0.0140
+    0.1132
+    0.1774
+    0.0782
+    0.0436
+   -0.1596
+   -0.2691
+   -0.2895
+   -0.3791
+   -0.4020
+   -0.4166
+   -0.4037
+   -0.3636
+   -0.4075
+   -0.4311
+   -0.4470
+   -0.5111
+   -0.6274
+   -0.7261
+   -0.6974
+   -0.5012
+];
+
+W =[
+  -14.8791
+  -13.2300
+  -13.5037
+  -13.0249
+  -11.2546
+  -10.0148
+   -8.8586
+   -8.5739
+   -7.7851
+   -6.7136
+   -5.5878
+   -4.6881
+   -3.8039
+   -3.0366
+   -2.7342
+   -1.3135
+   -0.7387
+   -0.1131
+   -0.2769
+    0.8696
+    1.8855
+    2.3667
+    2.4942
+    3.2049
+    3.9682
+    5.1500
+    4.7047
+    4.7827
+    5.3377
+    5.6614
+    5.2813
+    5.2967
+    5.5175
+    6.1526
+    5.6627
+    6.0694
+    6.5824
+    6.9032
+    6.7849
+    6.6896
+    6.6201
+    6.9933
+    5.8959
+    6.7419
+    6.9999
+    6.4009
+    5.5083
+    5.1054
+    5.2813
+    4.5790
+    3.9589
+    3.8599
+    3.8978
+    2.7957
+    3.2480
+    1.4634
+    1.9219
+    1.8398
+    1.9279
+    1.8316
+    1.6092
+    1.2741
+    0.2031
+   -0.0236
+   -0.1004
+   -0.3034
+   -1.0273
+   -0.2205
+    0.0458
+    0.2386
+   -0.0977
+   -0.3145
+   -0.1416
+   -0.7009
+   -0.9082
+   -0.8802
+   -0.5644
+   -0.5852
+   -0.5346
+    0.0652
+    0.1301
+    0.3444
+   -0.3592
+    0.8096
+    0.9644
+    1.0289
+    1.2781
+    1.2298
+    2.2134
+    2.0808
+    0.4925
+    0.6506
+    0.5531
+    0.2456
+   -0.5351
+   -0.8183
+   -0.8967
+   -0.7268
+   -1.0738
+   -1.2844
+   -1.4338
+   -1.6995
+   -1.7085
+   -2.2889
+   -2.1018
+   -2.4273
+   -2.4609
+   -2.1407
+   -2.3847
+   -3.1689
+   -4.5581
+   -4.1027
+   -4.2436
+   -4.8836
+   -5.9660
+   -4.9971
+   -5.2386
+   -5.6618
+];
+
+Y =[
+   -4.9347
+   -4.6205
+   -5.2198
+   -4.5937
+   -3.8015
+   -3.6643
+   -2.7239
+   -2.7524
+   -2.0634
+   -1.0112
+    0.0530
+    0.7623
+    1.7927
+    2.1486
+    2.4866
+    2.1456
+    2.1671
+   -0.0254
+   -1.6716
+   -1.9673
+   -1.6109
+   -1.0292
+   -0.1222
+    0.7329
+    1.1234
+    2.0603
+    1.7998
+    1.4820
+    1.1732
+    1.6424
+    1.5382
+    2.1399
+    2.0127
+    2.7210
+    2.4966
+    3.5249
+    3.6237
+    4.2011
+    4.5634
+    3.3442
+    2.7761
+    1.9812
+    1.3779
+    1.4616
+    1.3029
+    0.7594
+    0.3695
+    0.0832
+   -0.8118
+   -1.4557
+   -1.4850
+   -1.2346
+   -1.5696
+   -1.3785
+   -0.7682
+   -2.0308
+   -1.7778
+   -1.7801
+   -2.1711
+   -1.7469
+   -1.3413
+   -1.3352
+   -2.4390
+   -1.2125
+   -1.1695
+   -1.0891
+   -2.4753
+   -1.3503
+   -0.9412
+   -0.1470
+    0.0026
+    0.1108
+    0.6890
+    1.3520
+    1.6018
+    2.0667
+    1.7625
+    2.6658
+    3.4048
+    3.2507
+    3.4251
+    3.2174
+    3.1903
+    3.3396
+    3.1358
+    2.8625
+    3.3546
+    2.4609
+    1.9534
+    0.9962
+   -0.7904
+   -1.1672
+   -1.2586
+   -1.3593
+   -1.3443
+   -0.9413
+   -0.6023
+   -0.4516
+   -0.5129
+   -0.8741
+   -1.0784
+   -1.4091
+   -1.3627
+   -1.5731
+   -1.6037
+   -1.8814
+   -2.1482
+   -1.3597
+   -1.1855
+   -1.1122
+   -0.8424
+   -0.9747
+   -1.1385
+   -1.4548
+   -1.4284
+   -1.4633
+   -1.0621
+   -0.7871
+];
diff --git a/mex/sources/estimation/tests/sweuromodel_dll.mod b/mex/sources/estimation/tests/sweuromodel_dll.mod
index 363e310883fb494c748d69aa0deded1ae2e57ede..658dec00ade7f33ddb47b52db7b3562f4cc35c0d 100644
--- a/mex/sources/estimation/tests/sweuromodel_dll.mod
+++ b/mex/sources/estimation/tests/sweuromodel_dll.mod
@@ -1,182 +1,182 @@
-//options_.usePartInfo=1;
-
-var MC E EF R_KF QF CF IF YF LF PIEF WF RF R_K Q C I Y L PIE W R EE_A PIE_BAR EE_B EE_G EE_L EE_I KF K one BIGTHETA;    
-
-varexo E_A E_B E_G E_L E_I ETA_R E_PIE_BAR ETA_Q ETA_P ETA_W  ;  
- 
-parameters 
-xi_e lambda_w alpha czcap beta phi_i tau sig_c hab ccs cinvs phi_y gamma_w xi_w gamma_p xi_p sig_l r_dpi 
-r_pie r_dy r_y rho rho_a rho_pb rho_b rho_g rho_l rho_i LMP  ;
-
-
-
-alpha=.30;
-beta=.99;
-tau=0.025;
-ccs=0.6;
-cinvs=.22;  //% alpha*(tau+ctrend)/R_K   R_K=ctrend/beta-1+tau  
-lambda_w = 0.5;
-phi_i= 6.771;
-sig_c=   1.353; 
-hab=    0.573;    
-xi_w=   0.737;
-sig_l=    2.400;
-xi_p=   0.908;
-xi_e= 0.599;
-gamma_w=    0.763;
-gamma_p=    0.469;
-czcap=    0.169;
-phi_y=    1.408;
-r_pie=     1.684;
-r_dpi=    0.14;
-rho=      0.961;
-r_y=      0.099;
-r_dy=     0.159;
-rho_a=    0.823;
-rho_b=    0.855;
-rho_g=    0.949;
-rho_l=   0.889;
-rho_i=   0.927;
-rho_pb=  0.924;
-LMP = 0.0 ; //NEW.
-
-model(linear, use_dll); 
-          CF = (1/(1+hab))*(CF(1)+hab*CF(-1))-((1-hab)/((1+hab)*sig_c))*(RF-PIEF(1)-EE_B) ;
-	      0 =  alpha*R_KF+(1-alpha)*WF -EE_A ;
-          PIEF = 0*one;
-	      IF = (1/(1+beta))* ((  IF(-1) + beta*(IF(1)))+(1/phi_i)*QF)+0*ETA_Q+EE_I ;
-	      QF = -(RF-PIEF(1))+(1-beta*(1-tau))*((0+czcap)/czcap)*R_KF(1)+beta*(1-tau)*QF(1) +0*EE_I ;
-          KF =  (1-tau)*KF(-1)+tau*IF(-1) ;
-	      YF = (ccs*CF+cinvs*IF)+EE_G  ;
-
-	      YF = 1*phi_y*( alpha*KF+alpha*(1/czcap)*R_KF+(1-alpha)*LF+EE_A ) ;
-	      WF = (sig_c/(1-hab))*(CF-hab*CF(-1)) + sig_l*LF - EE_L ;
-	      LF = R_KF*((1+czcap)/czcap)-WF+KF ;
-          EF = EF(-1)+EF(1)-EF+(LF-EF)*((1-xi_e)*(1-xi_e*beta)/(xi_e));
-         
-	      C = (hab/(1+hab))*C(-1)+(1/(1+hab))*C(1)-((1-hab)/((1+hab)*sig_c))*(R-PIE(1)-EE_B) ;
-	      I = (1/(1+beta))* ((  I(-1) + beta*(I(1)))+(1/phi_i)*Q )+1*ETA_Q+1*EE_I ;
-	      Q = -(R-PIE(1))+(1-beta*(1-tau))*((0+czcap)/czcap)*R_K(1)+beta*(1-tau)*Q(1) +EE_I*0+0*ETA_Q ;
-	      K =  (1-tau)*K(-1)+tau*I(-1) ;
-	      Y = (ccs*C+cinvs*I)+ EE_G   ;
-	      Y = phi_y*( alpha*K+alpha*(1/czcap)*R_K+(1-alpha)*L ) +phi_y*EE_A  ;
-	      PIE = (1/(1+beta*gamma_p))*
-	            ( 
-	            (beta)*(PIE(1)) +(gamma_p)*(PIE(-1)) 
-	            +((1-xi_p)*(1-beta*xi_p)/(xi_p))*(MC)
-	            )  + ETA_P ; 
-	            
-	      MC = alpha*R_K+(1-alpha)*W -EE_A;
-	      W =  (1/(1+beta))*(beta*W(+1)+W(-1))
-                +(beta/(1+beta))*(PIE(+1))
-                -((1+beta*gamma_w)/(1+beta))*(PIE)
-                +(gamma_w/(1+beta))*(PIE(-1))
-                -(1/(1+beta))*(((1-beta*xi_w)*(1-xi_w))/(((1+(((1+lambda_w)*sig_l)/(lambda_w))))*xi_w))*(W-sig_l*L-(sig_c/(1-hab))*(C-hab*C(-1))+EE_L)
-                +ETA_W;
-	      L = R_K*((1+czcap)/czcap)-W+K ;
-
-//	      R = r_dpi*(PIE-PIE(-1))
-//              +(1-rho)*(r_pie*(PIE(-1)-PIE_BAR)+r_y*(Y-YF))
-//              +r_dy*(Y-YF-(Y(-1)-YF(-1)))
-//              +rho*(R(-1)-PIE_BAR)
-//              +PIE_BAR
-//              +ETA_R;
-
-
-	      R = 
-
-r_dpi*(PIE-PIE(-1))
-
-              +(1-rho)*(r_pie*(BIGTHETA)+r_y*(Y-YF))
-              +r_dy*(Y-YF-(Y(-1)-YF(-1)))
-              +rho*(R(-1)-PIE_BAR)
-              +PIE_BAR
-              +ETA_R;
-
-
-          E = E(-1)+E(1)-E+(L-E)*((1-xi_e)*(1-xi_e*beta)/(xi_e));
-          
-          
-          EE_A = (rho_a)*EE_A(-1)  + E_A;
-	      PIE_BAR = rho_pb*PIE_BAR(-1)+ E_PIE_BAR ;
-	      EE_B = rho_b*EE_B(-1) + E_B ;
-	      EE_G = rho_g*EE_G(-1) + E_G ;
-	      EE_L = rho_l*EE_L(-1) + E_L ;
-	      EE_I = rho_i*EE_I(-1) + E_I ;
-	      one = 0*one(-1) ;
-
-		LMP*BIGTHETA(1) = BIGTHETA - (PIE(-1) - PIE_BAR) ; 
-
-end; 
-
- 
-shocks;
-var E_A; stderr 0.598;
-var E_B; stderr 0.336;
-var E_G; stderr 0.325;
-var E_I; stderr 0.085;
-var E_L; stderr 3.520;
-var ETA_P; stderr 0.160;
-var ETA_W; stderr 0.289;
-var ETA_R; stderr 0.081;
-var ETA_Q; stderr 0.604;
-var E_PIE_BAR; stderr 0.017;
-end;
-
-//stoch_simul(irf=20) Y C PIE R W R_K L Q I K ;
-
-// stoch_simul generates what kind of standard errors for the shocks ?
-
-//steady;
-//check;
-//stoch_simul(periods=200,irf=20,simul_seed=3) Y C PIE MC R W R_K E L I ;
-
-//datatomfile('ddd',[]);
-
-// new syntax 
-
-estimated_params;
-// PARAM NAME, INITVAL, LB, UB, PRIOR_SHAPE, PRIOR_P1, PRIOR_P2, PRIOR_P3, PRIOR_P4, JSCALE
-// PRIOR_SHAPE: BETA_PDF, GAMMA_PDF, NORMAL_PDF, INV_GAMMA_PDF
-stderr E_A,0.543,0.01,4,INV_GAMMA_PDF,0.4,2;
-stderr E_PIE_BAR,0.072,0.001,4,INV_GAMMA_PDF,0.02,10;
-stderr E_B,0.2694,0.01,4,INV_GAMMA_PDF,0.2,2;
-stderr E_G,0.3052,0.01,4,INV_GAMMA_PDF,0.3,2;
-stderr E_L,1.4575,0.1,6,INV_GAMMA_PDF,1,2;
-stderr E_I,0.1318,0.01,4,INV_GAMMA_PDF,0.1,2;
-stderr ETA_R,0.1363,0.01,4,INV_GAMMA_PDF,0.1,2;
-stderr ETA_Q,0.4842,0.01,4,INV_GAMMA_PDF,0.4,2;
-stderr ETA_P,0.1731,0.01,4,INV_GAMMA_PDF,0.15,2;
-stderr ETA_W,0.2462,0.1,4,INV_GAMMA_PDF,0.25,2;
-rho_a,.9722,.1,.9999,BETA_PDF,0.85,0.1;
-rho_pb,.85,.1,.999,BETA_PDF,0.85,0.1;
-rho_b,.7647,.1,.99,BETA_PDF,0.85,0.1;
-rho_g,.9502,.1,.9999,BETA_PDF,0.85,0.1;
-rho_l,.9542,.1,.9999,BETA_PDF,0.85,0.1;
-rho_i,.6705,.1,.99,BETA_PDF,0.85,0.1;
-phi_i,5.2083,1,15,NORMAL_PDF,4,1.5;
-sig_c,0.9817,0.25,3,NORMAL_PDF,1,0.375;
-hab,0.5612,0.3,0.95,BETA_PDF,0.7,0.1;
-xi_w,0.7661,0.3,0.9,BETA_PDF,0.75,0.05;
-sig_l,1.7526,0.5,5,NORMAL_PDF,2,0.75;
-xi_p,0.8684,0.3,0.95,BETA_PDF,0.75,0.05;
-xi_e,0.5724,0.1,0.95,BETA_PDF,0.5,0.15;
-gamma_w,0.6202,0.1,0.99,BETA_PDF,0.75,0.15;
-gamma_p,0.6638,0.1,0.99,BETA_PDF,0.75,0.15;
-czcap,0.2516,0.01,2,NORMAL_PDF,0.2,0.075;
-phi_y,1.3011,1.001,2,NORMAL_PDF,1.45,0.125;
-r_pie,1.4616,1.2,2,NORMAL_PDF,1.7,0.1;
-r_dpi,0.1144,0.01,0.5,NORMAL_PDF,0.3,0.1;
-rho,0.8865,0.5,0.99,BETA_PDF,0.8,0.10;
-r_y,0.0571,0.01,0.2,NORMAL_PDF,0.125,0.05;
-r_dy,0.2228,0.05,0.5,NORMAL_PDF,0.0625,0.05;
-end;
-
-varobs Y C I E PIE W R;
-
-//estimation(datafile=rawdata_euromodel_1,presample=40, first_obs=1, nobs=118, lik_init=2, mode_compute=1,mh_replic=0);
-estimation(datafile=rawdata_euromodel_1,presample=40, first_obs=1, nobs=118,mh_jscale=0.2,mh_replic=150000, mode_check); //
-
-
-//stoch_simul(periods=200,irf=20,simul_seed=3) Y C PIE R W R_K L Q I K ;
-
+//options_.usePartInfo=1;
+
+var MC E EF R_KF QF CF IF YF LF PIEF WF RF R_K Q C I Y L PIE W R EE_A PIE_BAR EE_B EE_G EE_L EE_I KF K one BIGTHETA;    
+
+varexo E_A E_B E_G E_L E_I ETA_R E_PIE_BAR ETA_Q ETA_P ETA_W  ;  
+ 
+parameters 
+xi_e lambda_w alpha czcap beta phi_i tau sig_c hab ccs cinvs phi_y gamma_w xi_w gamma_p xi_p sig_l r_dpi 
+r_pie r_dy r_y rho rho_a rho_pb rho_b rho_g rho_l rho_i LMP  ;
+
+
+
+alpha=.30;
+beta=.99;
+tau=0.025;
+ccs=0.6;
+cinvs=.22;  //% alpha*(tau+ctrend)/R_K   R_K=ctrend/beta-1+tau  
+lambda_w = 0.5;
+phi_i= 6.771;
+sig_c=   1.353; 
+hab=    0.573;    
+xi_w=   0.737;
+sig_l=    2.400;
+xi_p=   0.908;
+xi_e= 0.599;
+gamma_w=    0.763;
+gamma_p=    0.469;
+czcap=    0.169;
+phi_y=    1.408;
+r_pie=     1.684;
+r_dpi=    0.14;
+rho=      0.961;
+r_y=      0.099;
+r_dy=     0.159;
+rho_a=    0.823;
+rho_b=    0.855;
+rho_g=    0.949;
+rho_l=   0.889;
+rho_i=   0.927;
+rho_pb=  0.924;
+LMP = 0.0 ; //NEW.
+
+model(linear, use_dll); 
+          CF = (1/(1+hab))*(CF(1)+hab*CF(-1))-((1-hab)/((1+hab)*sig_c))*(RF-PIEF(1)-EE_B) ;
+	      0 =  alpha*R_KF+(1-alpha)*WF -EE_A ;
+          PIEF = 0*one;
+	      IF = (1/(1+beta))* ((  IF(-1) + beta*(IF(1)))+(1/phi_i)*QF)+0*ETA_Q+EE_I ;
+	      QF = -(RF-PIEF(1))+(1-beta*(1-tau))*((0+czcap)/czcap)*R_KF(1)+beta*(1-tau)*QF(1) +0*EE_I ;
+          KF =  (1-tau)*KF(-1)+tau*IF(-1) ;
+	      YF = (ccs*CF+cinvs*IF)+EE_G  ;
+
+	      YF = 1*phi_y*( alpha*KF+alpha*(1/czcap)*R_KF+(1-alpha)*LF+EE_A ) ;
+	      WF = (sig_c/(1-hab))*(CF-hab*CF(-1)) + sig_l*LF - EE_L ;
+	      LF = R_KF*((1+czcap)/czcap)-WF+KF ;
+          EF = EF(-1)+EF(1)-EF+(LF-EF)*((1-xi_e)*(1-xi_e*beta)/(xi_e));
+         
+	      C = (hab/(1+hab))*C(-1)+(1/(1+hab))*C(1)-((1-hab)/((1+hab)*sig_c))*(R-PIE(1)-EE_B) ;
+	      I = (1/(1+beta))* ((  I(-1) + beta*(I(1)))+(1/phi_i)*Q )+1*ETA_Q+1*EE_I ;
+	      Q = -(R-PIE(1))+(1-beta*(1-tau))*((0+czcap)/czcap)*R_K(1)+beta*(1-tau)*Q(1) +EE_I*0+0*ETA_Q ;
+	      K =  (1-tau)*K(-1)+tau*I(-1) ;
+	      Y = (ccs*C+cinvs*I)+ EE_G   ;
+	      Y = phi_y*( alpha*K+alpha*(1/czcap)*R_K+(1-alpha)*L ) +phi_y*EE_A  ;
+	      PIE = (1/(1+beta*gamma_p))*
+	            ( 
+	            (beta)*(PIE(1)) +(gamma_p)*(PIE(-1)) 
+	            +((1-xi_p)*(1-beta*xi_p)/(xi_p))*(MC)
+	            )  + ETA_P ; 
+	            
+	      MC = alpha*R_K+(1-alpha)*W -EE_A;
+	      W =  (1/(1+beta))*(beta*W(+1)+W(-1))
+                +(beta/(1+beta))*(PIE(+1))
+                -((1+beta*gamma_w)/(1+beta))*(PIE)
+                +(gamma_w/(1+beta))*(PIE(-1))
+                -(1/(1+beta))*(((1-beta*xi_w)*(1-xi_w))/(((1+(((1+lambda_w)*sig_l)/(lambda_w))))*xi_w))*(W-sig_l*L-(sig_c/(1-hab))*(C-hab*C(-1))+EE_L)
+                +ETA_W;
+	      L = R_K*((1+czcap)/czcap)-W+K ;
+
+//	      R = r_dpi*(PIE-PIE(-1))
+//              +(1-rho)*(r_pie*(PIE(-1)-PIE_BAR)+r_y*(Y-YF))
+//              +r_dy*(Y-YF-(Y(-1)-YF(-1)))
+//              +rho*(R(-1)-PIE_BAR)
+//              +PIE_BAR
+//              +ETA_R;
+
+
+	      R = 
+
+r_dpi*(PIE-PIE(-1))
+
+              +(1-rho)*(r_pie*(BIGTHETA)+r_y*(Y-YF))
+              +r_dy*(Y-YF-(Y(-1)-YF(-1)))
+              +rho*(R(-1)-PIE_BAR)
+              +PIE_BAR
+              +ETA_R;
+
+
+          E = E(-1)+E(1)-E+(L-E)*((1-xi_e)*(1-xi_e*beta)/(xi_e));
+          
+          
+          EE_A = (rho_a)*EE_A(-1)  + E_A;
+	      PIE_BAR = rho_pb*PIE_BAR(-1)+ E_PIE_BAR ;
+	      EE_B = rho_b*EE_B(-1) + E_B ;
+	      EE_G = rho_g*EE_G(-1) + E_G ;
+	      EE_L = rho_l*EE_L(-1) + E_L ;
+	      EE_I = rho_i*EE_I(-1) + E_I ;
+	      one = 0*one(-1) ;
+
+		LMP*BIGTHETA(1) = BIGTHETA - (PIE(-1) - PIE_BAR) ; 
+
+end; 
+
+ 
+shocks;
+var E_A; stderr 0.598;
+var E_B; stderr 0.336;
+var E_G; stderr 0.325;
+var E_I; stderr 0.085;
+var E_L; stderr 3.520;
+var ETA_P; stderr 0.160;
+var ETA_W; stderr 0.289;
+var ETA_R; stderr 0.081;
+var ETA_Q; stderr 0.604;
+var E_PIE_BAR; stderr 0.017;
+end;
+
+//stoch_simul(irf=20) Y C PIE R W R_K L Q I K ;
+
+// stoch_simul generates what kind of standard errors for the shocks ?
+
+//steady;
+//check;
+//stoch_simul(periods=200,irf=20,simul_seed=3) Y C PIE MC R W R_K E L I ;
+
+//datatomfile('ddd',[]);
+
+// new syntax 
+
+estimated_params;
+// PARAM NAME, INITVAL, LB, UB, PRIOR_SHAPE, PRIOR_P1, PRIOR_P2, PRIOR_P3, PRIOR_P4, JSCALE
+// PRIOR_SHAPE: BETA_PDF, GAMMA_PDF, NORMAL_PDF, INV_GAMMA_PDF
+stderr E_A,0.543,0.01,4,INV_GAMMA_PDF,0.4,2;
+stderr E_PIE_BAR,0.072,0.001,4,INV_GAMMA_PDF,0.02,10;
+stderr E_B,0.2694,0.01,4,INV_GAMMA_PDF,0.2,2;
+stderr E_G,0.3052,0.01,4,INV_GAMMA_PDF,0.3,2;
+stderr E_L,1.4575,0.1,6,INV_GAMMA_PDF,1,2;
+stderr E_I,0.1318,0.01,4,INV_GAMMA_PDF,0.1,2;
+stderr ETA_R,0.1363,0.01,4,INV_GAMMA_PDF,0.1,2;
+stderr ETA_Q,0.4842,0.01,4,INV_GAMMA_PDF,0.4,2;
+stderr ETA_P,0.1731,0.01,4,INV_GAMMA_PDF,0.15,2;
+stderr ETA_W,0.2462,0.1,4,INV_GAMMA_PDF,0.25,2;
+rho_a,.9722,.1,.9999,BETA_PDF,0.85,0.1;
+rho_pb,.85,.1,.999,BETA_PDF,0.85,0.1;
+rho_b,.7647,.1,.99,BETA_PDF,0.85,0.1;
+rho_g,.9502,.1,.9999,BETA_PDF,0.85,0.1;
+rho_l,.9542,.1,.9999,BETA_PDF,0.85,0.1;
+rho_i,.6705,.1,.99,BETA_PDF,0.85,0.1;
+phi_i,5.2083,1,15,NORMAL_PDF,4,1.5;
+sig_c,0.9817,0.25,3,NORMAL_PDF,1,0.375;
+hab,0.5612,0.3,0.95,BETA_PDF,0.7,0.1;
+xi_w,0.7661,0.3,0.9,BETA_PDF,0.75,0.05;
+sig_l,1.7526,0.5,5,NORMAL_PDF,2,0.75;
+xi_p,0.8684,0.3,0.95,BETA_PDF,0.75,0.05;
+xi_e,0.5724,0.1,0.95,BETA_PDF,0.5,0.15;
+gamma_w,0.6202,0.1,0.99,BETA_PDF,0.75,0.15;
+gamma_p,0.6638,0.1,0.99,BETA_PDF,0.75,0.15;
+czcap,0.2516,0.01,2,NORMAL_PDF,0.2,0.075;
+phi_y,1.3011,1.001,2,NORMAL_PDF,1.45,0.125;
+r_pie,1.4616,1.2,2,NORMAL_PDF,1.7,0.1;
+r_dpi,0.1144,0.01,0.5,NORMAL_PDF,0.3,0.1;
+rho,0.8865,0.5,0.99,BETA_PDF,0.8,0.10;
+r_y,0.0571,0.01,0.2,NORMAL_PDF,0.125,0.05;
+r_dy,0.2228,0.05,0.5,NORMAL_PDF,0.0625,0.05;
+end;
+
+varobs Y C I E PIE W R;
+
+//estimation(datafile=rawdata_euromodel_1,presample=40, first_obs=1, nobs=118, lik_init=2, mode_compute=1,mh_replic=0);
+estimation(datafile=rawdata_euromodel_1,presample=40, first_obs=1, nobs=118,mh_jscale=0.2,mh_replic=150000, mode_check); //
+
+
+//stoch_simul(periods=200,irf=20,simul_seed=3) Y C PIE R W R_K L Q I K ;
+
diff --git a/mex/sources/estimation/utils/dynamic_dll.cc b/mex/sources/estimation/utils/dynamic_dll.cc
index bff1d92a8a5bc2b28a8edb0cac5c2e84e30e7e5d..495e0bae4966d7ba42449d6bc7748280ef5b01c2 100644
--- a/mex/sources/estimation/utils/dynamic_dll.cc
+++ b/mex/sources/estimation/utils/dynamic_dll.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/estimation/utils/dynamic_dll.hh b/mex/sources/estimation/utils/dynamic_dll.hh
index c1f28e997be2ef3549db44d5352a3bc2ac1b5d12..dfb4d8b19fb69cc4e540bb321d8c42600e63f6c6 100644
--- a/mex/sources/estimation/utils/dynamic_dll.hh
+++ b/mex/sources/estimation/utils/dynamic_dll.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010-2011 Dynare Team
+ * Copyright (C) 2010-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/k_order_perturbation/dynamic_m.hh b/mex/sources/k_order_perturbation/dynamic_m.hh
index 74b4706a4bd1ca1b2d69fc373a460dfae32d97f6..632dcdd7acd157585748e3cb9cde434bf49ebdc3 100644
--- a/mex/sources/k_order_perturbation/dynamic_m.hh
+++ b/mex/sources/k_order_perturbation/dynamic_m.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010 Dynare Team
+ * Copyright (C) 2010-2011 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/mex/sources/k_order_perturbation/k_ord_dynare.cc b/mex/sources/k_order_perturbation/k_ord_dynare.cc
index d932743028bb3ae9e856351b91f5dc2b03c62ee4..7258611e785ab57f2875b15b0b7ab40c74ee689a 100644
--- a/mex/sources/k_order_perturbation/k_ord_dynare.cc
+++ b/mex/sources/k_order_perturbation/k_ord_dynare.cc
@@ -46,7 +46,30 @@ KordpDynare::KordpDynare(const vector<string> &endo, int num_endo,
   nYs(npred + nboth), nYss(nboth + nforw), nY(num_endo), nJcols(jcols), NNZD(nnzd), nSteps(nsteps),
   nOrder(norder), journal(jr), ySteady(ysteady), params(inParams), vCov(vcov),
   md(1), dnl(*this, endo), denl(*this, exo), dsnl(*this, dnl, denl), ss_tol(sstol), varOrder(var_order),
-  ll_Incidence(llincidence), qz_criterium(criterium), dynamicModelFile(dynamicModelFile_arg)
+  ll_Incidence(llincidence), qz_criterium(criterium), dynamicModelFile(dynamicModelFile_arg), g1p(NULL),
+  g2p(NULL), g3p(NULL)
+{
+  ReorderDynareJacobianIndices();
+
+  //	Initialise ModelDerivativeContainer(*this, this->md, nOrder);
+  for (int iord = 1; iord <= nOrder; iord++)
+    md.insert(new FSSparseTensor(iord, nY+nYs+nYss+nExog, nY));
+}
+
+KordpDynare::KordpDynare(const vector<string> &endo, int num_endo,
+                         const vector<string> &exo, int nexog, int npar,
+                         Vector &ysteady, TwoDMatrix &vcov, Vector &inParams, int nstat,
+                         int npred, int nforw, int nboth, const int jcols, const Vector &nnzd,
+                         const int nsteps, int norder,
+                         Journal &jr, DynamicModelAC *dynamicModelFile_arg, double sstol,
+                         const vector<int> &var_order, const TwoDMatrix &llincidence, double criterium,
+			 TwoDMatrix *g1_arg, TwoDMatrix *g2_arg, TwoDMatrix *g3_arg) throw (TLException) :
+  nStat(nstat), nBoth(nboth), nPred(npred), nForw(nforw), nExog(nexog), nPar(npar),
+  nYs(npred + nboth), nYss(nboth + nforw), nY(num_endo), nJcols(jcols), NNZD(nnzd), nSteps(nsteps),
+  nOrder(norder), journal(jr), ySteady(ysteady), params(inParams), vCov(vcov),
+  md(1), dnl(*this, endo), denl(*this, exo), dsnl(*this, dnl, denl), ss_tol(sstol), varOrder(var_order),
+  ll_Incidence(llincidence), qz_criterium(criterium), dynamicModelFile(dynamicModelFile_arg), 
+  g1p(g1_arg), g2p(g2_arg), g3p(g3_arg)
 {
   ReorderDynareJacobianIndices();
 
@@ -89,35 +112,37 @@ KordpDynare::evaluateSystem(Vector &out, const Vector &yym, const Vector &yy,
 void
 KordpDynare::calcDerivativesAtSteady() throw (DynareException)
 {
-  TwoDMatrix g1(nY, nJcols);
-  g1.zeros();
-
-  TwoDMatrix *g2p = NULL, *g3p = NULL;
-
-  if (nOrder > 1)
-    {
-      // allocate space for sparse Hessian
-      g2p = new TwoDMatrix((int) NNZD[1], 3);
-      g2p->zeros();
-    }
-
-  if (nOrder > 2)
+  if (g1p == NULL)
     {
-      g3p = new TwoDMatrix((int) NNZD[2], 3);
-      g3p->zeros();
+      g1p = new TwoDMatrix(nY, nJcols);
+      g1p->zeros();
+      
+      if (nOrder > 1)
+	{
+	  // allocate space for sparse Hessian
+	  g2p = new TwoDMatrix((int) NNZD[1], 3);
+	  g2p->zeros();
+	}
+      
+      if (nOrder > 2)
+	{
+	  g3p = new TwoDMatrix((int) NNZD[2], 3);
+	  g3p->zeros();
+	}
+
+      Vector xx(nexog());
+      xx.zeros();
+      
+      Vector out(nY);
+      out.zeros();
+      Vector llxSteady(nJcols-nExog);
+      LLxSteady(ySteady, llxSteady);
+      
+      dynamicModelFile->eval(llxSteady, xx, params, ySteady, out, g1p, g2p, g3p);
     }
 
-  Vector xx(nexog());
-  xx.zeros();
-
-  Vector out(nY);
-  out.zeros();
-  Vector llxSteady(nJcols-nExog);
-  LLxSteady(ySteady, llxSteady);
-
-  dynamicModelFile->eval(llxSteady, xx, params, ySteady, out, &g1, g2p, g3p);
-
-  populateDerivativesContainer(g1, 1, JacobianIndices);
+  populateDerivativesContainer(*g1p, 1, JacobianIndices);
+  delete g1p;
 
   if (nOrder > 1)
     {
diff --git a/mex/sources/k_order_perturbation/k_ord_dynare.hh b/mex/sources/k_order_perturbation/k_ord_dynare.hh
index 3629c3d74ae40e12828f80b020d0c73ead8cc06f..445373cdcdcbe92ad6cf70c2fb8c669bfa13a529 100644
--- a/mex/sources/k_order_perturbation/k_ord_dynare.hh
+++ b/mex/sources/k_order_perturbation/k_ord_dynare.hh
@@ -113,6 +113,10 @@ class KordpDynare : public DynamicModel
   const TwoDMatrix &ll_Incidence;
   double qz_criterium;
   vector<int> JacobianIndices;
+
+  TwoDMatrix *g1p;
+  TwoDMatrix *g2p;
+  TwoDMatrix *g3p;
 public:
   KordpDynare(const vector<string> &endo, int num_endo,
               const vector<string> &exo, int num_exo, int num_par,
@@ -122,6 +126,14 @@ public:
               Journal &jr, DynamicModelAC *dynamicModelFile_arg, double sstol,
               const vector<int> &varOrder, const TwoDMatrix &ll_Incidence,
               double qz_criterium) throw (TLException);
+  KordpDynare(const vector<string> &endo, int num_endo,
+              const vector<string> &exo, int num_exo, int num_par,
+              Vector &ySteady, TwoDMatrix &vCov, Vector &params, int nstat, int nPred,
+              int nforw, int nboth, const int nJcols, const Vector &NNZD,
+              const int nSteps, const int ord,
+              Journal &jr, DynamicModelAC *dynamicModelFile_arg, double sstol,
+              const vector<int> &varOrder, const TwoDMatrix &ll_Incidence,
+              double qz_criterium, TwoDMatrix *g1_arg, TwoDMatrix *g2_arg, TwoDMatrix *g3_arg) throw (TLException);
 
   virtual ~KordpDynare();
   int
diff --git a/mex/sources/k_order_perturbation/k_order_perturbation.cc b/mex/sources/k_order_perturbation/k_order_perturbation.cc
index 86a98209bd35c2c8755d915b199f3d661226ac6d..fba8b8ec4462b9ab0dbc06bae6f99e3011a2b9e6 100644
--- a/mex/sources/k_order_perturbation/k_order_perturbation.cc
+++ b/mex/sources/k_order_perturbation/k_order_perturbation.cc
@@ -62,14 +62,24 @@ DynareMxArrayToString(const mxArray *mxFldp, const int len, const int width, vec
         out[j] += cNamesCharStr[j+i*len];
 }
 
+void copy_derivatives(mxArray *destin,const Symmetry &sym,const FGSContainer *derivs,const std::string &fieldname)
+{
+  const TwoDMatrix* x = derivs->get(sym);
+  int n = x->numRows();
+  int m = x->numCols();
+  mxArray *tmp = mxCreateDoubleMatrix(n, m, mxREAL);
+  memcpy(mxGetPr(tmp),x->getData().base(),n*m*sizeof(double));
+  mxSetField(destin,0,fieldname.c_str(),tmp);
+}
+
 extern "C" {
 
   void
   mexFunction(int nlhs, mxArray *plhs[],
               int nrhs, const mxArray *prhs[])
   {
-    if (nrhs != 3 || nlhs < 2)
-      DYN_MEX_FUNC_ERR_MSG_TXT("Must have exactly 3 input parameters and take at least 2 output parameters.");
+    if (nrhs < 3 || nlhs < 2)
+      DYN_MEX_FUNC_ERR_MSG_TXT("Must have at least 3 input parameters and takes at least 2 output parameters.");
 
     const mxArray *dr = prhs[0];
     const mxArray *M_ = prhs[1];
@@ -89,10 +99,10 @@ extern "C" {
     else
       kOrder = 1;
 
-    if (kOrder == 1 && nlhs != 2)
-      DYN_MEX_FUNC_ERR_MSG_TXT("k_order_perturbation at order 1 requires exactly 2 arguments in output");
-    else if (kOrder > 1 && nlhs != kOrder+2)
-      DYN_MEX_FUNC_ERR_MSG_TXT("k_order_perturbation at order > 1 requires exactly order+2 arguments in output");
+    //if (kOrder == 1 && nlhs != 2)
+    //  DYN_MEX_FUNC_ERR_MSG_TXT("k_order_perturbation at order 1 requires exactly 2 arguments in output");
+    //else if (kOrder > 1 && nlhs != kOrder+2)
+    //  DYN_MEX_FUNC_ERR_MSG_TXT("k_order_perturbation at order > 1 requires exactly order+2 arguments in output");
 
     double qz_criterium = 1+1e-6;
     mxFldp = mxGetField(options_, 0, "qz_criterium");
@@ -189,7 +199,32 @@ extern "C" {
     if ((nEndo != nendo) || (nExog != nexo))
       DYN_MEX_FUNC_ERR_MSG_TXT("Incorrect number of input parameters.");
 
-    /* Fetch time index */
+    TwoDMatrix *g1m=NULL;
+    TwoDMatrix *g2m=NULL;
+    TwoDMatrix *g3m=NULL;
+    // derivatives passed as arguments */
+    if (nrhs > 3) 
+      {
+	const mxArray *g1 = prhs[3];
+	int m = (int) mxGetM(g1);
+	int n = (int) mxGetN(g1);
+	g1m = new TwoDMatrix(m, n, mxGetPr(g1));
+	if (nrhs > 4)
+	  {
+	    const mxArray *g2 = prhs[4];
+	    int m = (int) mxGetM(g2);
+	    int n = (int) mxGetN(g2);
+	    g2m = new TwoDMatrix(m, n, mxGetPr(g2));
+	    if (nrhs > 5)
+	      {
+		const mxArray *g3 = prhs[5];
+		int m = (int) mxGetM(g3);
+		int n = (int) mxGetN(g3);
+		g3m = new TwoDMatrix(m, n, mxGetPr(g3));
+	      }
+	  }
+      }
+	    
 
     const int nSteps = 0; // Dynare++ solving steps, for time being default to 0 = deterministic steady state
     const double sstol = 1.e-13; //NL solver tolerance from
@@ -216,7 +251,8 @@ extern "C" {
         KordpDynare dynare(endoNames, nEndo, exoNames, nExog, nPar,
                            ySteady, vCov, modParams, nStat, nPred, nForw, nBoth,
                            jcols, NNZD, nSteps, kOrder, journal, dynamicModelFile,
-                           sstol, var_order_vp, llincidence, qz_criterium);
+                           sstol, var_order_vp, llincidence, qz_criterium,
+			   g1m, g2m, g3m);
 
         // construct main K-order approximation class
 
@@ -249,18 +285,40 @@ extern "C" {
             for (map<string, ConstTwoDMatrix>::const_iterator cit = mm.begin();
                  ((cit != mm.end()) && (ii < nlhs)); ++cit)
               {
-                {
-                  plhs[ii] = mxCreateDoubleMatrix((*cit).second.numRows(), (*cit).second.numCols(), mxREAL);
-
-                  // Copy Dynare++ matrix into MATLAB matrix
-                  const ConstVector &vec = (*cit).second.getData();
-                  assert(vec.skip() == 1);
-                  memcpy(mxGetPr(plhs[ii]), vec.base(), vec.length() * sizeof(double));
-
-                  ++ii;
-                }
+		plhs[ii] = mxCreateDoubleMatrix((*cit).second.numRows(), (*cit).second.numCols(), mxREAL);
+		
+		// Copy Dynare++ matrix into MATLAB matrix
+		const ConstVector &vec = (*cit).second.getData();
+		assert(vec.skip() == 1);
+		memcpy(mxGetPr(plhs[ii]), vec.base(), vec.length() * sizeof(double));
+		
+		++ii;
+		
               }
-          }
+	    if (kOrder == 3 && nlhs > 4)
+	      {
+		const FGSContainer *derivs = app.get_rule_ders();
+		const std::string fieldnames[] = {"gy", "gu", "gyy", "gyu", "guu", "gss", 
+				      "gyyy", "gyyu", "gyuu", "guuu", "gyss", "guss"};
+		// creates the char** expected by mxCreateStructMatrix()
+		const char* c_fieldnames[12];
+		for (int i=0; i < 12;++i)
+		  c_fieldnames[i] = fieldnames[i].c_str();
+		plhs[ii] = mxCreateStructMatrix(1,1,12,c_fieldnames);
+		copy_derivatives(plhs[ii],Symmetry(1,0,0,0),derivs,"gy");
+		copy_derivatives(plhs[ii],Symmetry(0,1,0,0),derivs,"gu");
+		copy_derivatives(plhs[ii],Symmetry(2,0,0,0),derivs,"gyy");
+		copy_derivatives(plhs[ii],Symmetry(0,2,0,0),derivs,"guu");
+		copy_derivatives(plhs[ii],Symmetry(1,1,0,0),derivs,"gyu");
+		copy_derivatives(plhs[ii],Symmetry(0,0,0,2),derivs,"gss");
+		copy_derivatives(plhs[ii],Symmetry(3,0,0,0),derivs,"gyyy");
+		copy_derivatives(plhs[ii],Symmetry(0,3,0,0),derivs,"guuu");
+		copy_derivatives(plhs[ii],Symmetry(2,1,0,0),derivs,"gyyu");
+		copy_derivatives(plhs[ii],Symmetry(1,2,0,0),derivs,"gyuu");
+		copy_derivatives(plhs[ii],Symmetry(1,0,0,2),derivs,"gyss");
+		copy_derivatives(plhs[ii],Symmetry(0,1,0,2),derivs,"guss");
+	      }
+	  }
       }
     catch (const KordException &e)
       {
@@ -294,5 +352,4 @@ extern "C" {
     plhs[0] = mxCreateDoubleScalar(0);
   } // end of mexFunction()
 } // end of extern C
-
 #endif // ifdef MATLAB_MEX_FILE  to exclude mexFunction for other applications
diff --git a/mex/sources/k_order_perturbation/tests/fs2000k.mod b/mex/sources/k_order_perturbation/tests/fs2000k.mod
index 731a946c7ab78cd5c31a8cca05e9aa565c0a4c93..850b1f938278090743fa7ab34accbb34dc70d943 100644
--- a/mex/sources/k_order_perturbation/tests/fs2000k.mod
+++ b/mex/sources/k_order_perturbation/tests/fs2000k.mod
@@ -1,119 +1,119 @@
-// This file replicates the estimation of the CIA model from 
-// Frank Schorfheide (2000) "Loss function-based evaluation of DSGE models" 
-// Journal of  Applied Econometrics, 15, 645-670.
-// the data are the ones provided on Schorfheide's web site with the programs.
-// http://www.econ.upenn.edu/~schorf/programs/dsgesel.ZIP
-// You need to have fsdat.m in the same directory as this file.
-// This file replicates: 
-// -the posterior mode as computed by Frank's Gauss programs
-// -the parameter mean posterior estimates reported in the paper
-// -the model probability (harmonic mean) reported in the paper
-// This file was tested with dyn_mat_test_0218.zip
-// the smooth shocks are probably stil buggy
-//
-// The equations are taken from J. Nason and T. Cogley (1994) 
-// "Testing the implications of long-run neutrality for monetary business
-// cycle models" Journal of Applied Econometrics, 9, S37-S70.
-// Note that there is an initial minus sign missing in equation (A1), p. S63.
-//
-// Michel Juillard, February 2004
-// Modified for testing k_order_perturbation by GP, Jan-Feb 09
-
-options_.usePartInfo=0;
-options_.use_k_order=0;
-
-//var m m_1 P P_1 c e W R k d n l gy_obs gp_obs Y_obs P_obs y dA P2 c2;
-var m m_1 P P_1 c e W R k d n l gy_obs gp_obs y dA P2 c2;
-varexo e_a e_m;
-
-parameters alp bet gam mst rho psi del;
-
-alp = 0.33;
-bet = 0.99;
-gam = 0.003;
-mst = 1.011;
-rho = 0.7;
-psi = 0.787;
-del = 0.02;
-
-model (use_dll);
-dA = exp(gam+e_a);
-log(m) = (1-rho)*log(mst) + rho*log(m_1(-1))+e_m;
--P/(c(+1)*P(+1)*m)+bet*P(+1)*(alp*exp(-alp*(gam+log(e(+1))))*k^(alp-1)*n(+1)^(1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c2(+1)*P2(+1)*m(+1))=0;
-W = l/n;
--(psi/(1-psi))*(c*P/(1-n))+l/n = 0;
-R = P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(-alp)/W;
-1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)/(m*l*c(+1)*P(+1)) = 0;
-c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1);
-P*c = m;
-m-1+d = l;
-e = exp(e_a);
-y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a));
-gy_obs = dA*y/y(-1);
-gp_obs = (P/P_1(-1))*m_1(-1)/dA;
-//Y_obs/Y_obs(-1) = gy_obs;
-//P_obs/P_obs(-1) = gp_obs;
-P2 = P(+1);
-c2 = c(+1);
-m_1 = m;
-P_1 = P;
-end;
-
-initval;
-m = mst;
-m_1=mst;
-P = 2.25;
-P_1 = 2.25;
-c = 0.45;
-e = 1;
-W = 4;
-R = 1.02;
-k = 6;
-d = 0.85;
-n = 0.19;
-l = 0.86;
-y = 0.6;
-gy_obs = exp(gam);
-gp_obs = exp(-gam); 
-dA = exp(gam);
-  P2=P;
-  c2=c;
-end;
-
-shocks;
-var e_a; stderr 0.014;
-var e_m; stderr 0.005;
-end;
-
-//unit_root_vars P_obs Y_obs;
-
-steady(solve_algo = 2);
-
-check;
-
-estimated_params;
-alp, beta_pdf, 0.356, 0.02; 
-bet, beta_pdf, 0.993, 0.002;
-gam, normal_pdf, 0.0085, 0.003;
-mst, normal_pdf, 1.0002, 0.007;
-rho, beta_pdf, 0.129, 0.223;
-psi, beta_pdf, 0.65, 0.05;
-del, beta_pdf, 0.01, 0.005;
-stderr e_a, inv_gamma_pdf, 0.035449, inf;
-stderr e_m, inv_gamma_pdf, 0.008862, inf;
-end;
-
-//varobs P_obs Y_obs;
-varobs gp_obs gy_obs;
-
-steady(solve_algo = 2);
-
-//observation_trends;
-//P_obs (log(mst)-gam);
-//Y_obs (gam);
-//end;
-
-//options_.useAIM = 1;
-estimation(datafile=fsdat,nobs=192,loglinear,mh_replic=2000,
-	mode_compute=4,mh_nblocks=2,mh_drop=0.45,mh_jscale=0.65);
-
+// This file replicates the estimation of the CIA model from 
+// Frank Schorfheide (2000) "Loss function-based evaluation of DSGE models" 
+// Journal of  Applied Econometrics, 15, 645-670.
+// the data are the ones provided on Schorfheide's web site with the programs.
+// http://www.econ.upenn.edu/~schorf/programs/dsgesel.ZIP
+// You need to have fsdat.m in the same directory as this file.
+// This file replicates: 
+// -the posterior mode as computed by Frank's Gauss programs
+// -the parameter mean posterior estimates reported in the paper
+// -the model probability (harmonic mean) reported in the paper
+// This file was tested with dyn_mat_test_0218.zip
+// the smooth shocks are probably stil buggy
+//
+// The equations are taken from J. Nason and T. Cogley (1994) 
+// "Testing the implications of long-run neutrality for monetary business
+// cycle models" Journal of Applied Econometrics, 9, S37-S70.
+// Note that there is an initial minus sign missing in equation (A1), p. S63.
+//
+// Michel Juillard, February 2004
+// Modified for testing k_order_perturbation by GP, Jan-Feb 09
+
+options_.usePartInfo=0;
+options_.use_k_order=0;
+
+//var m m_1 P P_1 c e W R k d n l gy_obs gp_obs Y_obs P_obs y dA P2 c2;
+var m m_1 P P_1 c e W R k d n l gy_obs gp_obs y dA P2 c2;
+varexo e_a e_m;
+
+parameters alp bet gam mst rho psi del;
+
+alp = 0.33;
+bet = 0.99;
+gam = 0.003;
+mst = 1.011;
+rho = 0.7;
+psi = 0.787;
+del = 0.02;
+
+model (use_dll);
+dA = exp(gam+e_a);
+log(m) = (1-rho)*log(mst) + rho*log(m_1(-1))+e_m;
+-P/(c(+1)*P(+1)*m)+bet*P(+1)*(alp*exp(-alp*(gam+log(e(+1))))*k^(alp-1)*n(+1)^(1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c2(+1)*P2(+1)*m(+1))=0;
+W = l/n;
+-(psi/(1-psi))*(c*P/(1-n))+l/n = 0;
+R = P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(-alp)/W;
+1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)/(m*l*c(+1)*P(+1)) = 0;
+c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1);
+P*c = m;
+m-1+d = l;
+e = exp(e_a);
+y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a));
+gy_obs = dA*y/y(-1);
+gp_obs = (P/P_1(-1))*m_1(-1)/dA;
+//Y_obs/Y_obs(-1) = gy_obs;
+//P_obs/P_obs(-1) = gp_obs;
+P2 = P(+1);
+c2 = c(+1);
+m_1 = m;
+P_1 = P;
+end;
+
+initval;
+m = mst;
+m_1=mst;
+P = 2.25;
+P_1 = 2.25;
+c = 0.45;
+e = 1;
+W = 4;
+R = 1.02;
+k = 6;
+d = 0.85;
+n = 0.19;
+l = 0.86;
+y = 0.6;
+gy_obs = exp(gam);
+gp_obs = exp(-gam); 
+dA = exp(gam);
+  P2=P;
+  c2=c;
+end;
+
+shocks;
+var e_a; stderr 0.014;
+var e_m; stderr 0.005;
+end;
+
+//unit_root_vars P_obs Y_obs;
+
+steady(solve_algo = 2);
+
+check;
+
+estimated_params;
+alp, beta_pdf, 0.356, 0.02; 
+bet, beta_pdf, 0.993, 0.002;
+gam, normal_pdf, 0.0085, 0.003;
+mst, normal_pdf, 1.0002, 0.007;
+rho, beta_pdf, 0.129, 0.223;
+psi, beta_pdf, 0.65, 0.05;
+del, beta_pdf, 0.01, 0.005;
+stderr e_a, inv_gamma_pdf, 0.035449, inf;
+stderr e_m, inv_gamma_pdf, 0.008862, inf;
+end;
+
+//varobs P_obs Y_obs;
+varobs gp_obs gy_obs;
+
+steady(solve_algo = 2);
+
+//observation_trends;
+//P_obs (log(mst)-gam);
+//Y_obs (gam);
+//end;
+
+//options_.useAIM = 1;
+estimation(datafile=fsdat,nobs=192,loglinear,mh_replic=2000,
+	mode_compute=4,mh_nblocks=2,mh_drop=0.45,mh_jscale=0.65);
+
diff --git a/mex/sources/local_state_space_iterations/local_state_space_iteration_2.cc b/mex/sources/local_state_space_iterations/local_state_space_iteration_2.cc
index 6943b782b52f5068e573cc4fb5cc4424ab9bf31e..3e299818398695b55bdef99f723cdd908cad1111 100644
--- a/mex/sources/local_state_space_iterations/local_state_space_iteration_2.cc
+++ b/mex/sources/local_state_space_iterations/local_state_space_iteration_2.cc
@@ -310,7 +310,7 @@ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
   double *ghxx = mxGetPr(prhs[5]);
   double *ghuu = mxGetPr(prhs[6]);
   double *ghxu = mxGetPr(prhs[7]);
-  double *yhat_, *ss;
+  double *yhat_ = NULL, *ss = NULL;
   if (nrhs>9)
     {
       yhat_ = mxGetPr(prhs[8]);
diff --git a/mex/sources/mjdgges/mjdgges.c b/mex/sources/mjdgges/mjdgges.c
index 2237ce292b0e55161be24ef55cf81066c9566714..145439bb9de794d7b54c95934c74514115b53061 100644
--- a/mex/sources/mjdgges/mjdgges.c
+++ b/mex/sources/mjdgges/mjdgges.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006-2011 Dynare Team
+ * Copyright (C) 2006-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -34,12 +34,11 @@ my_criteria(const double *alphar, const double *alphai, const double *beta)
 void
 mjdgges(double *a, double *b, double *z, double *n, double *sdim, double *eval_r, double *eval_i, double *info)
 {
-  lapack_int i_n, i_info, i_sdim, one, lwork;
+  lapack_int i_n, i_info, i_sdim, lwork;
   double *alphar, *alphai, *beta, *work, *par, *pai, *pb, *per, *pei;
   double *junk;
   lapack_int *bwork;
 
-  one = 1;
   i_n = (lapack_int)*n;
   alphar = mxCalloc(i_n, sizeof(double));
   alphai = mxCalloc(i_n, sizeof(double));
diff --git a/mex/sources/sobol/gaussian.hh b/mex/sources/sobol/gaussian.hh
index 9df04fdf3bd4c346e5065e707eeac63ba8bd7fce..2fee95097826ee8ec563b9f09bb643c5d033f4d7 100644
--- a/mex/sources/sobol/gaussian.hh
+++ b/mex/sources/sobol/gaussian.hh
@@ -2,7 +2,7 @@
 ** 
 ** Pseudo code of the algorithm is given at http://home.online.no/~pjacklam/notes/invnorm  
 **
-** Copyright (C)  2010 Dynare Team
+** Copyright (C) 2010-2011 Dynare Team
 **
 ** This file is part of Dynare.
 **
diff --git a/mex/sources/sobol/qmc_sequence.cc b/mex/sources/sobol/qmc_sequence.cc
index 0eddd734d45484e98f7c5f6ae1cd96db0b2a044b..04e4a567f0265586c6f965a68396019bca5c4cbb 100644
--- a/mex/sources/sobol/qmc_sequence.cc
+++ b/mex/sources/sobol/qmc_sequence.cc
@@ -1,7 +1,7 @@
 /*
 ** Computes Quasi Monte-Carlo sequence.
 **
-** Copyright (C) 2010-2011 Dynare Team
+** Copyright (C) 2010-2012 Dynare Team
 **
 ** This file is part of Dynare (can be used outside Dynare).
 **
@@ -135,7 +135,7 @@ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
     {
       DYN_MEX_FUNC_ERR_MSG_TXT("qmc_sequence:: The fifth input argument must be a positive scalar!");
     }
-  double *lower_bounds, *upper_bounds;
+  double *lower_bounds = NULL, *upper_bounds = NULL;
   int unit_hypercube_flag = 1;
   if ( (type==0) && (nrhs>4) )
     {
diff --git a/osx/createOsxFolderForPkg.sh b/osx/createOsxFolderForPkg.sh
index c969d5b3729cda7a413c55de4afd76b4efd4512b..d429886b636b00ff6dfab8f4b9897f276fdb392f 100755
--- a/osx/createOsxFolderForPkg.sh
+++ b/osx/createOsxFolderForPkg.sh
@@ -2,15 +2,13 @@
 
 set -ex
 
-TOP_DIR=/Users/Houtan/Documents/DYNARE
+TOP_DIR=/Users/Houtan/Documents/DYNARE/PACKAGES
 TOP_DYN_DIR=$TOP_DIR/dynare
 
-VERSION=4.2.2
+VERSION=4.3
 INSTALLDIRNAME=dynare-$VERSION-osx
+mkdir $INSTALLDIRNAME
 INSTALLDIR=$TOP_DIR/$INSTALLDIRNAME
-mkdir $INSTALLDIR
-
-PATH=${PATH}:/Applications/Octave.app/Contents/Resources/bin:/usr/local/bin:/usr/local/sbin:/usr/texbin:/usr/local/include:/usr/local/lib:/usr/local/libexec:/usr/local/share:/usr/local/Cellar/
 
 ########################
 # UPDATE DYNARE SOURCE #
@@ -23,23 +21,24 @@ autoreconf -si
 # BEGIN MAKING PACKAGE #
 ########################
 # create directories
-mkdir "$INSTALLDIR/doc"
-mkdir "$INSTALLDIR/doc/dynare++"
-mkdir "$INSTALLDIR/doc/dynare.html"
+mkdir "$INSTALLDIR/scripts"
 mkdir "$INSTALLDIR/dynare++"
-mkdir "$INSTALLDIR/mex"
-mkdir "$INSTALLDIR/mex/octave"
-mkdir "$INSTALLDIR/mex/matlab"
-mkdir "$INSTALLDIR/mex/matlab/osx64"
+mkdir -p "$INSTALLDIR/doc/dynare++"
+mkdir "$INSTALLDIR/doc/dynare.html"
+mkdir -p "$INSTALLDIR/contrib/ms-sbvar/TZcode"
+mkdir -p "$INSTALLDIR/mex/octave"
+mkdir -p "$INSTALLDIR/mex/matlab/osx64"
 mkdir "$INSTALLDIR/mex/matlab/osx32-7.4"
-mkdir "$INSTALLDIR/mex/matlab/osx32-7.5-7.13"
+mkdir "$INSTALLDIR/mex/matlab/osx32-7.5-7.14"
+
 
 # top level
-cp $TOP_DYN_DIR/dynare.el                                        $INSTALLDIR
+cp $TOP_DYN_DIR/scripts/dynare.el                                $INSTALLDIR/scripts
 cp $TOP_DYN_DIR/license.txt                                      $INSTALLDIR
+cp $TOP_DYN_DIR/NEWS                                             $INSTALLDIR
 
-# matlab
-cp -r $TOP_DYN_DIR/matlab                                        $INSTALLDIR
+# TZ Matlab
+cp -r $TOP_DYN_DIR/contrib/ms-sbvar/TZcode/MatlabFiles           $INSTALLDIR/contrib/ms-sbvar/TZcode
 
 # examples
 cp -r $TOP_DYN_DIR/examples                                      $INSTALLDIR
@@ -52,6 +51,9 @@ cp -r $TOP_DYN_DIR/examples                                      $INSTALLDIR
 make pdf
 make
 
+# Matlab
+# Must come after configure because matlab/dynare_version.m is created by configure script
+cp -r $TOP_DYN_DIR/matlab                                        $INSTALLDIR
 
 ########################
 # MAKE BULK OF PACKAGE #
@@ -60,52 +62,55 @@ make
 cp $TOP_DYN_DIR/preprocessor/dynare_m                            $INSTALLDIR/matlab
 
 # Matlab
-cp $TOP_DYN_DIR/mex/build/matlab/block_kalman_filter/*.mexmaci   $INSTALLDIR/mex/matlab/osx32-7.4
-cp $TOP_DYN_DIR/mex/build/matlab/bytecode/*.mexmaci              $INSTALLDIR/mex/matlab/osx32-7.4
-cp $TOP_DYN_DIR/mex/build/matlab/dynare_simul_/*.mexmaci         $INSTALLDIR/mex/matlab/osx32-7.4
-cp $TOP_DYN_DIR/mex/build/matlab/estimation/*.mexmaci            $INSTALLDIR/mex/matlab/osx32-7.4
-cp $TOP_DYN_DIR/mex/build/matlab/gensylv/*.mexmaci               $INSTALLDIR/mex/matlab/osx32-7.4
-cp $TOP_DYN_DIR/mex/build/matlab/k_order_perturbation/*.mexmaci  $INSTALLDIR/mex/matlab/osx32-7.4
-cp $TOP_DYN_DIR/mex/build/matlab/kalman_steady_state/*.mexmaci   $INSTALLDIR/mex/matlab/osx32-7.4
-cp $TOP_DYN_DIR/mex/build/matlab/kronecker/*.mexmaci             $INSTALLDIR/mex/matlab/osx32-7.4
-cp $TOP_DYN_DIR/mex/build/matlab/mjdgges/*.mexmaci               $INSTALLDIR/mex/matlab/osx32-7.4
-cp $TOP_DYN_DIR/mex/build/matlab/ms_sbvar/*.mexmaci              $INSTALLDIR/mex/matlab/osx32-7.4
+cp $TOP_DYN_DIR/mex/build/matlab/block_kalman_filter/*.mexmaci                      $INSTALLDIR/mex/matlab/osx32-7.4
+cp $TOP_DYN_DIR/mex/build/matlab/bytecode/*.mexmaci                                 $INSTALLDIR/mex/matlab/osx32-7.4
+cp $TOP_DYN_DIR/mex/build/matlab/dynare_simul_/*.mexmaci                            $INSTALLDIR/mex/matlab/osx32-7.4
+cp $TOP_DYN_DIR/mex/build/matlab/gensylv/*.mexmaci                                  $INSTALLDIR/mex/matlab/osx32-7.4
+cp $TOP_DYN_DIR/mex/build/matlab/k_order_perturbation/*.mexmaci                     $INSTALLDIR/mex/matlab/osx32-7.4
+cp $TOP_DYN_DIR/mex/build/matlab/kalman_steady_state/*.mexmaci                      $INSTALLDIR/mex/matlab/osx32-7.4
+cp $TOP_DYN_DIR/mex/build/matlab/kronecker/*.mexmaci                                $INSTALLDIR/mex/matlab/osx32-7.4
+cp $TOP_DYN_DIR/mex/build/matlab/local_state_space_iterations/*.mexmaci             $INSTALLDIR/mex/matlab/osx32-7.4
+cp $TOP_DYN_DIR/mex/build/matlab/mjdgges/*.mexmaci                                  $INSTALLDIR/mex/matlab/osx32-7.4
+cp $TOP_DYN_DIR/mex/build/matlab/ms_sbvar/*.mexmaci                                 $INSTALLDIR/mex/matlab/osx32-7.4
+cp $TOP_DYN_DIR/mex/build/matlab/sobol/*.mexmaci                                    $INSTALLDIR/mex/matlab/osx32-7.4
 
 # Octave
-cp $TOP_DYN_DIR/mex/build/octave/block_kalman_filter/*.mex       $INSTALLDIR/mex/octave
-cp $TOP_DYN_DIR/mex/build/octave/bytecode/*.mex                  $INSTALLDIR/mex/octave
-cp $TOP_DYN_DIR/mex/build/octave/dynare_simul_/*.mex             $INSTALLDIR/mex/octave
-cp $TOP_DYN_DIR/mex/build/octave/estimation/*.mex                $INSTALLDIR/mex/octave
-cp $TOP_DYN_DIR/mex/build/octave/gensylv/*.mex                   $INSTALLDIR/mex/octave
-cp $TOP_DYN_DIR/mex/build/octave/k_order_perturbation/*.mex      $INSTALLDIR/mex/octave
-cp $TOP_DYN_DIR/mex/build/octave/kalman_steady_state/*.mex       $INSTALLDIR/mex/octave
-cp $TOP_DYN_DIR/mex/build/octave/kronecker/*.mex                 $INSTALLDIR/mex/octave
-cp $TOP_DYN_DIR/mex/build/octave/mjdgges/*.mex                   $INSTALLDIR/mex/octave
-cp $TOP_DYN_DIR/mex/build/octave/ms_sbvar/*.mex                  $INSTALLDIR/mex/octave
-cp $TOP_DYN_DIR/mex/build/octave/ordschur/*.oct                  $INSTALLDIR/mex/octave
-cp $TOP_DYN_DIR/mex/build/octave/qzcomplex/*.oct                 $INSTALLDIR/mex/octave
+cp $TOP_DYN_DIR/mex/build/octave/block_kalman_filter/*.mex                          $INSTALLDIR/mex/octave
+cp $TOP_DYN_DIR/mex/build/octave/bytecode/*.mex                                     $INSTALLDIR/mex/octave
+cp $TOP_DYN_DIR/mex/build/octave/dynare_simul_/*.mex                                $INSTALLDIR/mex/octave
+cp $TOP_DYN_DIR/mex/build/octave/gensylv/*.mex                                      $INSTALLDIR/mex/octave
+cp $TOP_DYN_DIR/mex/build/octave/k_order_perturbation/*.mex                         $INSTALLDIR/mex/octave
+cp $TOP_DYN_DIR/mex/build/octave/kalman_steady_state/*.mex                          $INSTALLDIR/mex/octave
+cp $TOP_DYN_DIR/mex/build/octave/kronecker/*.mex                                    $INSTALLDIR/mex/octave
+cp $TOP_DYN_DIR/mex/build/octave/local_state_space_iterations/*.mex                 $INSTALLDIR/mex/octave
+cp $TOP_DYN_DIR/mex/build/octave/mjdgges/*.mex                                      $INSTALLDIR/mex/octave
+cp $TOP_DYN_DIR/mex/build/octave/ms_sbvar/*.mex                                     $INSTALLDIR/mex/octave
+cp $TOP_DYN_DIR/mex/build/octave/ordschur/*.oct                                     $INSTALLDIR/mex/octave
+cp $TOP_DYN_DIR/mex/build/octave/qzcomplex/*.oct                                    $INSTALLDIR/mex/octave
+cp $TOP_DYN_DIR/mex/build/octave/sobol/*.mex                                        $INSTALLDIR/mex/octave
 
 # dynare++
-cp $TOP_DYN_DIR/dynare++/src/dynare++                            $INSTALLDIR/dynare++
-cp $TOP_DYN_DIR/dynare++/extern/matlab/dynare_simul.m            $INSTALLDIR/dynare++
+cp $TOP_DYN_DIR/dynare++/src/dynare++                                               $INSTALLDIR/dynare++
+cp $TOP_DYN_DIR/dynare++/extern/matlab/dynare_simul.m                               $INSTALLDIR/dynare++
 
 # doc
-cp $TOP_DYN_DIR/doc/bvar-a-la-sims.pdf                           $INSTALLDIR/doc
-cp $TOP_DYN_DIR/doc/dr.pdf                                       $INSTALLDIR/doc
-cp $TOP_DYN_DIR/doc/dynare.pdf                                   $INSTALLDIR/doc
-cp $TOP_DYN_DIR/doc/guide.pdf                                    $INSTALLDIR/doc
-cp $TOP_DYN_DIR/doc/macroprocessor/macroprocessor.pdf            $INSTALLDIR/doc
-cp $TOP_DYN_DIR/doc/parallel/parallel.pdf                        $INSTALLDIR/doc
-cp $TOP_DYN_DIR/doc/preprocessor/preprocessor.pdf                $INSTALLDIR/doc
-cp $TOP_DYN_DIR/doc/userguide/UserGuide.pdf                      $INSTALLDIR/doc
+cp $TOP_DYN_DIR/doc/bvar-a-la-sims.pdf                                              $INSTALLDIR/doc
+cp $TOP_DYN_DIR/doc/dr.pdf                                                          $INSTALLDIR/doc
+cp $TOP_DYN_DIR/doc/dynare.pdf                                                      $INSTALLDIR/doc
+cp $TOP_DYN_DIR/doc/guide.pdf                                                       $INSTALLDIR/doc
+cp $TOP_DYN_DIR/doc/macroprocessor/macroprocessor.pdf                               $INSTALLDIR/doc
+cp $TOP_DYN_DIR/doc/parallel/parallel.pdf                                           $INSTALLDIR/doc
+cp $TOP_DYN_DIR/doc/preprocessor/preprocessor.pdf                                   $INSTALLDIR/doc
+cp $TOP_DYN_DIR/doc/userguide/UserGuide.pdf                                         $INSTALLDIR/doc
+cp $TOP_DYN_DIR/doc/gsa/gsa.pdf                                                     $INSTALLDIR/doc
 
 # doc (dynare++)
-cp $TOP_DYN_DIR/dynare++/doc/dynare++-tutorial.pdf               $INSTALLDIR/doc/dynare++
-cp $TOP_DYN_DIR/dynare++/doc/dynare++-ramsey.pdf                 $INSTALLDIR/doc/dynare++
-cp $TOP_DYN_DIR/dynare++/sylv/sylvester.pdf                      $INSTALLDIR/doc/dynare++
-cp $TOP_DYN_DIR/dynare++/tl/cc/tl.pdf                            $INSTALLDIR/doc/dynare++
-cp $TOP_DYN_DIR/dynare++/integ/cc/integ.pdf                      $INSTALLDIR/doc/dynare++
-cp $TOP_DYN_DIR/dynare++/kord/kord.pdf                           $INSTALLDIR/doc/dynare++
+cp $TOP_DYN_DIR/dynare++/doc/dynare++-tutorial.pdf                                  $INSTALLDIR/doc/dynare++
+cp $TOP_DYN_DIR/dynare++/doc/dynare++-ramsey.pdf                                    $INSTALLDIR/doc/dynare++
+cp $TOP_DYN_DIR/dynare++/sylv/sylvester.pdf                                         $INSTALLDIR/doc/dynare++
+cp $TOP_DYN_DIR/dynare++/tl/cc/tl.pdf                                               $INSTALLDIR/doc/dynare++
+cp $TOP_DYN_DIR/dynare++/integ/cc/integ.pdf                                         $INSTALLDIR/doc/dynare++
+cp $TOP_DYN_DIR/dynare++/kord/kord.pdf                                              $INSTALLDIR/doc/dynare++
 
 
 ##############################################
@@ -117,16 +122,17 @@ cd $TOP_DYN_DIR/mex/build/matlab
 make
 
 # Matlab
-cp $TOP_DYN_DIR/mex/build/matlab/block_kalman_filter/*.mexmaci   $INSTALLDIR/mex/matlab/osx32-7.5-7.13
-cp $TOP_DYN_DIR/mex/build/matlab/bytecode/*.mexmaci              $INSTALLDIR/mex/matlab/osx32-7.5-7.13
-cp $TOP_DYN_DIR/mex/build/matlab/dynare_simul_/*.mexmaci         $INSTALLDIR/mex/matlab/osx32-7.5-7.13
-cp $TOP_DYN_DIR/mex/build/matlab/estimation/*.mexmaci            $INSTALLDIR/mex/matlab/osx32-7.5-7.13
-cp $TOP_DYN_DIR/mex/build/matlab/gensylv/*.mexmaci               $INSTALLDIR/mex/matlab/osx32-7.5-7.13
-cp $TOP_DYN_DIR/mex/build/matlab/k_order_perturbation/*.mexmaci  $INSTALLDIR/mex/matlab/osx32-7.5-7.13
-cp $TOP_DYN_DIR/mex/build/matlab/kalman_steady_state/*.mexmaci   $INSTALLDIR/mex/matlab/osx32-7.5-7.13
-cp $TOP_DYN_DIR/mex/build/matlab/kronecker/*.mexmaci             $INSTALLDIR/mex/matlab/osx32-7.5-7.13
-cp $TOP_DYN_DIR/mex/build/matlab/mjdgges/*.mexmaci               $INSTALLDIR/mex/matlab/osx32-7.5-7.13
-cp $TOP_DYN_DIR/mex/build/matlab/ms_sbvar/*.mexmaci              $INSTALLDIR/mex/matlab/osx32-7.5-7.13
+cp $TOP_DYN_DIR/mex/build/matlab/block_kalman_filter/*.mexmaci                      $INSTALLDIR/mex/matlab/osx32-7.5-7.14
+cp $TOP_DYN_DIR/mex/build/matlab/bytecode/*.mexmaci                                 $INSTALLDIR/mex/matlab/osx32-7.5-7.14
+cp $TOP_DYN_DIR/mex/build/matlab/dynare_simul_/*.mexmaci                            $INSTALLDIR/mex/matlab/osx32-7.5-7.14
+cp $TOP_DYN_DIR/mex/build/matlab/gensylv/*.mexmaci                                  $INSTALLDIR/mex/matlab/osx32-7.5-7.14
+cp $TOP_DYN_DIR/mex/build/matlab/k_order_perturbation/*.mexmaci                     $INSTALLDIR/mex/matlab/osx32-7.5-7.14
+cp $TOP_DYN_DIR/mex/build/matlab/kalman_steady_state/*.mexmaci                      $INSTALLDIR/mex/matlab/osx32-7.5-7.14
+cp $TOP_DYN_DIR/mex/build/matlab/kronecker/*.mexmaci                                $INSTALLDIR/mex/matlab/osx32-7.5-7.14
+cp $TOP_DYN_DIR/mex/build/matlab/local_state_space_iterations/*.mexmaci             $INSTALLDIR/mex/matlab/osx32-7.5-7.14
+cp $TOP_DYN_DIR/mex/build/matlab/mjdgges/*.mexmaci                                  $INSTALLDIR/mex/matlab/osx32-7.5-7.14
+cp $TOP_DYN_DIR/mex/build/matlab/ms_sbvar/*.mexmaci                                 $INSTALLDIR/mex/matlab/osx32-7.5-7.14
+cp $TOP_DYN_DIR/mex/build/matlab/sobol/*.mexmaci                                    $INSTALLDIR/mex/matlab/osx32-7.5-7.14
 
 
 #####################################
@@ -138,16 +144,17 @@ cd $TOP_DYN_DIR/mex/build/matlab
 make
 
 # Matlab
-cp $TOP_DYN_DIR/mex/build/matlab/block_kalman_filter/*.mexmaci64   $INSTALLDIR/mex/matlab/osx64
-cp $TOP_DYN_DIR/mex/build/matlab/bytecode/*.mexmaci64              $INSTALLDIR/mex/matlab/osx64
-cp $TOP_DYN_DIR/mex/build/matlab/dynare_simul_/*.mexmaci64         $INSTALLDIR/mex/matlab/osx64
-cp $TOP_DYN_DIR/mex/build/matlab/estimation/*.mexmaci64            $INSTALLDIR/mex/matlab/osx64
-cp $TOP_DYN_DIR/mex/build/matlab/gensylv/*.mexmaci64               $INSTALLDIR/mex/matlab/osx64
-cp $TOP_DYN_DIR/mex/build/matlab/k_order_perturbation/*.mexmaci64  $INSTALLDIR/mex/matlab/osx64
-cp $TOP_DYN_DIR/mex/build/matlab/kalman_steady_state/*.mexmaci64   $INSTALLDIR/mex/matlab/osx64
-cp $TOP_DYN_DIR/mex/build/matlab/kronecker/*.mexmaci64             $INSTALLDIR/mex/matlab/osx64
-cp $TOP_DYN_DIR/mex/build/matlab/mjdgges/*.mexmaci64               $INSTALLDIR/mex/matlab/osx64
-cp $TOP_DYN_DIR/mex/build/matlab/ms_sbvar/*.mexmaci64              $INSTALLDIR/mex/matlab/osx64
+cp $TOP_DYN_DIR/mex/build/matlab/block_kalman_filter/*.mexmaci64                      $INSTALLDIR/mex/matlab/osx64
+cp $TOP_DYN_DIR/mex/build/matlab/bytecode/*.mexmaci64                                 $INSTALLDIR/mex/matlab/osx64
+cp $TOP_DYN_DIR/mex/build/matlab/dynare_simul_/*.mexmaci64                            $INSTALLDIR/mex/matlab/osx64
+cp $TOP_DYN_DIR/mex/build/matlab/gensylv/*.mexmaci64                                  $INSTALLDIR/mex/matlab/osx64
+cp $TOP_DYN_DIR/mex/build/matlab/k_order_perturbation/*.mexmaci64                     $INSTALLDIR/mex/matlab/osx64
+cp $TOP_DYN_DIR/mex/build/matlab/kalman_steady_state/*.mexmaci64                      $INSTALLDIR/mex/matlab/osx64
+cp $TOP_DYN_DIR/mex/build/matlab/kronecker/*.mexmaci64                                $INSTALLDIR/mex/matlab/osx64
+cp $TOP_DYN_DIR/mex/build/matlab/local_state_space_iterations/*.mexmaci64             $INSTALLDIR/mex/matlab/osx64
+cp $TOP_DYN_DIR/mex/build/matlab/mjdgges/*.mexmaci64                                  $INSTALLDIR/mex/matlab/osx64
+cp $TOP_DYN_DIR/mex/build/matlab/ms_sbvar/*.mexmaci64                                 $INSTALLDIR/mex/matlab/osx64
+cp $TOP_DYN_DIR/mex/build/matlab/sobol/*.mexmaci64                                    $INSTALLDIR/mex/matlab/osx64
 
 # clean everything
 cd $TOP_DYN_DIR
@@ -157,8 +164,9 @@ make distclean
 cd $INSTALLDIR
 find . -name *.DS_Store -type f -exec rm {} \;
 
-# adjust permissions
-cd $TOP_DIR
+# Change permissions
 chmod -R g+w $INSTALLDIR
 
-echo "DONE :)"
+echo DONE
+# NEED TO BUILD DYNARE.HTML DOCUMENTION ON DEBIAN
+# AND INCLUDE IN DISTRIBUTION BY HAND
\ No newline at end of file
diff --git a/preprocessor/ComputingTasks.cc b/preprocessor/ComputingTasks.cc
index a77d0e28ca0fdb22f26a9b09f3c7e3e7c0ccce46..3a3451d5b0862bbce23790004ba042b1fa1c61d2 100644
--- a/preprocessor/ComputingTasks.cc
+++ b/preprocessor/ComputingTasks.cc
@@ -95,6 +95,9 @@ void
 SimulStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings)
 {
   mod_file_struct.simul_present = true;
+
+  // The following is necessary to allow shocks+endval+simul in a loop
+  mod_file_struct.shocks_present_but_simul_not_yet = false;
 }
 
 void
@@ -132,14 +135,6 @@ StochSimulStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli
       || mod_file_struct.order_option >= 3)
     mod_file_struct.k_order_solver = true;
 
-  // Check that option "pruning" is not used with k-order
-  it = options_list.num_options.find("pruning");
-  if ((it != options_list.num_options.end() && it->second == "1")
-      && mod_file_struct.k_order_solver)
-    {
-      cerr << "ERROR: in 'stoch_simul', you cannot use option 'pruning' with 'k_order_solver' option or with 3rd order approximation" << endl;
-      exit(EXIT_FAILURE);
-    }
 }
 
 void
@@ -224,6 +219,12 @@ DiscretionaryPolicyStatement::checkPass(ModFileStructure &mod_file_struct, Warni
 {
   mod_file_struct.discretionary_policy_present = true;
 
+  if (options_list.symbol_list_options.find("instruments") == options_list.symbol_list_options.end())
+    {
+      cerr << "ERROR: discretionary_policy: the instruments option is required." << endl;
+      exit(EXIT_FAILURE);
+    }
+
   /* Fill in option_order of mod_file_struct
      Since discretionary policy needs one further order of derivation (for example, for 1st order
      approximation, it needs 2nd derivatives), we add 1 to the order declared by user */
@@ -276,13 +277,28 @@ EstimationStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli
   // Fill in option_order of mod_file_struct
   OptionsList::num_options_t::const_iterator it = options_list.num_options.find("order");
   if (it != options_list.num_options.end())
-    mod_file_struct.order_option = max(mod_file_struct.order_option, atoi(it->second.c_str()));
-
+    {
+      int order = atoi(it->second.c_str());
+          
+      if (order > 2)
+        {
+          cerr << "ERROR: order > 2 is not supported in estimation" << endl;
+          exit(EXIT_FAILURE);
+        }
+      
+      mod_file_struct.order_option = max(mod_file_struct.order_option, order);
+    }
+  
   // Fill in mod_file_struct.partial_information
   it = options_list.num_options.find("partial_information");
   if (it != options_list.num_options.end() && it->second == "1")
     mod_file_struct.partial_information = true;
 
+  // Fill in mod_file_struct.estimation_analytic_derivation
+  it = options_list.num_options.find("analytic_derivation");
+  if (it != options_list.num_options.end() && it->second == "1")
+    mod_file_struct.estimation_analytic_derivation = true;
+
   it = options_list.num_options.find("dsge_var");
   if (it != options_list.num_options.end())
     // Ensure that irf_shocks & dsge_var have not both been passed
@@ -334,6 +350,14 @@ void
 EstimationStatement::writeOutput(ostream &output, const string &basename) const
 {
   options_list.writeOutput(output);
+
+  // Special treatment for order option and particle filter
+  OptionsList::num_options_t::const_iterator it = options_list.num_options.find("order");
+  if (it == options_list.num_options.end())
+    output << "options_.order = 1;" << endl;
+  else if (atoi(it->second.c_str()) == 2)
+    output << "options_.particle.status = 1;" << endl;
+
   symbol_list.writeOutput("var_list_", output);
   output << "dynare_estimation(var_list_);\n";
 }
@@ -356,6 +380,21 @@ void
 DynareSensitivityStatement::writeOutput(ostream &output, const string &basename) const
 {
   options_list.writeOutput(output, "options_gsa");
+
+  /* Ensure that nograph, nodisplay and graph_format are also set in top-level
+     options_.
+     \todo factorize this code between identification and dynare_sensitivity,
+     and provide a generic mechanism for this situation (maybe using regexps) */
+  OptionsList::num_options_t::const_iterator it = options_list.num_options.find("nodisplay");
+  if (it != options_list.num_options.end())
+    output << "options_.nodisplay = " << it->second << ";" << endl;
+  it = options_list.num_options.find("nograph");
+  if (it != options_list.num_options.end())
+    output << "options_.nograph = " << it->second << ";" << endl;
+  OptionsList::string_options_t::const_iterator it2 = options_list.string_options.find("graph_format");
+  if (it2 != options_list.string_options.end())
+    output << "options_.graph_format = '" << it2->second << "';" << endl;
+  
   output << "dynare_sensitivity(options_gsa);" << endl;
 }
 
@@ -1162,6 +1201,21 @@ void
 IdentificationStatement::writeOutput(ostream &output, const string &basename) const
 {
   options_list.writeOutput(output, "options_ident");
+
+  /* Ensure that nograph, nodisplay and graph_format are also set in top-level
+     options_.
+     \todo factorize this code between identification and dynare_sensitivity,
+     and provide a generic mechanism for this situation (maybe using regexps) */
+  OptionsList::num_options_t::const_iterator it = options_list.num_options.find("nodisplay");
+  if (it != options_list.num_options.end())
+    output << "options_.nodisplay = " << it->second << ";" << endl;
+  it = options_list.num_options.find("nograph");
+  if (it != options_list.num_options.end())
+    output << "options_.nograph = " << it->second << ";" << endl;
+  OptionsList::string_options_t::const_iterator it2 = options_list.string_options.find("graph_format");
+  if (it2 != options_list.string_options.end())
+    output << "options_.graph_format = '" << it2->second << "';" << endl;
+
   output << "dynare_identification(options_ident);" << endl;
 }
 
@@ -2314,5 +2368,35 @@ CalibSmootherStatement::writeOutput(ostream &output, const string &basename) con
   symbol_list.writeOutput("var_list_", output);
   output << "options_.mode_compute = 0;" << endl
          << "options_.smoother = 1;" << endl
+         << "options_.order = 1;" << endl
          << "dynare_estimation(var_list_);" << endl;
 }
+
+ExtendedPathStatement::ExtendedPathStatement(const OptionsList &options_list_arg)
+  : options_list(options_list_arg)
+{
+}
+
+void
+ExtendedPathStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings)
+{
+  if (options_list.num_options.find("periods") == options_list.num_options.end())
+    {
+      cerr << "ERROR: the 'periods' option of 'extended_path' is mandatory" << endl;
+      exit(EXIT_FAILURE);
+    }
+}
+
+void
+ExtendedPathStatement::writeOutput(ostream &output, const string &basename) const
+{
+  // Beware: options do not have the same name in the interface and in the M code...
+
+  OptionsList::num_options_t::const_iterator it = options_list.num_options.find("solver_periods");
+  if (it != options_list.num_options.end())
+    output << "options_.ep.periods = " << it->second << ";" << endl;
+
+  output << "oo_.endo_simul = [ oo_.steady_state, extended_path([], " << options_list.num_options.find("periods")->second
+         << ") ];" << endl
+         << "oo_.exo_simul = oo_.ep.shocks;" << endl;
+}
diff --git a/preprocessor/ComputingTasks.hh b/preprocessor/ComputingTasks.hh
index 0c210ce60399a66b7bb317793dbccd81a0e812ff..5a75ea55bcbb54a31753a1c16d6961c736235bdb 100644
--- a/preprocessor/ComputingTasks.hh
+++ b/preprocessor/ComputingTasks.hh
@@ -519,6 +519,16 @@ public:
   virtual void writeOutput(ostream &output, const string &basename) const;
 };
 
+class ExtendedPathStatement : public Statement
+{
+private:
+  const OptionsList options_list;
+public:
+  ExtendedPathStatement(const OptionsList &options_list_arg);
+  virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings);
+  virtual void writeOutput(ostream &output, const string &basename) const;
+};
+
 class SvarIdentificationStatement : public Statement
 {
 public:
diff --git a/preprocessor/ConfigFile.cc b/preprocessor/ConfigFile.cc
index 0c6874d9a81def70957fa7b6e8af9f9e55438b21..2d0e34999547918164dd253215dc0a01e84c545b 100644
--- a/preprocessor/ConfigFile.cc
+++ b/preprocessor/ConfigFile.cc
@@ -30,6 +30,16 @@
 
 using namespace std;
 
+Hook::Hook(string &global_init_file_arg)
+{
+  if (global_init_file_arg.empty())
+    {
+      cerr << "ERROR: The Hook must have a Global Initialization File argument." << endl;
+      exit(EXIT_FAILURE);
+    }
+  hooks["global_init_file"] = global_init_file_arg;
+}
+
 SlaveNode::SlaveNode(string &computerName_arg, string port_arg, int minCpuNbr_arg, int maxCpuNbr_arg, string &userName_arg,
                      string &password_arg, string &remoteDrive_arg, string &remoteDirectory_arg,
                      string &dynarePath_arg, string &matlabOctavePath_arg, bool singleCompThread_arg,
@@ -74,56 +84,78 @@ ConfigFile::~ConfigFile()
 }
 
 void
-ConfigFile::getConfigFileInfo(const string &parallel_config_file)
+ConfigFile::getConfigFileInfo(const string &config_file)
 {
   using namespace boost;
-  if (!parallel && !parallel_test)
-    return;
-
   ifstream *configFile;
-  if (parallel_config_file.empty())
+
+  if (config_file.empty())
     {
+      string defaultConfigFile ("");
       // Test OS and try to open default file
 #if defined(_WIN32) || defined(__CYGWIN32__)
       if (getenv("APPDATA") == NULL)
         {
-          cerr << "ERROR: APPDATA environment variable not found." << endl;
-          exit(EXIT_FAILURE);
+          if (parallel || parallel_test)
+            cerr << "ERROR: ";
+          else
+            cerr << "WARNING: ";
+          cerr << "APPDATA environment variable not found." << endl;
+
+          if (parallel || parallel_test)
+            exit(EXIT_FAILURE);
         }
-      string defaultConfigFile(getenv("APPDATA"));
-      defaultConfigFile += "\\dynare.ini";
-#else
-      if (getenv("HOME") == NULL)
+      else
         {
-          cerr << "ERROR: HOME environment variable not found." << endl;
-          exit(EXIT_FAILURE);
+          defaultConfigFile += getenv("APPDATA");
+          defaultConfigFile += "\\dynare.ini";
         }
-      string defaultConfigFile(getenv("HOME"));
-      defaultConfigFile += "/.dynare";
+#else
+        if (getenv("HOME") == NULL)
+          {
+            if (parallel || parallel_test)
+              cerr << "ERROR: ";
+            else
+              cerr << "WARNING: ";
+            cerr << "HOME environment variable not found." << endl;
+            if (parallel || parallel_test)
+              exit(EXIT_FAILURE);
+          }
+        else
+          {
+            defaultConfigFile += getenv("HOME");
+            defaultConfigFile += "/.dynare";
+          }
 #endif
-      configFile = new ifstream(defaultConfigFile.c_str(), fstream::in);
-      if (!configFile->is_open())
-        {
-          cerr << "ERROR: Could not open the default config file (" << defaultConfigFile << ")" << endl;
-          exit(EXIT_FAILURE);
-        }
-    }
-  else
-    {
-      configFile = new ifstream(parallel_config_file.c_str(), fstream::in);
-      if (!configFile->is_open())
-        {
-          cerr << "ERROR: Couldn't open file " << parallel_config_file << endl;;
-          exit(EXIT_FAILURE);
-        }
-    }
+        configFile = new ifstream(defaultConfigFile.c_str(), fstream::in);
+        if (!configFile->is_open())
+          if (parallel || parallel_test)
+            {
+              cerr << "ERROR: Could not open the default config file (" << defaultConfigFile << ")" << endl;
+              exit(EXIT_FAILURE);
+            }
+          else
+            return;
+      }
+    else
+      {
+        configFile = new ifstream(config_file.c_str(), fstream::in);
+        if (!configFile->is_open())
+          {
+            cerr << "ERROR: Couldn't open file " << config_file << endl;;
+            exit(EXIT_FAILURE);
+          }
+      }
+
 
   string name, computerName, port, userName, password, remoteDrive,
-    remoteDirectory, dynarePath, matlabOctavePath, operatingSystem;
+    remoteDirectory, dynarePath, matlabOctavePath, operatingSystem,
+    global_init_file;
   int minCpuNbr = 0, maxCpuNbr = 0;
   bool singleCompThread = true;
   member_nodes_t member_nodes;
 
+  bool inHooks = false;
   bool inNode = false;
   bool inCluster = false;
   while (configFile->good())
@@ -134,29 +166,43 @@ ConfigFile::getConfigFileInfo(const string &parallel_config_file)
       if (line.empty())
         continue;
 
-      if (!line.compare("[node]") || !line.compare("[cluster]"))
+      if (!line.compare("[node]") || !line.compare("[cluster]") || !line.compare("[hooks]"))
         {
-          addConfFileElement(inNode, inCluster, member_nodes, name,
-                             computerName, port, minCpuNbr, maxCpuNbr, userName,
-                             password, remoteDrive, remoteDirectory,
-                             dynarePath, matlabOctavePath, singleCompThread,
-                             operatingSystem);
+          if (!global_init_file.empty())
+            // we were just in [hooks]
+            addHooksConfFileElement(global_init_file);
+          else
+            // we were just in [node] or [cluster]
+            addParallelConfFileElement(inNode, inCluster, member_nodes, name,
+                                       computerName, port, minCpuNbr, maxCpuNbr, userName,
+                                       password, remoteDrive, remoteDirectory,
+                                       dynarePath, matlabOctavePath, singleCompThread,
+                                       operatingSystem);
 
           //! Reset communication vars / option defaults
-          if (!line.compare("[node]"))
+          if (!line.compare("[hooks]"))
             {
-              inNode = true;
+              inHooks = true;
+              inNode = false;
               inCluster = false;
             }
           else
-            {
-              inNode = false;
-              inCluster = true;
-            }
+            if (!line.compare("[node]"))
+              {
+                inHooks = false;
+                inNode = true;
+                inCluster = false;
+              }
+            else
+              {
+                inHooks = false;
+                inNode = false;
+                inCluster = true;
+              }
 
           name = userName = computerName = port = password = remoteDrive
             = remoteDirectory = dynarePath = matlabOctavePath
-            = operatingSystem = "";
+            = operatingSystem = global_init_file = "";
           minCpuNbr = maxCpuNbr = 0;
           singleCompThread = true;
           member_nodes.clear();
@@ -173,164 +219,194 @@ ConfigFile::getConfigFileInfo(const string &parallel_config_file)
           trim(tokenizedLine.front());
           trim(tokenizedLine.back());
 
-          if (!tokenizedLine.front().compare("Name"))
-            name = tokenizedLine.back();
-          else if (!tokenizedLine.front().compare("CPUnbr"))
-            {
-              vector<string> tokenizedCpuNbr;
-              split(tokenizedCpuNbr, tokenizedLine.back(), is_any_of(":"));
-              try
-                {
-                  if (tokenizedCpuNbr.size() == 1)
-                    {
-                      minCpuNbr = 1;
-                      maxCpuNbr = lexical_cast< int >(tokenizedCpuNbr.front());
-                    }
-                  else if (tokenizedCpuNbr.size() == 2
-                           && tokenizedCpuNbr[0].at(0) == '['
-                           && tokenizedCpuNbr[1].at(tokenizedCpuNbr[1].size()-1) == ']')
-                    {
-                      tokenizedCpuNbr[0].erase(0, 1);
-                      tokenizedCpuNbr[1].erase(tokenizedCpuNbr[1].size()-1, 1);
-                      minCpuNbr = lexical_cast< int >(tokenizedCpuNbr[0]);
-                      maxCpuNbr = lexical_cast< int >(tokenizedCpuNbr[1]);
-                    }
-                }
-              catch (const bad_lexical_cast &)
+          if (inHooks)
+            if (!tokenizedLine.front().compare("GlobalInitFile"))
+              if (global_init_file.empty())
+                global_init_file = tokenizedLine.back();
+              else
                 {
-                  cerr << "ERROR: Could not convert value to integer for CPUnbr." << endl;
+                  cerr << "ERROR: May not have more than one GlobalInitFile option in [hooks] block." << endl;
                   exit(EXIT_FAILURE);
                 }
-
-              if (minCpuNbr <= 0 || maxCpuNbr <= 0)
-                {
-                  cerr << "ERROR: Syntax for the CPUnbr option is as follows:" << endl
-                       << "       1) CPUnbr = <int>" << endl
-                       << "    or 2) CPUnbr = [<int>:<int>]" << endl
-                       << "       where <int> is an Integer > 0." << endl;
-                  exit(EXIT_FAILURE);
-                }
-
-              minCpuNbr--;
-              maxCpuNbr--;
-              if (minCpuNbr > maxCpuNbr)
-                {
-                  int tmp = maxCpuNbr;
-                  maxCpuNbr = minCpuNbr;
-                  minCpuNbr = tmp;
-                }
-            }
-          else if (!tokenizedLine.front().compare("Port"))
-            port = tokenizedLine.back();
-          else if (!tokenizedLine.front().compare("ComputerName"))
-            computerName = tokenizedLine.back();
-          else if (!tokenizedLine.front().compare("UserName"))
-            userName = tokenizedLine.back();
-          else if (!tokenizedLine.front().compare("Password"))
-            password = tokenizedLine.back();
-          else if (!tokenizedLine.front().compare("RemoteDrive"))
-            remoteDrive = tokenizedLine.back();
-          else if (!tokenizedLine.front().compare("RemoteDirectory"))
-            remoteDirectory = tokenizedLine.back();
-          else if (!tokenizedLine.front().compare("DynarePath"))
-            dynarePath = tokenizedLine.back();
-          else if (!tokenizedLine.front().compare("MatlabOctavePath"))
-            matlabOctavePath = tokenizedLine.back();
-          else if (!tokenizedLine.front().compare("SingleCompThread"))
-            if (tokenizedLine.back().compare("true") == 0)
-              singleCompThread = true;
-            else if (tokenizedLine.back().compare("false") == 0)
-              singleCompThread = false;
             else
               {
-                cerr << "ERROR (in config file): The value passed to SingleCompThread may only be 'true' or 'false'." << endl;
+                cerr << "ERROR: Unrecognized option " << tokenizedLine.front() << " in [hooks] block." << endl;
                 exit(EXIT_FAILURE);
               }
-          else if (!tokenizedLine.front().compare("OperatingSystem"))
-            operatingSystem = tokenizedLine.back();
-          else if (!tokenizedLine.front().compare("Members"))
-            {
-              char_separator<char> sep(" ,;", "()", drop_empty_tokens);
-              tokenizer<char_separator<char> > tokens(tokenizedLine.back(), sep);
-              bool begin_weight = false;
-              string node_name;
-              for (tokenizer<char_separator<char> >::iterator it = tokens.begin();
-                   it != tokens.end(); it++)
-                {
-                  string token (*it);
-                  if (token.compare("(") == 0)
-                    {
-                      begin_weight = true;
-                      continue;
-                    }
-                  else if (token.compare(")") == 0)
-                    {
-                      node_name.clear();
-                      begin_weight = false;
-                      continue;
-                    }
-
-                  if (!begin_weight)
-                    {
-                      if (!node_name.empty())
-                        if (member_nodes.find(node_name) != member_nodes.end())
-                          {
-                            cerr << "ERROR (in config file): Node entered twice in specification of cluster." << endl;
-                            exit(EXIT_FAILURE);
-                          }
-                        else
-                          member_nodes[node_name] = 1.0;
-                      node_name = token;
-                    }
-                  else
-                    try
+          else
+            if (!tokenizedLine.front().compare("Name"))
+              name = tokenizedLine.back();
+            else if (!tokenizedLine.front().compare("CPUnbr"))
+              {
+                vector<string> tokenizedCpuNbr;
+                split(tokenizedCpuNbr, tokenizedLine.back(), is_any_of(":"));
+                try
+                  {
+                    if (tokenizedCpuNbr.size() == 1)
                       {
-                        double weight = lexical_cast<double>(token.c_str());
-                        if (weight <= 0)
-                          {
-                            cerr << "ERROR (in config file): Misspecification of weights passed to Members option." << endl;
-                            exit(EXIT_FAILURE);
-                          }
-                        member_nodes[node_name] = weight;
+                        minCpuNbr = 1;
+                        maxCpuNbr = lexical_cast< int >(tokenizedCpuNbr.front());
                       }
-                    catch (bad_lexical_cast &)
+                    else if (tokenizedCpuNbr.size() == 2
+                             && tokenizedCpuNbr[0].at(0) == '['
+                             && tokenizedCpuNbr[1].at(tokenizedCpuNbr[1].size()-1) == ']')
                       {
-                        cerr << "ERROR (in config file): Misspecification of weights passed to Members option." << endl;
-                        exit(EXIT_FAILURE);
+                        tokenizedCpuNbr[0].erase(0, 1);
+                        tokenizedCpuNbr[1].erase(tokenizedCpuNbr[1].size()-1, 1);
+                        minCpuNbr = lexical_cast< int >(tokenizedCpuNbr[0]);
+                        maxCpuNbr = lexical_cast< int >(tokenizedCpuNbr[1]);
                       }
-                }
-              if (!node_name.empty())
-                if (member_nodes.find(node_name) == member_nodes.end())
-                  member_nodes[node_name] = 1.0;
-                else
+                  }
+                catch (const bad_lexical_cast &)
                   {
-                    cerr << "ERROR (in config file): Node entered twice in specification of cluster." << endl;
+                    cerr << "ERROR: Could not convert value to integer for CPUnbr." << endl;
                     exit(EXIT_FAILURE);
                   }
-            }
-          else
-            {
-              cerr << "ERROR (in config file): Option " << tokenizedLine.front() << " is invalid." << endl;
-              exit(EXIT_FAILURE);
-            }
+
+                if (minCpuNbr <= 0 || maxCpuNbr <= 0)
+                  {
+                    cerr << "ERROR: Syntax for the CPUnbr option is as follows:" << endl
+                         << "       1) CPUnbr = <int>" << endl
+                         << "    or 2) CPUnbr = [<int>:<int>]" << endl
+                         << "       where <int> is an Integer > 0." << endl;
+                    exit(EXIT_FAILURE);
+                  }
+
+                minCpuNbr--;
+                maxCpuNbr--;
+                if (minCpuNbr > maxCpuNbr)
+                  {
+                    int tmp = maxCpuNbr;
+                    maxCpuNbr = minCpuNbr;
+                    minCpuNbr = tmp;
+                  }
+              }
+            else if (!tokenizedLine.front().compare("Port"))
+              port = tokenizedLine.back();
+            else if (!tokenizedLine.front().compare("ComputerName"))
+              computerName = tokenizedLine.back();
+            else if (!tokenizedLine.front().compare("UserName"))
+              userName = tokenizedLine.back();
+            else if (!tokenizedLine.front().compare("Password"))
+              password = tokenizedLine.back();
+            else if (!tokenizedLine.front().compare("RemoteDrive"))
+              remoteDrive = tokenizedLine.back();
+            else if (!tokenizedLine.front().compare("RemoteDirectory"))
+              remoteDirectory = tokenizedLine.back();
+            else if (!tokenizedLine.front().compare("DynarePath"))
+              dynarePath = tokenizedLine.back();
+            else if (!tokenizedLine.front().compare("MatlabOctavePath"))
+              matlabOctavePath = tokenizedLine.back();
+            else if (!tokenizedLine.front().compare("SingleCompThread"))
+              if (tokenizedLine.back().compare("true") == 0)
+                singleCompThread = true;
+              else if (tokenizedLine.back().compare("false") == 0)
+                singleCompThread = false;
+              else
+                {
+                  cerr << "ERROR (in config file): The value passed to SingleCompThread may only be 'true' or 'false'." << endl;
+                  exit(EXIT_FAILURE);
+                }
+            else if (!tokenizedLine.front().compare("OperatingSystem"))
+              operatingSystem = tokenizedLine.back();
+            else if (!tokenizedLine.front().compare("Members"))
+              {
+                char_separator<char> sep(" ,;", "()", drop_empty_tokens);
+                tokenizer<char_separator<char> > tokens(tokenizedLine.back(), sep);
+                bool begin_weight = false;
+                string node_name;
+                for (tokenizer<char_separator<char> >::iterator it = tokens.begin();
+                     it != tokens.end(); it++)
+                  {
+                    string token (*it);
+                    if (token.compare("(") == 0)
+                      {
+                        begin_weight = true;
+                        continue;
+                      }
+                    else if (token.compare(")") == 0)
+                      {
+                        node_name.clear();
+                        begin_weight = false;
+                        continue;
+                      }
+
+                    if (!begin_weight)
+                      {
+                        if (!node_name.empty())
+                          if (member_nodes.find(node_name) != member_nodes.end())
+                            {
+                              cerr << "ERROR (in config file): Node entered twice in specification of cluster." << endl;
+                              exit(EXIT_FAILURE);
+                            }
+                          else
+                            member_nodes[node_name] = 1.0;
+                        node_name = token;
+                      }
+                    else
+                      try
+                        {
+                          double weight = lexical_cast<double>(token.c_str());
+                          if (weight <= 0)
+                            {
+                              cerr << "ERROR (in config file): Misspecification of weights passed to Members option." << endl;
+                              exit(EXIT_FAILURE);
+                            }
+                          member_nodes[node_name] = weight;
+                        }
+                      catch (bad_lexical_cast &)
+                        {
+                          cerr << "ERROR (in config file): Misspecification of weights passed to Members option." << endl;
+                          exit(EXIT_FAILURE);
+                        }
+                  }
+                if (!node_name.empty())
+                  if (member_nodes.find(node_name) == member_nodes.end())
+                    member_nodes[node_name] = 1.0;
+                  else
+                    {
+                      cerr << "ERROR (in config file): Node entered twice in specification of cluster." << endl;
+                      exit(EXIT_FAILURE);
+                    }
+              }
+            else
+              {
+                cerr << "ERROR (in config file): Option " << tokenizedLine.front() << " is invalid." << endl;
+                exit(EXIT_FAILURE);
+              }
         }
     }
 
-  addConfFileElement(inNode, inCluster, member_nodes, name,
-                     computerName, port, minCpuNbr, maxCpuNbr, userName,
-                     password, remoteDrive, remoteDirectory,
-                     dynarePath, matlabOctavePath, singleCompThread,
-                     operatingSystem);
+  if (!global_init_file.empty())
+    addHooksConfFileElement(global_init_file);
+  else
+    addParallelConfFileElement(inNode, inCluster, member_nodes, name,
+                               computerName, port, minCpuNbr, maxCpuNbr, userName,
+                               password, remoteDrive, remoteDirectory,
+                               dynarePath, matlabOctavePath, singleCompThread,
+                               operatingSystem);
   configFile->close();
   delete configFile;
 }
 
 void
-ConfigFile::addConfFileElement(bool inNode, bool inCluster, member_nodes_t member_nodes,
-                               string &name, string &computerName, string port, int minCpuNbr, int maxCpuNbr, string &userName,
-                               string &password, string &remoteDrive, string &remoteDirectory,
-                               string &dynarePath, string &matlabOctavePath, bool singleCompThread,
-                               string &operatingSystem)
+ConfigFile::addHooksConfFileElement(string &global_init_file)
+{
+  if (global_init_file.empty())
+    {
+      cerr << "ERROR: The global initialization file must be passed to the GlobalInitFile option." << endl;
+      exit(EXIT_FAILURE);
+    }
+  else
+    hooks.push_back(new Hook(global_init_file));
+}
+
+void
+ConfigFile::addParallelConfFileElement(bool inNode, bool inCluster, member_nodes_t member_nodes,
+                                       string &name, string &computerName, string port, int minCpuNbr, int maxCpuNbr, string &userName,
+                                       string &password, string &remoteDrive, string &remoteDirectory,
+                                       string &dynarePath, string &matlabOctavePath, bool singleCompThread,
+                                       string &operatingSystem)
 {
   //! ADD NODE
   if (inNode)
@@ -375,6 +451,21 @@ ConfigFile::addConfFileElement(bool inNode, bool inCluster, member_nodes_t membe
 void
 ConfigFile::checkPass(WarningConsolidation &warnings) const
 {
+  bool global_init_file_declared = false;
+  for (vector<Hook *>::const_iterator it = hooks.begin() ; it != hooks.end(); it++)
+    {
+      const map <string, string> hookmap = (*it)->get_hooks();
+      for (map <string, string>::const_iterator mapit = hookmap.begin() ; mapit != hookmap.end(); mapit++)
+        if (mapit->first.compare("global_init_file") == 0)
+          if (global_init_file_declared == true)
+            {
+              cerr << "ERROR: Only one global initialization file may be provided." << endl;
+              exit(EXIT_FAILURE);
+            }
+          else
+            global_init_file_declared = true;
+    }
+
   if (!parallel && !parallel_test)
     return;
 
@@ -502,6 +593,17 @@ ConfigFile::transformPass()
     it->second /= weight_denominator;
 }
 
+void
+ConfigFile::writeHooks(ostream &output) const
+{
+  for (vector<Hook *>::const_iterator it = hooks.begin() ; it != hooks.end(); it++)
+    {
+      map <string, string> hookmap = (*it)->get_hooks();
+      for (map <string, string>::const_iterator mapit = hookmap.begin() ; mapit != hookmap.end(); mapit++)
+        output << "options_." << mapit->first << " = '" << mapit->second << "';" << endl;
+    }
+}
+
 void
 ConfigFile::writeCluster(ostream &output) const
 {
diff --git a/preprocessor/ConfigFile.hh b/preprocessor/ConfigFile.hh
index 332e351f399089be9e2495f44379dfd972cccc4b..c7dd85ef519b0f49bd5d271a209fffa21e6315e6 100644
--- a/preprocessor/ConfigFile.hh
+++ b/preprocessor/ConfigFile.hh
@@ -29,6 +29,16 @@ using namespace std;
 
 typedef map<string, double> member_nodes_t;
 
+class Hook
+{
+public:
+  Hook(string &global_init_file_arg);
+  ~Hook();
+private:
+  map<string, string> hooks;
+public:
+  inline map<string, string>get_hooks() { return hooks; };
+};
 
 class SlaveNode
 {
@@ -79,16 +89,20 @@ private:
   const bool parallel_slave_open_mode;
   const string cluster_name;
   string firstClusterName;
+  //! Hooks
+  vector<Hook *> hooks;
   //! Cluster Table
   map<string, Cluster *> clusters;
   //! Node Map
   map<string, SlaveNode *> slave_nodes;
+  //! Add Hooks
+  void addHooksConfFileElement(string &global_init_file);
   //! Add a SlaveNode or a Cluster object
-  void addConfFileElement(bool inNode, bool inCluster, member_nodes_t member_nodes, string &name,
-                          string &computerName, string port, int minCpuNbr, int maxCpuNbr, string &userName,
-                          string &password, string &remoteDrive, string &remoteDirectory,
-                          string &dynarePath, string &matlabOctavePath, bool singleCompThread,
-                          string &operatingSystem);
+  void addParallelConfFileElement(bool inNode, bool inCluster, member_nodes_t member_nodes, string &name,
+                                  string &computerName, string port, int minCpuNbr, int maxCpuNbr, string &userName,
+                                  string &password, string &remoteDrive, string &remoteDirectory,
+                                  string &dynarePath, string &matlabOctavePath, bool singleCompThread,
+                                  string &operatingSystem);
 public:
   //! Parse config file
   void getConfigFileInfo(const string &parallel_config_file);
@@ -96,6 +110,8 @@ public:
   void checkPass(WarningConsolidation &warnings) const;
   //! Check Pass
   void transformPass();
+  //! Write any hooks
+  void writeHooks(ostream &output) const;
   //! Create options_.parallel structure, write options
   void writeCluster(ostream &output) const;
   //! Close slave nodes if needed
diff --git a/preprocessor/DataTree.cc b/preprocessor/DataTree.cc
index 359470af68f9e2a13d055defa4b3055f25f2b409..629365fbd004bd2d3d39d11d8c39186d3f771e95 100644
--- a/preprocessor/DataTree.cc
+++ b/preprocessor/DataTree.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2011 Dynare Team
+ * Copyright (C) 2003-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -51,7 +51,7 @@ DataTree::~DataTree()
 }
 
 expr_t
-DataTree::AddNonNegativeConstant(const string &value) throw (NumericalConstants::InvalidFloatingPointNumberException)
+DataTree::AddNonNegativeConstant(const string &value)
 {
   int id = num_constants.AddNonNegativeConstant(value);
 
diff --git a/preprocessor/DataTree.hh b/preprocessor/DataTree.hh
index e616f9cfef86347f4c79b98a97d5ac94bb229833..17823d23f0c313ac84cfd307ef992338f4dbff55 100644
--- a/preprocessor/DataTree.hh
+++ b/preprocessor/DataTree.hh
@@ -110,7 +110,7 @@ public:
   };
 
   //! Adds a non-negative numerical constant (possibly Inf or NaN)
-  expr_t AddNonNegativeConstant(const string &value) throw (NumericalConstants::InvalidFloatingPointNumberException);
+  expr_t AddNonNegativeConstant(const string &value);
   //! Adds a variable
   /*! The default implementation of the method refuses any lag != 0 */
   virtual VariableNode *AddVariable(int symb_id, int lag = 0);
diff --git a/preprocessor/DynamicModel.cc b/preprocessor/DynamicModel.cc
index 65baedeb502850146c40bc98a1b0f1afa3a829cc..c4a6b0331acc73027163afa06fa74f1fcb1c8a7c 100644
--- a/preprocessor/DynamicModel.cc
+++ b/preprocessor/DynamicModel.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2011 Dynare Team
+ * Copyright (C) 2003-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -1910,7 +1910,7 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri
               mDynamicModelFile << "  g1=[];g2=[];g3=[];\n";
               mDynamicModelFile << "  y=" << dynamic_basename << "_" << block + 1 << "(y, x, params, steady_state, 0, y_kmin, periods);\n";
               mDynamicModelFile << "  tmp = y(:,M_.block_structure.block(" << block + 1 << ").variable);\n";
-              mDynamicModelFile << "  if(isnan(tmp) | isinf(tmp))\n";
+              mDynamicModelFile << "  if any(isnan(tmp) | isinf(tmp))\n";
               mDynamicModelFile << "    disp(['Inf or Nan value during the evaluation of block " << block <<"']);\n";
               mDynamicModelFile << "    return;\n";
               mDynamicModelFile << "  end;\n";
@@ -1938,7 +1938,7 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri
               mDynamicModelFile << "  g1=[];g2=[];g3=[];\n";
               mDynamicModelFile << "  " << dynamic_basename << "_" << block + 1 << "(y, x, params, steady_state, 0, y_kmin, periods);\n";
               mDynamicModelFile << "  tmp = y(:,M_.block_structure.block(" << block + 1 << ").variable);\n";
-              mDynamicModelFile << "  if(isnan(tmp) | isinf(tmp))\n";
+              mDynamicModelFile << "  if any(isnan(tmp) | isinf(tmp))\n";
               mDynamicModelFile << "    disp(['Inf or Nan value during the evaluation of block " << block <<"']);\n";
               mDynamicModelFile << "    return;\n";
               mDynamicModelFile << "  end;\n";
@@ -1968,7 +1968,7 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri
                             <<", options_.periods, " << blocks_linear[block]
                             <<", blck_num, y_kmin, options_.maxit_, options_.solve_tolf, options_.slowc, " << cutoff << ", options_.stack_solve_algo, 1, 1, 0);\n";
           mDynamicModelFile << "  tmp = y(:,M_.block_structure.block(" << block + 1 << ").variable);\n";
-          mDynamicModelFile << "  if(isnan(tmp) | isinf(tmp))\n";
+          mDynamicModelFile << "  if any(isnan(tmp) | isinf(tmp))\n";
           mDynamicModelFile << "    disp(['Inf or Nan value during the resolution of block " << block <<"']);\n";
           mDynamicModelFile << "    return;\n";
           mDynamicModelFile << "  end;\n";
@@ -1998,7 +1998,7 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri
                             <<", options_.periods, " << blocks_linear[block]
                             <<", blck_num, y_kmin, options_.maxit_, options_.solve_tolf, options_.slowc, " << cutoff << ", options_.stack_solve_algo, 1, 1, 0);\n";
           mDynamicModelFile << "  tmp = y(:,M_.block_structure.block(" << block + 1 << ").variable);\n";
-          mDynamicModelFile << "  if(isnan(tmp) | isinf(tmp))\n";
+          mDynamicModelFile << "  if any(isnan(tmp) | isinf(tmp))\n";
           mDynamicModelFile << "    disp(['Inf or Nan value during the resolution of block " << block <<"']);\n";
           mDynamicModelFile << "    return;\n";
           mDynamicModelFile << "  end;\n";
@@ -2028,7 +2028,7 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri
                             <<", " << blocks_linear[block]
                             <<", blck_num, y_kmin, options_.maxit_, options_.solve_tolf, options_.slowc, " << cutoff << ", options_.stack_solve_algo);\n";
           mDynamicModelFile << "  tmp = y(:,M_.block_structure.block(" << block + 1 << ").variable);\n";
-          mDynamicModelFile << "  if(isnan(tmp) | isinf(tmp))\n";
+          mDynamicModelFile << "  if any(isnan(tmp) | isinf(tmp))\n";
           mDynamicModelFile << "    disp(['Inf or Nan value during the resolution of block " << block <<"']);\n";
           mDynamicModelFile << "    return;\n";
           mDynamicModelFile << "  end;\n";
@@ -2665,7 +2665,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de
             i_nz_state_var[i] = n;
           unsigned int lp = n_obs;
 
-          for (int block = 0;  block < nb_blocks; block++)
+          for (unsigned int block = 0;  block < nb_blocks; block++)
             {
               int block_size = getBlockSize(block);
               int nze = 0;
@@ -2744,7 +2744,7 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de
               lp += nze; 
             }
           output << "M_.nz_state_var = [";
-          for (int i = 0; i < lp; i++)
+          for (unsigned int i = 0; i < lp; i++)
             output << i_nz_state_var[i] << " ";
           output << "];" << endl;
           output << "M_.n_diag = " << nb_diag << ";" << endl;
diff --git a/preprocessor/DynamicModel.hh b/preprocessor/DynamicModel.hh
index 18a5f7e65862d655a2e2f5b936fa80c27aa30ad2..6f416f93a096f1a0fbdad71a65ee2c7489cb0d26 100644
--- a/preprocessor/DynamicModel.hh
+++ b/preprocessor/DynamicModel.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2011 Dynare Team
+ * Copyright (C) 2003-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/preprocessor/DynareBison.yy b/preprocessor/DynareBison.yy
index 179b6f38ea7f8e1eed067fa67061b36ec5a8b5f1..2ee59d06204e90b9c120105275e9dfa797abc5e2 100644
--- a/preprocessor/DynareBison.yy
+++ b/preprocessor/DynareBison.yy
@@ -89,20 +89,20 @@ class ParsingDriver;
 #define yylex driver.lexer->lex
 %}
 
-%token AIM_SOLVER AR AUTOCORR
+%token AIM_SOLVER ANALYTIC_DERIVATION AR AUTOCORR
 %token BAYESIAN_IRF BETA_PDF BLOCK
 %token BVAR_DENSITY BVAR_FORECAST
 %token BVAR_PRIOR_DECAY BVAR_PRIOR_FLAT BVAR_PRIOR_LAMBDA
 %token BVAR_PRIOR_MU BVAR_PRIOR_OMEGA BVAR_PRIOR_TAU BVAR_PRIOR_TRAIN
 %token BVAR_REPLIC BYTECODE
-%token CALIB_SMOOTHER CHANGE_TYPE CHECK CONDITIONAL_FORECAST CONDITIONAL_FORECAST_PATHS CONF_SIG CONSTANT CONTROLLED_VAREXO CORR COVAR CUTOFF
-%token DATAFILE FILE DOUBLING DR_ALGO DROP DSAMPLE DYNASAVE DYNATYPE CALIBRATION
-%token END ENDVAL EQUAL ESTIMATION ESTIMATED_PARAMS ESTIMATED_PARAMS_BOUNDS ESTIMATED_PARAMS_INIT
+%token CALIB_SMOOTHER CHANGE_TYPE CHECK CONDITIONAL_FORECAST CONDITIONAL_FORECAST_PATHS CONF_SIG CONSTANT CONTROLLED_VAREXO CORR COVAR CUTOFF CYCLE_REDUCTION LOGARITHMIC_REDUCTION
+%token DATAFILE FILE DOUBLING DR_CYCLE_REDUCTION_TOL DR_LOGARITHMIC_REDUCTION_TOL DR_LOGARITHMIC_REDUCTION_MAXITER DR_ALGO DROP DSAMPLE DYNASAVE DYNATYPE CALIBRATION
+%token END ENDVAL EQUAL ESTIMATION ESTIMATED_PARAMS ESTIMATED_PARAMS_BOUNDS ESTIMATED_PARAMS_INIT EXTENDED_PATH
 %token FILENAME FILTER_STEP_AHEAD FILTERED_VARS FIRST_OBS LAST_OBS SET_TIME
 %token <string_val> FLOAT_NUMBER
 %token DEFAULT FIXED_POINT
 %token FORECAST K_ORDER_SOLVER INSTRUMENTS PRIOR SHIFT MEAN STDEV VARIANCE MODE INTERVAL SHAPE DOMAINN
-%token GAMMA_PDF GRAPH CONDITIONAL_VARIANCE_DECOMPOSITION NOCHECK TRANSFORM_LOGPOW STD
+%token GAMMA_PDF GRAPH GRAPH_FORMAT CONDITIONAL_VARIANCE_DECOMPOSITION NOCHECK TRANSFORM_LOGPOW STD
 %token HISTVAL HOMOTOPY_SETUP HOMOTOPY_MODE HOMOTOPY_STEPS HOMOTOPY_FORCE_CONTINUE HP_FILTER HP_NGRID
 %token IDENTIFICATION INF_CONSTANT INITVAL INITVAL_FILE BOUNDS JSCALE INIT
 %token <string_val> INT_NUMBER
@@ -111,19 +111,19 @@ class ParsingDriver;
 %token KALMAN_ALGO KALMAN_TOL SUBSAMPLES OPTIONS
 %token LABELS LAPLACE LIK_ALGO LIK_INIT LINEAR LOAD_IDENT_FILES LOAD_MH_FILE LOAD_PARAMS_AND_STEADY_STATE LOGLINEAR LYAPUNOV
 %token LYAPUNOV_FIXED_POINT_TOL LYAPUNOV_DOUBLING_TOL LYAPUNOV_SQUARE_ROOT_SOLVER_TOL MARKOWITZ MARGINAL_DENSITY MAX MAXIT
-%token MFS MH_DROP MH_INIT_SCALE MH_JSCALE MH_MODE MH_NBLOCKS MH_REPLIC MH_RECOVER MIN MINIMAL_SOLVING_PERIODS
+%token MFS MH_DROP MH_INIT_SCALE MH_JSCALE MH_MODE MH_NBLOCKS MH_REPLIC MH_RECOVER MIN MINIMAL_SOLVING_PERIODS SOLVE_MAXIT
 %token MODE_CHECK MODE_COMPUTE MODE_FILE MODEL MODEL_COMPARISON MODEL_INFO MSHOCKS ABS SIGN
 %token MODIFIEDHARMONICMEAN MOMENTS_VARENDO DIFFUSE_FILTER SUB_DRAWS
 %token <string_val> NAME
-%token NAN_CONSTANT NO_STATIC NOBS NOCONSTANT NOCORR NODIAGNOSTIC NOFUNCTIONS
+%token NAN_CONSTANT NO_STATIC NOBS NOCONSTANT NODISPLAY NOCORR NODIAGNOSTIC NOFUNCTIONS
 %token NOGRAPH NOMOMENTS NOPRINT NORMAL_PDF
 %token OBSERVATION_TRENDS OPTIM OPTIM_WEIGHTS ORDER OSR OSR_PARAMS MAX_DIM_COVA_GROUP ADVANCED
 %token PARAMETERS PARAMETER_SET PARTIAL_INFORMATION PERIODS PLANNER_OBJECTIVE PLOT_CONDITIONAL_FORECAST PLOT_PRIORS PREFILTER PRESAMPLE
 %token PRINT PRIOR_MC PRIOR_TRUNC PRIOR_MODE PRIOR_MEAN POSTERIOR_MODE POSTERIOR_MEAN POSTERIOR_MEDIAN PRUNING
 %token <string_val> QUOTED_STRING
 %token QZ_CRITERIUM FULL DSGE_VAR DSGE_VARLAG DSGE_PRIOR_WEIGHT TRUNCATE
-%token RELATIVE_IRF REPLIC RPLOT SAVE_PARAMS_AND_STEADY_STATE PARAMETER_UNCERTAINTY
-%token SHOCKS SHOCK_DECOMPOSITION SIGMA_E SIMUL SIMUL_ALGO SIMUL_SEED SMOOTHER SQUARE_ROOT_SOLVER STACK_SOLVE_ALGO STEADY_STATE_MODEL SOLVE_ALGO
+%token RELATIVE_IRF REPLIC SIMUL_REPLIC RPLOT SAVE_PARAMS_AND_STEADY_STATE PARAMETER_UNCERTAINTY
+%token SHOCKS SHOCK_DECOMPOSITION SIGMA_E SIMUL SIMUL_ALGO SIMUL_SEED SMOOTHER SQUARE_ROOT_SOLVER STACK_SOLVE_ALGO STEADY_STATE_MODEL SOLVE_ALGO SOLVER_PERIODS
 %token STDERR STEADY STOCH_SIMUL SYLVESTER SYLVESTER_FIXED_POINT_TOL REGIMES REGIME
 %token TEX RAMSEY_POLICY PLANNER_DISCOUNT DISCRETIONARY_POLICY DISCRETIONARY_TOL
 %token <string_val> TEX_NAME
@@ -150,7 +150,7 @@ class ParsingDriver;
 %token VLISTLOG VLISTPER
 %token RESTRICTION RESTRICTION_FNAME CROSS_RESTRICTIONS NLAGS CONTEMP_REDUCED_FORM REAL_PSEUDO_FORECAST
 %token NONE DUMMY_OBS NSTATES INDXSCALESSTATES NO_BAYESIAN_PRIOR SPECIFICATION SIMS_ZHA
-%token <string_val> ALPHA BETA ABAND NINV CMS NCMS CNUM GAMMA INV_GAMMA INV_GAMMA1 INV_GAMMA2 NORMAL UNIFORM
+%token <string_val> ALPHA BETA ABAND NINV CMS NCMS CNUM GAMMA INV_GAMMA INV_GAMMA1 INV_GAMMA2 NORMAL UNIFORM EPS PDF FIG DR
 %token GSIG2_LMDM Q_DIAG FLAT_PRIOR NCSK NSTD
 %token INDXPARR INDXOVR INDXAP APBAND INDXIMF IMFBAND INDXFORE FOREBAND INDXGFOREHAT INDXGIMFHAT
 %token INDXESTIMA INDXGDLS EQ_MS FILTER_COVARIANCE FILTER_DECOMPOSITION
@@ -269,6 +269,7 @@ statement : parameters
           | ms_irf
           | ms_variance_decomposition
           | calib_smoother
+          | extended_path
           ;
 
 dsample : DSAMPLE INT_NUMBER ';'
@@ -915,6 +916,8 @@ stoch_simul_options : o_dr_algo
                     | o_nofunctions
                     | o_nomoments
                     | o_nograph
+                    | o_nodisplay
+                    | o_graph_format
                     | o_irf
                     | o_irf_shocks
                     | o_relative_irf
@@ -923,6 +926,7 @@ stoch_simul_options : o_dr_algo
                     | o_periods
                     | o_simul
                     | o_simul_seed
+                    | o_simul_replic
                     | o_qz_criterium
                     | o_print
                     | o_noprint
@@ -933,6 +937,10 @@ stoch_simul_options : o_dr_algo
                     | o_pruning
                     | o_sylvester
                     | o_sylvester_fixed_point_tol
+                    | o_dr
+                    | o_dr_cycle_reduction_tol
+                    | o_dr_logarithmic_reduction_tol
+                    | o_dr_logarithmic_reduction_maxiter
                     ;
 
 symbol_list : symbol_list symbol
@@ -1448,6 +1456,8 @@ estimation_options : o_datafile
                    | o_lik_algo
                    | o_lik_init
                    | o_nograph
+                   | o_nodisplay
+                   | o_graph_format
                    | o_conf_sig
                    | o_mh_replic
                    | o_mh_drop
@@ -1498,6 +1508,11 @@ estimation_options : o_datafile
                    | o_lyapunov
                    | o_lyapunov_fixed_point_tol
                    | o_lyapunov_doubling_tol
+                   | o_dr
+                   | o_dr_cycle_reduction_tol
+                   | o_dr_logarithmic_reduction_tol
+                   | o_dr_logarithmic_reduction_maxiter
+                   | o_analytic_derivation
                    ;
 
 list_optim_option : QUOTED_STRING COMMA QUOTED_STRING
@@ -1597,6 +1612,9 @@ identification_option : o_ar
                       | o_parameter_set
                       | o_lik_init
                       | o_kalman_algo
+                      | o_nograph
+                      | o_nodisplay
+                      | o_graph_format
                       ;
 
 model_comparison : MODEL_COMPARISON mc_filename_list ';'
@@ -1652,6 +1670,7 @@ discretionary_policy_options_list : discretionary_policy_options_list COMMA disc
 
 discretionary_policy_options : ramsey_policy_options 
                              | o_discretionary_tol;
+                             | o_solve_maxit;
                              ;
 
 ramsey_policy_options_list : ramsey_policy_options_list COMMA ramsey_policy_options
@@ -2019,6 +2038,8 @@ dynare_sensitivity_option : o_gsa_identification
                           | o_prefilter
                           | o_presample
                           | o_nograph
+                          | o_nodisplay
+                          | o_graph_format
                           | o_conf_sig
                           | o_loglinear
                           | o_mode_file
@@ -2065,6 +2086,8 @@ forecast_options: forecast_option
 forecast_option: o_periods
           | o_conf_sig
           | o_nograph
+          | o_nodisplay
+          | o_graph_format
           ;
 
 conditional_forecast : CONDITIONAL_FORECAST '(' conditional_forecast_options ')' ';'
@@ -2133,6 +2156,20 @@ calib_smoother_option : o_filtered_vars
                       | o_datafile
                       ;
 
+extended_path : EXTENDED_PATH ';'
+                { driver.extended_path(); }
+              | EXTENDED_PATH '(' extended_path_options_list ')' ';'            
+                { driver.extended_path(); }
+              ;
+
+extended_path_options_list : extended_path_option COMMA extended_path_options_list
+                           | extended_path_option
+                           ;
+
+extended_path_option : o_periods
+                     | o_solver_periods
+                     ;
+
 o_dr_algo : DR_ALGO EQUAL INT_NUMBER {
                                        if (*$3 == string("0"))
                                          driver.warning("dr_algo option is now deprecated, and may be removed in a future version of Dynare");
@@ -2160,12 +2197,15 @@ o_irf_shocks : IRF_SHOCKS EQUAL '(' symbol_list ')' { driver.option_symbol_list(
 o_hp_filter : HP_FILTER EQUAL non_negative_number { driver.option_num("hp_filter", $3); };
 o_hp_ngrid : HP_NGRID EQUAL INT_NUMBER { driver.option_num("hp_ngrid", $3); };
 o_periods : PERIODS EQUAL INT_NUMBER { driver.option_num("periods", $3); };
+o_solver_periods : SOLVER_PERIODS EQUAL INT_NUMBER { driver.option_num("solver_periods", $3); };
 o_maxit : MAXIT EQUAL INT_NUMBER { driver.option_num("maxit_", $3); };
+o_solve_maxit : SOLVE_MAXIT EQUAL INT_NUMBER { driver.option_num("solve_maxit", $3); };
 o_cutoff : CUTOFF EQUAL non_negative_number { driver.cutoff($3); };
 o_markowitz : MARKOWITZ EQUAL non_negative_number { driver.option_num("markowitz", $3); };
 o_minimal_solving_periods : MINIMAL_SOLVING_PERIODS EQUAL non_negative_number { driver.option_num("minimal_solving_periods", $3); };
 o_mfs : MFS EQUAL INT_NUMBER { driver.mfs($3); };
 o_simul : SIMUL; // Do nothing, only here for backward compatibility
+o_simul_replic : SIMUL_REPLIC EQUAL INT_NUMBER { driver.option_num("simul_replic", $3); };
 o_simul_seed : SIMUL_SEED EQUAL INT_NUMBER { driver.error("'simul_seed' option is no longer supported; use 'set_dynare_seed' command instead"); } ;
 o_qz_criterium : QZ_CRITERIUM EQUAL non_negative_number { driver.option_num("qz_criterium", $3); };
 o_file : FILE EQUAL filename { driver.option_str("file", $3); };
@@ -2205,10 +2245,18 @@ o_presample : PRESAMPLE EQUAL INT_NUMBER { driver.option_num("presample", $3); }
 o_lik_algo : LIK_ALGO EQUAL INT_NUMBER { driver.option_num("lik_algo", $3); };
 o_lik_init : LIK_INIT EQUAL INT_NUMBER { driver.option_num("lik_init", $3); };
 o_nograph : NOGRAPH
-            { driver.option_num("nograph","1"); };
+            { driver.option_num("nograph","1"); }
           | GRAPH
             { driver.option_num("nograph", "0"); }
           ;
+o_nodisplay : NODISPLAY { driver.option_num("nodisplay","1"); };
+o_graph_format : GRAPH_FORMAT EQUAL EPS
+                { driver.option_str("graph_format", "eps"); }
+               | GRAPH_FORMAT EQUAL FIG
+                { driver.option_str("graph_format", "fig"); }
+               | GRAPH_FORMAT EQUAL PDF
+                { driver.option_str("graph_format", "pdf"); }
+               ;
 o_subsample_name : symbol EQUAL date_number ':' date_number
                    { driver.set_subsample_name_equal_to_date_range($1, $3, $5); }
                  ;
@@ -2273,6 +2321,12 @@ o_lyapunov : LYAPUNOV EQUAL FIXED_POINT {driver.option_num("lyapunov_fp", "1");
               | LYAPUNOV EQUAL DEFAULT {driver.option_num("lyapunov_fp", "0");driver.option_num("lyapunov_db", "0"); driver.option_num("lyapunov_srs", "0");};
 o_lyapunov_fixed_point_tol : LYAPUNOV_FIXED_POINT_TOL EQUAL non_negative_number {driver.option_num("lyapunov_fixed_point_tol",$3);};
 o_lyapunov_doubling_tol : LYAPUNOV_DOUBLING_TOL EQUAL non_negative_number {driver.option_num("lyapunov_doubling_tol",$3);};
+o_dr : DR EQUAL CYCLE_REDUCTION {driver.option_num("dr_cycle_reduction", "1"); }
+       | DR EQUAL LOGARITHMIC_REDUCTION {driver.option_num("dr_logarithmic_reduction", "1"); }
+       | DR EQUAL DEFAULT {driver.option_num("dr_cycle_reduction", "0"); driver.option_num("dr_logarithmic_reduction", "0");};
+o_dr_cycle_reduction_tol : DR_CYCLE_REDUCTION_TOL EQUAL non_negative_number {driver.option_num("dr_cycle_reduction_tol",$3);};
+o_dr_logarithmic_reduction_tol : DR_LOGARITHMIC_REDUCTION_TOL EQUAL non_negative_number {driver.option_num("dr_logarithmic_reduction_tol",$3);};
+o_dr_logarithmic_reduction_maxiter : DR_LOGARITHMIC_REDUCTION_MAXITER EQUAL INT_NUMBER {driver.option_num("dr_logarithmic_reduction_maxiter",$3);};
 
 o_bvar_prior_tau : BVAR_PRIOR_TAU EQUAL signed_number { driver.option_num("bvar_prior_tau", $3); };
 o_bvar_prior_decay : BVAR_PRIOR_DECAY EQUAL non_negative_number { driver.option_num("bvar_prior_decay", $3); };
@@ -2525,6 +2579,7 @@ o_regimes : REGIMES { driver.option_num("ms.regimes","1"); };
 o_regime : REGIME EQUAL INT_NUMBER { driver.option_num("ms.regime",$3); };
 o_data_obs_nbr : DATA_OBS_NBR EQUAL INT_NUMBER { driver.option_num("ms.forecast_data_obs",$3); };
 o_discretionary_tol: DISCRETIONARY_TOL EQUAL non_negative_number { driver.option_num("discretionary_tol",$3); };
+o_analytic_derivation : ANALYTIC_DERIVATION { driver.option_num("analytic_derivation", "1"); }
 
 range : symbol ':' symbol
         {
@@ -2638,6 +2693,10 @@ symbol : NAME
        | INV_GAMMA2
        | NORMAL
        | UNIFORM
+       | EPS
+       | PDF
+       | FIG
+       | DR
        ;
 %%
 
@@ -2647,9 +2706,3 @@ Dynare::parser::error(const Dynare::parser::location_type &l,
 {
   driver.error(l, m);
 }
-
-/*
-  Local variables:
-  mode: C++
-  End:
-*/
diff --git a/preprocessor/DynareFlex.ll b/preprocessor/DynareFlex.ll
index 39adb4bfbb9fc0eebb377985315b0eda17cd1c5c..28d72ad0a87635c5529ec20a49d216ced2babcdf 100644
--- a/preprocessor/DynareFlex.ll
+++ b/preprocessor/DynareFlex.ll
@@ -183,6 +183,7 @@ string eofbuff;
 <INITIAL>homotopy_setup {BEGIN DYNARE_BLOCK; return token::HOMOTOPY_SETUP;}
 <INITIAL>conditional_forecast_paths {BEGIN DYNARE_BLOCK; return token::CONDITIONAL_FORECAST_PATHS;}
 <INITIAL>svar_identification {BEGIN DYNARE_BLOCK; return token::SVAR_IDENTIFICATION;}
+<INITIAL>extended_path {BEGIN DYNARE_BLOCK; return token::EXTENDED_PATH;}
 
  /* For the semicolon after an "end" keyword */
 <INITIAL>; {return Dynare::parser::token_type (yytext[0]);}
@@ -220,6 +221,11 @@ string eofbuff;
 <DYNARE_STATEMENT>lik_init  		{return token::LIK_INIT;}
 <DYNARE_STATEMENT>graph   		{return token::GRAPH;}
 <DYNARE_STATEMENT>nograph   		{return token::NOGRAPH;}
+<DYNARE_STATEMENT>nodisplay     {return token::NODISPLAY;}
+<DYNARE_STATEMENT>graph_format  {return token::GRAPH_FORMAT;}
+<DYNARE_STATEMENT>eps  {yylval->string_val = new string(yytext); return token::EPS;}
+<DYNARE_STATEMENT>pdf  {yylval->string_val = new string(yytext); return token::PDF;}
+<DYNARE_STATEMENT>fig  {yylval->string_val = new string(yytext); return token::FIG;}
 <DYNARE_STATEMENT>print   		{return token::PRINT;}
 <DYNARE_STATEMENT>noprint   		{return token::NOPRINT;}
 <DYNARE_STATEMENT>conf_sig  		{return token::CONF_SIG;}
@@ -296,6 +302,8 @@ string eofbuff;
 <DYNARE_STATEMENT>fixed_point {return token::FIXED_POINT;}
 <DYNARE_STATEMENT>doubling {return token::DOUBLING;}
 <DYNARE_STATEMENT>square_root_solver {return token::SQUARE_ROOT_SOLVER;}
+<DYNARE_STATEMENT>cycle_reduction {return token::CYCLE_REDUCTION;}
+<DYNARE_STATEMENT>logarithmic_reduction {return token::LOGARITHMIC_REDUCTION;}
 <DYNARE_STATEMENT>default {return token::DEFAULT;}
 <DYNARE_STATEMENT>alpha {
   yylval->string_val = new string(yytext);
@@ -408,6 +416,7 @@ string eofbuff;
 <DYNARE_STATEMENT>max_block_iterations {return token::MAX_BLOCK_ITERATIONS;}
 <DYNARE_STATEMENT>max_repeated_optimization_runs {return token::MAX_REPEATED_OPTIMIZATION_RUNS;}
 <DYNARE_STATEMENT>maxit {return token::MAXIT;}
+<DYNARE_STATEMENT>solve_maxit {return token::SOLVE_MAXIT;}
 <DYNARE_STATEMENT>function_convergence_criterion {return token::FUNCTION_CONVERGENCE_CRITERION;}
 <DYNARE_STATEMENT>parameter_convergence_criterion {return token::PARAMETER_CONVERGENCE_CRITERION;}
 <DYNARE_STATEMENT>number_of_large_perturbations {return token::NUMBER_OF_LARGE_PERTURBATIONS;}
@@ -457,6 +466,8 @@ string eofbuff;
 <DYNARE_STATEMENT>growth_factor {return token::GROWTH_FACTOR;}
 <DYNARE_STATEMENT>cova_compute {return token::COVA_COMPUTE;}
 <DYNARE_STATEMENT>discretionary_tol {return token::DISCRETIONARY_TOL;}
+<DYNARE_STATEMENT>analytic_derivation {return token::ANALYTIC_DERIVATION;}
+<DYNARE_STATEMENT>solver_periods {return token::SOLVER_PERIODS;}
 
 <DYNARE_STATEMENT>[\$][^$]*[\$] {
   strtok(yytext+1, "$");
@@ -496,9 +507,16 @@ string eofbuff;
 <DYNARE_STATEMENT>order {return token::ORDER;}
 <DYNARE_STATEMENT>sylvester {return token::SYLVESTER;}
 <DYNARE_STATEMENT>lyapunov {return token::LYAPUNOV;}
+<DYNARE_STATEMENT>dr {
+  yylval->string_val = new string(yytext);
+  return token::DR;
+ }
 <DYNARE_STATEMENT>sylvester_fixed_point_tol {return token::SYLVESTER_FIXED_POINT_TOL;}
 <DYNARE_STATEMENT>lyapunov_fixed_point_tol {return token::LYAPUNOV_FIXED_POINT_TOL;}
 <DYNARE_STATEMENT>lyapunov_doubling_tol {return token::LYAPUNOV_DOUBLING_TOL;}
+<DYNARE_STATEMENT>dr_cycle_reduction_tol {return token::DR_CYCLE_REDUCTION_TOL;}
+<DYNARE_STATEMENT>dr_logarithmic_reduction_tol {return token::DR_LOGARITHMIC_REDUCTION_TOL;}
+<DYNARE_STATEMENT>dr_logarithmic_reduction_maxiter {return token::DR_LOGARITHMIC_REDUCTION_MAXITER;}
 <DYNARE_STATEMENT>replic {return token::REPLIC;}
 <DYNARE_STATEMENT>ar {return token::AR;}
 <DYNARE_STATEMENT>nofunctions {return token::NOFUNCTIONS;}
@@ -509,6 +527,7 @@ string eofbuff;
 <DYNARE_STATEMENT>simul_seed {return token::SIMUL_SEED;}
 <DYNARE_STATEMENT>qz_criterium {return token::QZ_CRITERIUM;}
 <DYNARE_STATEMENT>simul {return token::SIMUL;}
+<DYNARE_STATEMENT>simul_replic {return token::SIMUL_REPLIC;}
 <DYNARE_STATEMENT>xls_sheet {return token::XLS_SHEET;}
 <DYNARE_STATEMENT>xls_range {return token::XLS_RANGE;}
 <DYNARE_STATEMENT>mh_recover {return token::MH_RECOVER;}
@@ -761,9 +780,3 @@ DynareFlexLexer::yylex()
   cerr << "DynareFlexLexer::yylex() has been called, that should never happen!" << endl;
   exit(EXIT_FAILURE);
 }
-
-/*
-  Local variables:
-  mode: C++
-  End:
-*/
diff --git a/preprocessor/ExprNode.cc b/preprocessor/ExprNode.cc
index 5f278ce1ee001ea819b7fb30356bcef0762d4275..66bef7503cd70d5a5d1610d60f8e5d7a9642666a 100644
--- a/preprocessor/ExprNode.cc
+++ b/preprocessor/ExprNode.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2011 Dynare Team
+ * Copyright (C) 2007-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/preprocessor/ExprNode.hh b/preprocessor/ExprNode.hh
index ffe6aff3a51b9eaed6b142e36e637769624f212b..dfef96606e4f2dbb2cda212ff3c22bc0d39c4cba 100644
--- a/preprocessor/ExprNode.hh
+++ b/preprocessor/ExprNode.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2011 Dynare Team
+ * Copyright (C) 2007-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/preprocessor/MinimumFeedbackSet.cc b/preprocessor/MinimumFeedbackSet.cc
index c43562f04fb67fe95a7239a6b3e6d3217a9fc5b1..479c8f227cee2544e952048c3c8a89ccd2a71e35 100644
--- a/preprocessor/MinimumFeedbackSet.cc
+++ b/preprocessor/MinimumFeedbackSet.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009-2011 Dynare Team
+ * Copyright (C) 2009-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -226,7 +226,6 @@ namespace MFS
     bool not_a_loop;
     int i;
     AdjacencyList_t::vertex_iterator  it, it1, ita, it_end;
-    property_map<AdjacencyList_t, vertex_index_t>::type v_index = get(vertex_index, G);
     for (tie(it, it_end) = vertices(G), i = 0; it != it_end; ++it, i++)
       {
         int in_degree_n = in_degree(*it, G);
diff --git a/preprocessor/ModFile.cc b/preprocessor/ModFile.cc
index bbc8599294a0e3d480c4111223f71185b1324a1e..4496b65bfa53068e9e0922aa500859b8ee2d3054 100644
--- a/preprocessor/ModFile.cc
+++ b/preprocessor/ModFile.cc
@@ -401,9 +401,9 @@ ModFile::computingPass(bool no_tmp_terms)
                   cerr << "ERROR: Incorrect order option..." << endl;
                   exit(EXIT_FAILURE);
                 }
-              bool hessian = mod_file_struct.order_option >= 2 || mod_file_struct.identification_present;
+              bool hessian = mod_file_struct.order_option >= 2 || mod_file_struct.identification_present || mod_file_struct.estimation_analytic_derivation;
               bool thirdDerivatives = mod_file_struct.order_option == 3;
-              bool paramsDerivatives = mod_file_struct.identification_present;
+              bool paramsDerivatives = mod_file_struct.identification_present || mod_file_struct.estimation_analytic_derivation;
               dynamic_model.computingPass(true, hessian, thirdDerivatives, paramsDerivatives, global_eval_context, no_tmp_terms, block, use_dll, byte_code);
             }
         }
@@ -462,8 +462,9 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool no_log, b
               << "M_.fname = '" << basename << "';" << endl
               << "%" << endl
               << "% Some global variables initialization" << endl
-              << "%" << endl
-              << "global_initialization;" << endl
+              << "%" << endl;
+  config_file.writeHooks(mOutputFile);
+  mOutputFile << "global_initialization;" << endl
               << "diary off;" << endl;
   if (!no_log)
     mOutputFile << "logname_ = '" << basename << ".log';" << endl
diff --git a/preprocessor/ModelTree.cc b/preprocessor/ModelTree.cc
index bdd2bbd5dcfd1dabbef4b281ad8f6eae5b0b4c7d..6ada1a471221488bdaa821d21f75727483846c77 100644
--- a/preprocessor/ModelTree.cc
+++ b/preprocessor/ModelTree.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2011 Dynare Team
+ * Copyright (C) 2003-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/preprocessor/NumericalConstants.cc b/preprocessor/NumericalConstants.cc
index 6efe1fc06e01503efcf6f0f9858e74e858c1322a..dc2bd80f2a7d06b295afb8e7a990d3953defcd01 100644
--- a/preprocessor/NumericalConstants.cc
+++ b/preprocessor/NumericalConstants.cc
@@ -26,7 +26,7 @@
 #include "NumericalConstants.hh"
 
 int
-NumericalConstants::AddNonNegativeConstant(const string &iConst) throw (InvalidFloatingPointNumberException)
+NumericalConstants::AddNonNegativeConstant(const string &iConst)
 {
   map<string, int>::const_iterator iter = numConstantsIndex.find(iConst);
 
@@ -37,12 +37,10 @@ NumericalConstants::AddNonNegativeConstant(const string &iConst) throw (InvalidF
   mNumericalConstants.push_back(iConst);
   numConstantsIndex[iConst] = id;
 
-  errno = 0;
   double val = strtod(iConst.c_str(), NULL);
 
-  // We check that the number is valid (e.g. not like "1e-10000")
-  if (errno != 0)
-    throw InvalidFloatingPointNumberException(iConst);
+  /* Note that we allow underflows (will be converted to 0) and overflows (will
+     be converted to Inf), as MATLAB and Octave do. */
 
   assert(val >= 0 || isnan(val)); // Check we have a positive constant or a NaN
   double_vals.push_back(val);
diff --git a/preprocessor/NumericalConstants.hh b/preprocessor/NumericalConstants.hh
index 0a54616a23fbacc27b7eb6134991c28ea09ef020..cb50b0cb47d556b3c714cd796700b894a4532002 100644
--- a/preprocessor/NumericalConstants.hh
+++ b/preprocessor/NumericalConstants.hh
@@ -37,15 +37,8 @@ private:
   //! Map matching constants to their id
   map<string, int> numConstantsIndex;
 public:
-  class InvalidFloatingPointNumberException
-  {
-  public:
-    const string fp;
-    InvalidFloatingPointNumberException(const string &fp_arg) : fp(fp_arg) {}
-  };
-
   //! Adds a non-negative constant (possibly Inf or NaN) and returns its ID
-  int AddNonNegativeConstant(const string &iConst) throw (InvalidFloatingPointNumberException);
+  int AddNonNegativeConstant(const string &iConst);
   //! Get a constant in string form
   string get(int ID) const;
   //! Get a constant in double form
diff --git a/preprocessor/NumericalInitialization.cc b/preprocessor/NumericalInitialization.cc
index 63d1d73ae0670c290335d4614528feabc98142b1..98327d66383d53cf03f3f821dbeebad8a2d69633 100644
--- a/preprocessor/NumericalInitialization.cc
+++ b/preprocessor/NumericalInitialization.cc
@@ -150,9 +150,9 @@ EndValStatement::EndValStatement(const init_values_t &init_values_arg,
 void
 EndValStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings)
 {
-  if (mod_file_struct.shocks_present)
+  if (mod_file_struct.shocks_present_but_simul_not_yet)
     {
-      cerr << "ERROR: Putting a \"shocks\" block before an \"endval\" block is not permitted. Please swap the two blocks. This limitation will be removed in the next major release of Dynare." << endl;
+      cerr << "ERROR: Putting a \"shocks\" block before an \"endval\" block is not permitted. Please swap the two blocks. This limitation will be removed in a future release of Dynare." << endl;
       exit(EXIT_FAILURE);
     }
 }
diff --git a/preprocessor/ParsingDriver.cc b/preprocessor/ParsingDriver.cc
index 30e474462eb5fb7e95208cd2cb4fe376944c183a..75dc4daaaf67ac7f05c108ab2a3cf472c838dc9d 100644
--- a/preprocessor/ParsingDriver.cc
+++ b/preprocessor/ParsingDriver.cc
@@ -258,15 +258,7 @@ ParsingDriver::add_equation_tags(string *key, string *value)
 expr_t
 ParsingDriver::add_non_negative_constant(string *constant)
 {
-  expr_t id;
-  try
-    {
-      id = data_tree->AddNonNegativeConstant(*constant);
-    }
-  catch (NumericalConstants::InvalidFloatingPointNumberException &e)
-    {
-      error("Invalid floating point number: " + *constant);
-    }
+  expr_t id = data_tree->AddNonNegativeConstant(*constant);
   delete constant;
   return id;
 }
@@ -747,17 +739,11 @@ void
 ParsingDriver::add_value(string *v)
 {
   expr_t id;
-  try
-    {
-      if (v->at(0) == '-')
-        id = data_tree->AddUMinus(data_tree->AddNonNegativeConstant(v->substr(1, string::npos)));
-      else
-        id = data_tree->AddNonNegativeConstant(*v);
-    }
-  catch (NumericalConstants::InvalidFloatingPointNumberException &e)
-    {
-      error("Invalid floating point number: " + *v);
-    }
+
+  if (v->at(0) == '-')
+    id = data_tree->AddUMinus(data_tree->AddNonNegativeConstant(v->substr(1, string::npos)));
+  else
+    id = data_tree->AddNonNegativeConstant(*v);
 
   delete v;
   det_shocks_values.push_back(id);
@@ -1004,17 +990,11 @@ void
 ParsingDriver::add_to_row_const(string *v)
 {
   expr_t id;
-  try
-    {
-      if (v->at(0) == '-')
-        id = data_tree->AddUMinus(data_tree->AddNonNegativeConstant(v->substr(1, string::npos)));
-      else
-        id = data_tree->AddNonNegativeConstant(*v);
-    }
-  catch (NumericalConstants::InvalidFloatingPointNumberException &e)
-    {
-      error("Invalid floating point number: " + *v);
-    }
+
+  if (v->at(0) == '-')
+    id = data_tree->AddUMinus(data_tree->AddNonNegativeConstant(v->substr(1, string::npos)));
+  else
+    id = data_tree->AddNonNegativeConstant(*v);
 
   delete v;
   sigmae_row.push_back(id);
@@ -1940,6 +1920,13 @@ ParsingDriver::calib_smoother()
   options_list.clear();
 }
 
+void
+ParsingDriver::extended_path()
+{
+  mod_file->addStatement(new ExtendedPathStatement(options_list));
+  options_list.clear();
+}
+
 expr_t
 ParsingDriver::add_model_equal(expr_t arg1, expr_t arg2)
 {
diff --git a/preprocessor/ParsingDriver.hh b/preprocessor/ParsingDriver.hh
index d3f6107dbf9ac3a351dd8c69e673c7aa2c55f194..e6bbeba39752522ba532cec62ea7f57206a1a2ae 100644
--- a/preprocessor/ParsingDriver.hh
+++ b/preprocessor/ParsingDriver.hh
@@ -516,6 +516,8 @@ public:
   void plot_conditional_forecast(string *periods = NULL);
   //! Smoother on calibrated models
   void calib_smoother();
+  //! Extended path
+  void extended_path();
   //! Writes token "arg1=arg2" to model tree
   expr_t add_model_equal(expr_t arg1, expr_t arg2);
   //! Writes token "arg=0" to model tree
diff --git a/preprocessor/Shocks.cc b/preprocessor/Shocks.cc
index a909cb15978422483ab50d2eef8f02d39e4878be..3536053e186c502145b214b1ef687858ddf099e4 100644
--- a/preprocessor/Shocks.cc
+++ b/preprocessor/Shocks.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2010 Dynare Team
+ * Copyright (C) 2003-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -196,7 +196,7 @@ void
 ShocksStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings)
 {
   // Workaround for trac ticket #35
-  mod_file_struct.shocks_present = true;
+  mod_file_struct.shocks_present_but_simul_not_yet = true;
 
   // Determine if there is a calibrated measurement error
   for (var_and_std_shocks_t::const_iterator it = var_shocks.begin();
@@ -245,7 +245,7 @@ void
 MShocksStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings)
 {
   // Workaround for trac ticket #35
-  mod_file_struct.shocks_present = true;
+  mod_file_struct.shocks_present_but_simul_not_yet = true;
 }
 
 ConditionalForecastPathsStatement::ConditionalForecastPathsStatement(const AbstractShocksStatement::det_shocks_t &paths_arg, const SymbolTable &symbol_table_arg) :
@@ -289,9 +289,9 @@ ConditionalForecastPathsStatement::writeOutput(ostream &output, const string &ba
        it != paths.end(); it++)
     {
       if (it == paths.begin())
-        output << "constrained_vars_ = " << it->first << ";" << endl;
+        output << "constrained_vars_ = " << it->first +1 << ";" << endl;
       else
-        output << "constrained_vars_ = [constrained_vars_; " << it->first << "];" << endl;
+        output << "constrained_vars_ = [constrained_vars_; " << it->first +1 << "];" << endl;
 
       const vector<AbstractShocksStatement::DetShockElement> &elems = it->second;
       for (int i = 0; i < (int) elems.size(); i++)
diff --git a/preprocessor/Shocks.hh b/preprocessor/Shocks.hh
index 1f4c34c9e348f447df560de8a480053db0db5901..7eda7f7aedc6ac4e326407dba3f2282c09a22aed 100644
--- a/preprocessor/Shocks.hh
+++ b/preprocessor/Shocks.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2010 Dynare Team
+ * Copyright (C) 2003-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/preprocessor/Statement.cc b/preprocessor/Statement.cc
index 7ca25265eaa821039d2dd4b0027a4649cb9c3063..48abb3a984101f77f422605659606e3dcbf29e1a 100644
--- a/preprocessor/Statement.cc
+++ b/preprocessor/Statement.cc
@@ -35,8 +35,9 @@ ModFileStructure::ModFileStructure() :
   bvar_present(false),
   svar_identification_present(false),
   identification_present(false),
+  estimation_analytic_derivation(false),
   partial_information(false),
-  shocks_present(false),
+  shocks_present_but_simul_not_yet(false),
   histval_present(false),
   k_order_solver(false),
   calibrated_measurement_errors(false),
diff --git a/preprocessor/Statement.hh b/preprocessor/Statement.hh
index 92b1ff19f94eba92e443b840c3a55708cd13f937..1c5c00829994d27867f410876087c4b30a045944 100644
--- a/preprocessor/Statement.hh
+++ b/preprocessor/Statement.hh
@@ -65,11 +65,15 @@ public:
   bool svar_identification_present;
   //! Whether an identification statement is present or the identification option of dynare_sensitivity statement is equal to one
   bool identification_present;
+  //! Whether the option analytic_derivation is given to estimation
+  bool estimation_analytic_derivation;
   //! Whether the option partial_information is given to stoch_simul/estimation/osr/ramsey_policy
   bool partial_information;
-  //! Whether a shocks or mshocks block is present
-  /*! Used for the workaround for trac ticket #35 */
-  bool shocks_present;
+  //! Whether a shocks or mshocks block has been parsed and no simul command yet run
+  /*! Used for the workaround for trac ticket #35. When a simul command is
+      seen, this flag is cleared in order to allow a sequence
+      shocks+endval+simul in a loop */
+  bool shocks_present_but_simul_not_yet;
   //! Whether a histval bloc is present
   /*! Used for the workaround for trac ticket #157 */
   bool histval_present;
diff --git a/preprocessor/StaticModel.cc b/preprocessor/StaticModel.cc
index 2c495c2b430431e85398906c99502d67bca24b21..57b13bea790282feeac6ad1a514549200c48b601 100644
--- a/preprocessor/StaticModel.cc
+++ b/preprocessor/StaticModel.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2011 Dynare Team
+ * Copyright (C) 2003-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -1511,6 +1511,56 @@ StaticModel::writeOutput(ostream &output, bool block) const
          output << getBlockEquationID(b, i)+1 << "; ";
       output << "];" << endl;
     }
+  for (int b = 0; b < (int) nb_blocks; b++)
+    {
+      BlockSimulationType simulation_type = getBlockSimulationType(b);
+      unsigned int block_size = getBlockSize(b);
+      ostringstream tmp_s, tmp_s_eq;
+      tmp_s.str("");
+      tmp_s_eq.str("");
+      for (unsigned int i = 0; i < block_size; i++)
+        {
+          tmp_s << " " << getBlockVariableID(b, i)+1;
+          tmp_s_eq << " " << getBlockEquationID(b, i)+1;
+        }
+      output << "block_structure_stat.block(" << b+1 << ").Simulation_Type = " << simulation_type << ";\n";
+      output << "block_structure_stat.block(" << b+1 << ").endo_nbr = " << block_size << ";\n";
+      output << "block_structure_stat.block(" << b+1 << ").mfs = " << getBlockMfs(block) << ";\n";
+      output << "block_structure_stat.block(" << b+1 << ").equation = [" << tmp_s_eq.str() << "];\n";
+      output << "block_structure_stat.block(" << b+1 << ").variable = [" << tmp_s.str() << "];\n";
+    }
+  output << "M_.block_structure_stat.block = block_structure_stat.block;\n";
+  string cst_s;
+  int nb_endo = symbol_table.endo_nbr();
+  output << "M_.block_structure_stat.variable_reordered = [";
+  for (int i = 0; i < nb_endo; i++)
+    output << " " << variable_reordered[i]+1;
+  output << "];\n";
+  output << "M_.block_structure_stat.equation_reordered = [";
+  for (int i = 0; i < nb_endo; i++)
+    output << " " << equation_reordered[i]+1;
+  output << "];\n";
+  
+  map<pair<int, int>,  int>  row_incidence;
+  for (first_derivatives_t::const_iterator it = first_derivatives.begin();
+       it != first_derivatives.end(); it++)
+    {
+      int deriv_id = it->first.second;
+      if (getTypeByDerivID(deriv_id) == eEndogenous)
+        {
+          int eq = it->first.first;
+          int symb = getSymbIDByDerivID(deriv_id);
+          int var = symbol_table.getTypeSpecificID(symb);
+          //int lag = getLagByDerivID(deriv_id);
+          row_incidence[make_pair(eq, var)] = 1;
+        }
+    }
+  output << "M_.block_structure_stat.incidence.sparse_IM = [";
+  for (map<pair< int, int >,  int>::const_iterator it = row_incidence.begin(); it != row_incidence.end(); it++)
+    {
+      output << it->first.first+1 << " " << it->first.second+1 << ";\n";
+    }
+  output << "];\n";
 }
 
 SymbolType
diff --git a/preprocessor/SymbolTable.cc b/preprocessor/SymbolTable.cc
index 42ad88a7bf61a48c2d916918d13afe0e98de03fb..f68d879e1191f00565649fe77e9d51a3d27aef71 100644
--- a/preprocessor/SymbolTable.cc
+++ b/preprocessor/SymbolTable.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2011 Dynare Team
+ * Copyright (C) 2003-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
diff --git a/preprocessor/SymbolTable.hh b/preprocessor/SymbolTable.hh
index a692d7d631557f0776ea3122b609daa1b3a53b9a..8b3763c5eb4fb73c4b72cd95dbcc3908dd4f38e4 100644
--- a/preprocessor/SymbolTable.hh
+++ b/preprocessor/SymbolTable.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2011 Dynare Team
+ * Copyright (C) 2003-2012 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -39,9 +39,7 @@ enum aux_var_t
     avExoLag = 3,         //!< Substitute for exo lags >= 2
     avExpectation = 4,    //!< Substitute for Expectation Operator
     // Type 5 now unused
-    avMultiplier = 6,     //!< Multipliers for FOC of Ramsey Problem
-    avLog = 7,            //!< Substitute argument of log expression
-    avPow = 8             //!< Substitute argument for power expression
+    avMultiplier = 6      //!< Multipliers for FOC of Ramsey Problem
   };
 
 //! Information on some auxiliary variables
diff --git a/preprocessor/macro/MacroBison.yy b/preprocessor/macro/MacroBison.yy
index 7146d78da1b6b5366400b2deac2cbd31f692b0e8..a7dc4fc5cefd9d3de778164cbc64080fde132fb4 100644
--- a/preprocessor/macro/MacroBison.yy
+++ b/preprocessor/macro/MacroBison.yy
@@ -79,7 +79,7 @@ class MacroDriver;
 
 %}
 
-%token DEFINE LINE FOR IN IF ELSE ENDIF ECHO_DIR ERROR IFDEF
+%token DEFINE LINE FOR IN IF ELSE ENDIF ECHO_DIR ERROR IFDEF IFNDEF
 %token LPAREN RPAREN LBRACKET RBRACKET EQUAL EOL
 
 %token <int_val> INTEGER
@@ -119,6 +119,8 @@ statement : expr
             { TYPERR_CATCH(driver.begin_if($2), @$); }
           | IFDEF NAME
             { TYPERR_CATCH(driver.begin_ifdef(*$2), @$); delete $2; }
+          | IFNDEF NAME
+            { TYPERR_CATCH(driver.begin_ifndef(*$2), @$); delete $2; }
           | ECHO_DIR expr
             { TYPERR_CATCH(driver.echo(@$, $2), @$); }
           | ERROR expr
@@ -205,9 +207,3 @@ Macro::parser::error(const Macro::parser::location_type &l,
 {
   driver.error(l, m);
 }
-
-/*
-  Local variables:
-  mode: C++
-  End:
-*/
diff --git a/preprocessor/macro/MacroDriver.cc b/preprocessor/macro/MacroDriver.cc
index 6ac13b02a8b8c682d3bd697f458db035e3c7cca6..746fd12e334b6ea14ac9ead4744d9fb14fbabc87 100644
--- a/preprocessor/macro/MacroDriver.cc
+++ b/preprocessor/macro/MacroDriver.cc
@@ -170,15 +170,25 @@ MacroDriver::begin_ifdef(const string &name)
   try
     {
       get_variable(name);
-      const MacroValue *one = new IntMV(*this, 1);
-      begin_if(one);
-      delete one;
+      begin_if(new IntMV(*this, 1));
     }
   catch (UnknownVariable &)
     {
-      const MacroValue *zero = new IntMV(*this, 0);
-      begin_if(zero);
-      delete zero;
+      begin_if(new IntMV(*this, 0));
+    }
+}
+
+void
+MacroDriver::begin_ifndef(const string &name)
+{
+  try
+    {
+      get_variable(name);
+      begin_if(new IntMV(*this, 0));
+    }
+  catch (UnknownVariable &)
+    {
+      begin_if(new IntMV(*this, 1));
     }
 }
 
diff --git a/preprocessor/macro/MacroDriver.hh b/preprocessor/macro/MacroDriver.hh
index fb21543b9184f63c32ac58bc478ce5b01a2dac49..0945a32960b4cfe1a8c5f3d03a9db72bc2e24e18 100644
--- a/preprocessor/macro/MacroDriver.hh
+++ b/preprocessor/macro/MacroDriver.hh
@@ -211,6 +211,9 @@ public:
   //! Begins an @#ifdef statement
   void begin_ifdef(const string &name);
 
+  //! Begins an @#ifndef statement
+  void begin_ifndef(const string &name);
+
   //! Executes @#echo directive
   void echo(const Macro::parser::location_type &l, const MacroValue *value) const throw (MacroValue::TypeError);
 
diff --git a/preprocessor/macro/MacroFlex.ll b/preprocessor/macro/MacroFlex.ll
index e073e1e601120169163fec5e6bb33f1693a9dba8..7e3e5dbaea557812b79665c000cc1ab4c0222e15 100644
--- a/preprocessor/macro/MacroFlex.ll
+++ b/preprocessor/macro/MacroFlex.ll
@@ -165,10 +165,11 @@ CONT \\\\
 <STMT>endfor                { driver.error(*yylloc, "@#endfor is not matched by a @#for statement"); }
 
 <STMT>ifdef                 { reading_if_statement = true; return token::IFDEF; }
+<STMT>ifndef                { reading_if_statement = true; return token::IFNDEF; }
 
 <STMT>if                    { reading_if_statement = true; return token::IF; }
-<STMT>else                  { driver.error(*yylloc, "@#else is not matched by an @#if statement"); }
-<STMT>endif                 { driver.error(*yylloc, "@#endif is not matched by an @#if statement"); }
+<STMT>else                  { driver.error(*yylloc, "@#else is not matched by an @#if/@#ifdef/@#ifndef statement"); }
+<STMT>endif                 { driver.error(*yylloc, "@#endif is not matched by an @#if/@#ifdef/@#ifndef statement"); }
 
 <STMT>echo                  { return token::ECHO_DIR; }
 <STMT>error                 { return token::ERROR; }
@@ -225,7 +226,7 @@ CONT \\\\
                               yylloc->step();
                             }
 <THEN_BODY>.                { then_body_tmp.append(yytext); yylloc->step(); }
-<THEN_BODY><<EOF>>          { driver.error(if_stmt_loc_tmp, "@#if not matched by an @#endif (unexpected end of file)"); }
+<THEN_BODY><<EOF>>          { driver.error(if_stmt_loc_tmp, "@#if/@#ifdef/@#ifndef not matched by an @#endif (unexpected end of file)"); }
 <THEN_BODY>^{SPC}*@#{SPC}*else{SPC}*(\/\/.*)?{EOL} {
                               yylloc->lines(1);
                               yylloc->step();
@@ -267,7 +268,7 @@ CONT \\\\
                               yylloc->step();
                             }
 <ELSE_BODY>.                { else_body_tmp.append(yytext); yylloc->step(); }
-<ELSE_BODY><<EOF>>          { driver.error(if_stmt_loc_tmp, "@#if not matched by an @#endif (unexpected end of file)"); }
+<ELSE_BODY><<EOF>>          { driver.error(if_stmt_loc_tmp, "@#if/@#ifdef/@#ifndef not matched by an @#endif (unexpected end of file)"); }
 
 <ELSE_BODY>^{SPC}*@#{SPC}*endif{SPC}*(\/\/.*)?{EOL} {
                               yylloc->lines(1);
@@ -427,9 +428,3 @@ MacroFlexLexer::yylex()
   cerr << "MacroFlexLexer::yylex() has been called, that should never happen!" << endl;
   exit(EXIT_FAILURE);
 }
-
-/*
-  Local variables:
-  mode: C++
-  End:
-*/
diff --git a/scripts/diffFuncNames.py b/scripts/diffFuncNames.py
new file mode 100644
index 0000000000000000000000000000000000000000..14dc224ab2248e7490d7cbf697affcfad1885892
--- /dev/null
+++ b/scripts/diffFuncNames.py
@@ -0,0 +1,65 @@
+##
+## This script recursively goes through the matlab directory and its
+## subdirectories, comparing all .m file names to the function declarations at
+## the top of those files. If the two do not correspond, it prints out the name
+## of the file and the name of the function declared in the file.
+##
+
+##
+## Copyright (C) 2012 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/>.
+##
+
+import os
+import string
+
+for dirname, dirnames, filenames in os.walk('../matlab'):
+    for filename in filenames:
+        filename = string.strip(filename)
+
+        if filename[-2:] != '.m' or filename == 'msstart2.m' or filename == 'msstart_setup.m' or filename == 'qmc_sequence.m':
+            continue
+
+        fullfilename = os.path.join(dirname, filename)
+        f = open(fullfilename, 'r')
+        funcDef = ''
+        inComment = False
+        while True:
+            funcDef += f.read(1)
+            if funcDef[-1:] == '%':
+                inComment = True
+
+            if inComment:
+                if funcDef[-1:] == '\n':
+                    inComment = False
+            else:
+                if funcDef[-1:] == '(':
+                    break
+        f.close()
+
+        spliteq = string.rsplit(funcDef, '=')
+        if len(spliteq) == 1:
+            spliteq = string.rsplit(funcDef, 'function ')
+
+        spliteq = spliteq.pop()
+        spliteq = string.strip(spliteq, '. ')
+        spliteq = string.strip(spliteq, '\n ')
+        spliteq = string.strip(spliteq, '( ')
+
+        if filename[:-2] != spliteq:
+            print fullfilename + ': ' + spliteq
+
diff --git a/dynare.el b/scripts/dynare.el
similarity index 100%
rename from dynare.el
rename to scripts/dynare.el
diff --git a/scripts/functionDifferences.py b/scripts/functionDifferences.py
new file mode 100644
index 0000000000000000000000000000000000000000..0679087ef627a4d9e298d509192012f4cb52b1cf
--- /dev/null
+++ b/scripts/functionDifferences.py
@@ -0,0 +1,204 @@
+##
+## This script recursively goes through the matlab directory and its
+## subdirectories in the unstable branch, comparing the calling structures of the
+## functions to those in another branch/commit, in this case the 4.2.5 branch
+## The output is compatible with a Dynare Wiki page
+##
+## NB: To err on the side of safety, this script won't clean your workspace so a
+## git command to checkout a different branch will fail if your workspace is
+## dirty.
+##
+
+##
+## Copyright (C) 2012 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/>.
+##
+
+import os
+import string
+import subprocess
+import sys
+
+def runCompare():
+    unstable = getFuncDict()
+    subprocess.call(['git','checkout','4.2'])
+
+    stable = getFuncDict()
+    subprocess.call(['git','checkout','master'])
+
+    us = set(unstable.keys())
+    ss = set(stable.keys())
+
+    deletedFunctions = sorted(ss - us)
+    makeOldFunctionsWikiTable(deletedFunctions, stable)
+
+    newFunctions = sorted(us - ss)
+    makeNewFunctionsWikiTable(newFunctions, unstable)
+
+    outputChanged = set([])
+    inputChanged = set([])
+    commonFunctions = sorted(ss & us)
+    for le in commonFunctions:
+        sOut = set(stable[le]['output'])
+        uOut = set(unstable[le]['output'])
+        sIn = set(stable[le]['input'])
+        uIn = set(unstable[le]['input'])
+
+        if len(uOut - sOut):
+            outputChanged.add(le)
+
+        if len(uIn - sIn):
+            inputChanged.add(le)
+
+    unionChanged = sorted(outputChanged | inputChanged)
+    makeUnionChangedWikiTable(unionChanged, stable, unstable)
+
+
+def makeUnionChangedWikiTable(keys, stable, unstable):
+    write = sys.stdout.write
+    print "= Functions Whose Arguments Have Changed between Dynare 4.2.5 and " \
+        "Dynare 4.3 ="
+    print "|| '''Location''' || '''Old Output''' || " \
+        "'''New Output''' || '''Old Input''' || '''New Input''' ||"
+    for k in keys:
+        write('|| {{{' + unstable[k]['filename'][10:]  + '}}} || ')
+        write(str(stable[k]['output']) + ' || ')
+        write(str(unstable[k]['output']) + ' || ')
+        write(str(stable[k]['input']) + ' || ')
+        write(str(unstable[k]['input']) + ' ||')
+        print
+
+
+def makeNewFunctionsWikiTable(keys, dictionary):
+    print '= New Functions in Dynare 4.3 ='
+    makeWikiTable(keys, dictionary)
+
+
+def makeOldFunctionsWikiTable(keys, dictionary):
+    print '= Functions Removed in Dynare 4.3 ='
+    makeWikiTable(keys, dictionary)
+
+
+def makeWikiTable(keys, dictionary):
+    write = sys.stdout.write
+    print "|| '''Location''' || '''Output''' || '''Input''' ||"
+    for k in keys:
+        write('|| {{{' + dictionary[k]['filename'][10:]  + '}}} || ')
+        write(str(dictionary[k]['output']) + ' || ')
+        write(str(dictionary[k]['input']) + ' ||')
+        print
+
+
+def printDict(dictionary, title):
+    print
+    print '***********************************'
+    print '** ' + title
+    print '***********************************'
+    for key in sorted(dictionary.iterkeys()):
+        b = dictionary[key]
+        print key + ':' + b['filename']
+    print '***********************************'
+    print '***********************************'
+    print
+
+
+def getFuncDict():
+    functions = {}
+
+    for dirname, dirnames, filenames in os.walk('../matlab'):
+        for filename in filenames:
+            filename = string.strip(filename)
+
+            if filename[-2:] != '.m' or filename == 'msstart2.m' or filename == 'msstart_setup.m' or filename == 'qmc_sequence.m':
+                continue
+
+            fullfilename = os.path.join(dirname, filename)
+            f = open(fullfilename, 'r')
+            funcDef = ''
+            inComment = False
+            while True:
+                funcDef += f.read(1)
+                if inComment:
+                    if funcDef[-1:] == '\n':
+                        inComment = False
+                else:
+                    if funcDef[-1:] == '%':
+                        inComment = True
+                    elif funcDef[-1:] == ')':
+                        break
+            funcDef = funcDef.strip()
+            f.close()
+
+            funcDict = {}
+            funcDict['filename'] = fullfilename
+
+            # OUTPUT
+            spliteq = string.rsplit(funcDef, '=')
+            if len(spliteq) == 1:
+                # no output
+                outputs = ['']
+                funcDict['output'] = outputs
+                rhs = string.split(funcDef, ' ', 1).pop(1).strip()
+            else:
+                outputs = string.split(spliteq.pop(0), ' ', 1).pop(1)
+                outputs = [string.strip(outputs, '[] ')]
+                outputs = getputs(outputs)
+                funcDict['output'] = outputs
+                rhs = string.strip(spliteq.pop(0), ' .\n')
+
+            # FUNCTION NAME
+            splitfn = string.split(rhs, '(')
+            fn = splitfn.pop(0)
+
+            # INPUT
+            inputs = [string.strip(le,')') for le in splitfn]
+            inputs = getputs(inputs)
+            funcDict['input'] = inputs
+
+            functions[fn] = funcDict
+
+    return functions
+
+
+def getputs(puts):
+    ''' Can be of the forms
+    a
+    a
+    a, b
+    a, b   % aoeu
+    a, ...
+       b
+    a, ... % aoeu
+       b
+
+    Return a list of (in/out puts)
+    '''
+    splitout = string.split(string.join(puts), '\n')
+
+    for i,le in enumerate(splitout[:]):
+        indx = string.find(le, '%')
+        if indx != -1:
+            splitout[i] = string.strip(le[:indx], '\t .')
+        else:
+            splitout[i] = string.strip(le, '\t .')
+
+    splitcommas = string.split(string.join(splitout), ',')
+    return [string.strip(le) for le in splitcommas]
+
+
+if __name__ == "__main__":
+    runCompare()
diff --git a/uncrustify.cfg b/scripts/uncrustify.cfg
similarity index 100%
rename from uncrustify.cfg
rename to scripts/uncrustify.cfg
diff --git a/tests/.gitignore b/tests/.gitignore
index 57556058afcaaea53d8adff831901ad579affd78..689f72a334c3b8dc39371149f4435b45d9d3f607 100644
--- a/tests/.gitignore
+++ b/tests/.gitignore
@@ -39,6 +39,7 @@ wsOct
 !/external_function/extFunWithFirstAndSecondDerivs.m
 !/fs2000/fs2000a_steadystate.m
 !/fs2000/fsdat_simul.m
+!/fs2000/fsdat_simul_missing_obs.m
 !/gsa/data_ca1.m
 !/gsa/data_ca1.mat
 !/gsa/ls2003_mean.mat
diff --git a/tests/AIM/data_ca1.m b/tests/AIM/data_ca1.m
index b0b4f054613b41ebd91b9492f4edca5d38f6cb26..c28fae1a2800e83eda0e6343196e8aeafad2935f 100644
--- a/tests/AIM/data_ca1.m
+++ b/tests/AIM/data_ca1.m
@@ -1,100 +1,100 @@
-data = [0.928467646476  11.8716889412   20  0.418037507392  0.227382377518 ...
--0.705994063083 11.7522582094   21.25   1.09254424511   -1.29488274994 ...
--0.511895351926 9.68144025625   17.25   -1.66150408407  0.331508393098 ...
--0.990955971267 10.0890781236   17  1.43016275252   -2.43589670141 ...
--0.981233061806 12.1094840679   18.25   2.91293288733   -0.790246576864 ...
--0.882182844512 8.54559460406   15  0.419579139481  0.358729719566 ...
--0.930893002836 6.19238374422   12.5    -1.48847457959  0.739779938797 ...
-1.53158206947   2.76544271886   11.5    -0.336216769682 0.455559918769 ...
-2.2659052834    5.47418162513   11  0.306436789767  -0.0707985731221 ...
-1.05419803797   6.35698426189   11  0.140700250477  0.620401487202 ...
-1.20161076793   3.4253301593    11  0.461296492351  0.14354323987 ...
-1.73934077971   4.70926070322   11.5    1.35798282982   0.38564694435 ...
-1.71735262584   3.54232079749   12.5    2.9097529155    -0.804308583301 ...
-0.426343657844  3.32719108897   13  1.64214862652   -1.18214664701 ...
-1.67751812324   2.93444727338   11.25   0.344434910651  -1.6529373719 ...
-1.37013301099   4.72303361923   11.75   2.61511526582   0.327684243041 ...
-0.281231073781  4.4893853071    10.5    1.17043449257   1.12855106649 ...
-1.53638992834   3.7325309699    10.25   -0.683947046728 0.11943538737 ...
-1.68081431462   3.34729969129   10  1.41159342106   -1.59065680853 ...
--0.343321601133 5.05563513564   12  1.75117366498   -2.40127764642 ...
-0.873415608666  3.2779996255    10.25   -1.39895866711  0.0971444398216 ...
-0.26399696544   4.78229419828   9.75    0.0914692438124 0.299310457612 ...
--0.562233624818 3.88598638237   9.75    -0.0505384765105    0.332826708151 ...
-2.15161914936   3.84859710132   8.75    -3.44811080489  0.789138678784 ...
-1.2345093726    5.62225030942   9.5 -0.366945407434 2.32974981198 ...
-1.62554967459   4.24667132831   10  -0.800958371402 0.0293183770935 ...
-1.33035402527   2.75248979249   9.75    -0.855723113225 0.852493939813 ...
-1.52078814077   3.53415985826   9.75    -3.37963469203  -1.05133958119 ...
-1.16704983697   4.92754079464   10.75   -3.0142303324   0.459907431978 ...
-0.277213572101  4.55532133037   11.75   -0.851995599415 2.03242034852 ...
-0.842215068977  3.11164509647   12.25   -1.08290421696  0.014323281961 ...
-1.05325028606   4.92882647578   13.5    -1.1953883867   0.706764750654 ...
-0.453051253568  6.82998950103   13.5    0.111803656462  0.088462593153 ...
-0.199885995525  5.82643354662   13.5    -0.920501518421 -0.26504958666 ...
-0.137907999624  2.66076369132   13.5    -1.17122929812  -0.995642430514 ...
-0.721949686709  5.70497876823   14.25   1.19378169018   -1.10644839651 ...
--0.418465249225 3.75861110232   14.75   -1.03131674824  0.188507675831 ...
--0.644028342116 4.15104788154   13.75   -1.48911756546  0.204560913792 ...
--0.848213852668 5.65580324027   12.75   0.677011703877  -0.849628054542 ...
--1.51954076928  11.4866911266   11.25   -0.446024680774 -0.456342350765 ...
-0.265275055215  2.85472749592   9.75    -0.598778202436 -0.907311640831 ...
-0.356162529063  2.29614015658   9.5 -0.46820788432  -1.22130883441 ...
-0.368308864363  -0.539083504685 8   -0.781333991956 0.374007246518 ...
--0.145751412732 1.61507621789   8.25    3.68291932628   1.32438399845 ...
-0.285457283664  2.14334055993   7   1.42819405379   -0.00818660844123 ...
-0.372390129412  1.60000213334   6.25    0.626106424052  -0.10136772765 ...
-0.382720203063  1.72614243263   7.25    4.89631941021   -1.10060711916 ...
-0.737957515573  2.90430582851   6   -0.0422721010314    0.4178952497 ...
-0.649532581668  0.657135682543  6   0.692066153971  0.422299120276 ...
-0.627159201987  1.70352689913   5.75    2.62066711305   -1.29237304034 ...
-0.905441299817  1.95663197267   5.5 1.5949697565    -0.27115830703 ...
-1.49322577898   -2.08741765309  6.25    1.23027694802   0.418336889527 ...
-1.48750731567   -1.57274121871  8   3.01660550994   -0.893958254365 ...
-1.39783858087   2.22623066426   7   -0.80842319214  1.47625453886 ...
-0.89274836317   1.30378081742   8   -0.249485058661 0.159871204185 ...
-0.920652246088  4.1437741965    9.75    2.8204453623    0.178149239655 ...
--0.00264276644799   3.07989972052   8.75    -2.56342461535  2.105998353 ...
-0.0198190461681 0.766283759256  8   -1.15838865989  1.56888883418 ...
-0.440050515311  0.127570085801  7.5 0.0400753569995 0.028914333532 ...
-0.129536637901  1.78174141526   6.75    0.959943962785  0.307781224401 ...
-0.398549827172  3.03606770667   6.5 -0.340209794742 0.100979469478 ...
-1.17174775425   0.629625188037  5.75    0.403003686814  0.902394579377 ...
-0.991163981251  2.50862910684   4.75    -1.44963996982  1.16150986945 ...
-0.967603566096  2.12003739013   4.75    0.610846030775  -0.889994896068 ...
-1.14689383604   1.24185011459   4.75    2.01098091308   -1.73846431001 ...
-1.32593824054   0.990713820685  4.75    -0.0955142989332    -0.0369257308362 ...
-0.861135002644  -0.24744943605  6   1.72793107135   -0.691506789639 ...
-1.26870850151   2.09844764887   6.5 1.50720217572   -1.31399187077 ...
-0.260364987715  1.10650139716   6.5 1.13659047496   0.0720441664643 ...
-1.09731242214   0.490796381346  7.25    4.59123894147   -2.14073070763 ...
-1.63792841781   0.612652594286  6.75    1.79604605035   -0.644363995357 ...
-1.48465576034   0.978295808687  6.75    -2.00753620902  1.39437534964 ...
-1.0987608663    4.25212569087   6.25    -2.58901196498  2.56054320803 ...
-1.42592178132   2.76984518311   6.25    0.888195752358  1.03114549274 ...
-1.52958239462   1.31795955491   6.5 -0.902907564082 -0.0952198893776 ...
-1.0170168994    2.14733589918   7   -1.3054866978   2.68803738466 ...
-0.723253652257  3.43552889347   7.5 1.8213700853    0.592593586195 ...
-1.24720806008   3.87383806577   7.5 0.0522300654168 0.988871238698 ...
-0.482531471239  2.67793287032   7.5 2.9693944293    -0.108591166081 ...
-0.154056100439  0.927269031704  6.75    0.119222057561  3.30489209451 ...
-0.0694865769274 6.65916526788   6.25    0.889014476084  -2.83976849035 ...
--0.121267434867 0.341442615696  5.25    0.323053239216  -3.49289229012 ...
-0.726473690375  -3.5423730964   4   2.19149290449   -3.20855054004 ...
-1.39271709108   2.63121085718   3.75    0.88406577736   0.75622580197 ...
-1.07502077727   5.88578836799   4.25    -2.55088273352  2.89018116374 ...
-0.759049251607  4.24703604223   4.5 0.575687665685  -0.388292506167 ...
-]; 
- 
-data = reshape(data,5,86)'; 
-y_obs = data(:,1); 
-pie_obs = data(:,2); 
-R_obs = data(:,3); 
-de = data(:,4); 
-dq = data(:,5); 
- 
-%Country: Canada 
-%Sample Range: 1981:2 to 2002:3 
-%Observations: 86 
-%Variables: Real GDP Growth [%], Inflation [annualized %], Nom Rate [%], 
-%           Exchange Rate Change [%], Terms of Trade Change [%] 
+data = [0.928467646476  11.8716889412   20  0.418037507392  0.227382377518 ...
+-0.705994063083 11.7522582094   21.25   1.09254424511   -1.29488274994 ...
+-0.511895351926 9.68144025625   17.25   -1.66150408407  0.331508393098 ...
+-0.990955971267 10.0890781236   17  1.43016275252   -2.43589670141 ...
+-0.981233061806 12.1094840679   18.25   2.91293288733   -0.790246576864 ...
+-0.882182844512 8.54559460406   15  0.419579139481  0.358729719566 ...
+-0.930893002836 6.19238374422   12.5    -1.48847457959  0.739779938797 ...
+1.53158206947   2.76544271886   11.5    -0.336216769682 0.455559918769 ...
+2.2659052834    5.47418162513   11  0.306436789767  -0.0707985731221 ...
+1.05419803797   6.35698426189   11  0.140700250477  0.620401487202 ...
+1.20161076793   3.4253301593    11  0.461296492351  0.14354323987 ...
+1.73934077971   4.70926070322   11.5    1.35798282982   0.38564694435 ...
+1.71735262584   3.54232079749   12.5    2.9097529155    -0.804308583301 ...
+0.426343657844  3.32719108897   13  1.64214862652   -1.18214664701 ...
+1.67751812324   2.93444727338   11.25   0.344434910651  -1.6529373719 ...
+1.37013301099   4.72303361923   11.75   2.61511526582   0.327684243041 ...
+0.281231073781  4.4893853071    10.5    1.17043449257   1.12855106649 ...
+1.53638992834   3.7325309699    10.25   -0.683947046728 0.11943538737 ...
+1.68081431462   3.34729969129   10  1.41159342106   -1.59065680853 ...
+-0.343321601133 5.05563513564   12  1.75117366498   -2.40127764642 ...
+0.873415608666  3.2779996255    10.25   -1.39895866711  0.0971444398216 ...
+0.26399696544   4.78229419828   9.75    0.0914692438124 0.299310457612 ...
+-0.562233624818 3.88598638237   9.75    -0.0505384765105    0.332826708151 ...
+2.15161914936   3.84859710132   8.75    -3.44811080489  0.789138678784 ...
+1.2345093726    5.62225030942   9.5 -0.366945407434 2.32974981198 ...
+1.62554967459   4.24667132831   10  -0.800958371402 0.0293183770935 ...
+1.33035402527   2.75248979249   9.75    -0.855723113225 0.852493939813 ...
+1.52078814077   3.53415985826   9.75    -3.37963469203  -1.05133958119 ...
+1.16704983697   4.92754079464   10.75   -3.0142303324   0.459907431978 ...
+0.277213572101  4.55532133037   11.75   -0.851995599415 2.03242034852 ...
+0.842215068977  3.11164509647   12.25   -1.08290421696  0.014323281961 ...
+1.05325028606   4.92882647578   13.5    -1.1953883867   0.706764750654 ...
+0.453051253568  6.82998950103   13.5    0.111803656462  0.088462593153 ...
+0.199885995525  5.82643354662   13.5    -0.920501518421 -0.26504958666 ...
+0.137907999624  2.66076369132   13.5    -1.17122929812  -0.995642430514 ...
+0.721949686709  5.70497876823   14.25   1.19378169018   -1.10644839651 ...
+-0.418465249225 3.75861110232   14.75   -1.03131674824  0.188507675831 ...
+-0.644028342116 4.15104788154   13.75   -1.48911756546  0.204560913792 ...
+-0.848213852668 5.65580324027   12.75   0.677011703877  -0.849628054542 ...
+-1.51954076928  11.4866911266   11.25   -0.446024680774 -0.456342350765 ...
+0.265275055215  2.85472749592   9.75    -0.598778202436 -0.907311640831 ...
+0.356162529063  2.29614015658   9.5 -0.46820788432  -1.22130883441 ...
+0.368308864363  -0.539083504685 8   -0.781333991956 0.374007246518 ...
+-0.145751412732 1.61507621789   8.25    3.68291932628   1.32438399845 ...
+0.285457283664  2.14334055993   7   1.42819405379   -0.00818660844123 ...
+0.372390129412  1.60000213334   6.25    0.626106424052  -0.10136772765 ...
+0.382720203063  1.72614243263   7.25    4.89631941021   -1.10060711916 ...
+0.737957515573  2.90430582851   6   -0.0422721010314    0.4178952497 ...
+0.649532581668  0.657135682543  6   0.692066153971  0.422299120276 ...
+0.627159201987  1.70352689913   5.75    2.62066711305   -1.29237304034 ...
+0.905441299817  1.95663197267   5.5 1.5949697565    -0.27115830703 ...
+1.49322577898   -2.08741765309  6.25    1.23027694802   0.418336889527 ...
+1.48750731567   -1.57274121871  8   3.01660550994   -0.893958254365 ...
+1.39783858087   2.22623066426   7   -0.80842319214  1.47625453886 ...
+0.89274836317   1.30378081742   8   -0.249485058661 0.159871204185 ...
+0.920652246088  4.1437741965    9.75    2.8204453623    0.178149239655 ...
+-0.00264276644799   3.07989972052   8.75    -2.56342461535  2.105998353 ...
+0.0198190461681 0.766283759256  8   -1.15838865989  1.56888883418 ...
+0.440050515311  0.127570085801  7.5 0.0400753569995 0.028914333532 ...
+0.129536637901  1.78174141526   6.75    0.959943962785  0.307781224401 ...
+0.398549827172  3.03606770667   6.5 -0.340209794742 0.100979469478 ...
+1.17174775425   0.629625188037  5.75    0.403003686814  0.902394579377 ...
+0.991163981251  2.50862910684   4.75    -1.44963996982  1.16150986945 ...
+0.967603566096  2.12003739013   4.75    0.610846030775  -0.889994896068 ...
+1.14689383604   1.24185011459   4.75    2.01098091308   -1.73846431001 ...
+1.32593824054   0.990713820685  4.75    -0.0955142989332    -0.0369257308362 ...
+0.861135002644  -0.24744943605  6   1.72793107135   -0.691506789639 ...
+1.26870850151   2.09844764887   6.5 1.50720217572   -1.31399187077 ...
+0.260364987715  1.10650139716   6.5 1.13659047496   0.0720441664643 ...
+1.09731242214   0.490796381346  7.25    4.59123894147   -2.14073070763 ...
+1.63792841781   0.612652594286  6.75    1.79604605035   -0.644363995357 ...
+1.48465576034   0.978295808687  6.75    -2.00753620902  1.39437534964 ...
+1.0987608663    4.25212569087   6.25    -2.58901196498  2.56054320803 ...
+1.42592178132   2.76984518311   6.25    0.888195752358  1.03114549274 ...
+1.52958239462   1.31795955491   6.5 -0.902907564082 -0.0952198893776 ...
+1.0170168994    2.14733589918   7   -1.3054866978   2.68803738466 ...
+0.723253652257  3.43552889347   7.5 1.8213700853    0.592593586195 ...
+1.24720806008   3.87383806577   7.5 0.0522300654168 0.988871238698 ...
+0.482531471239  2.67793287032   7.5 2.9693944293    -0.108591166081 ...
+0.154056100439  0.927269031704  6.75    0.119222057561  3.30489209451 ...
+0.0694865769274 6.65916526788   6.25    0.889014476084  -2.83976849035 ...
+-0.121267434867 0.341442615696  5.25    0.323053239216  -3.49289229012 ...
+0.726473690375  -3.5423730964   4   2.19149290449   -3.20855054004 ...
+1.39271709108   2.63121085718   3.75    0.88406577736   0.75622580197 ...
+1.07502077727   5.88578836799   4.25    -2.55088273352  2.89018116374 ...
+0.759049251607  4.24703604223   4.5 0.575687665685  -0.388292506167 ...
+]; 
+ 
+data = reshape(data,5,86)'; 
+y_obs = data(:,1); 
+pie_obs = data(:,2); 
+R_obs = data(:,3); 
+de = data(:,4); 
+dq = data(:,5); 
+ 
+%Country: Canada 
+%Sample Range: 1981:2 to 2002:3 
+%Observations: 86 
+%Variables: Real GDP Growth [%], Inflation [annualized %], Nom Rate [%], 
+%           Exchange Rate Change [%], Terms of Trade Change [%] 
diff --git a/tests/AIM/fs2000_b1L1L_AIM_steadystate.m b/tests/AIM/fs2000_b1L1L_AIM_steadystate.m
index 3d427d7d1089bb3e521f04ae2d066d75e2885da9..eea49707ddc95a61186262259fdb0fee376325a3 100644
--- a/tests/AIM/fs2000_b1L1L_AIM_steadystate.m
+++ b/tests/AIM/fs2000_b1L1L_AIM_steadystate.m
@@ -1,65 +1,65 @@
-% computes the steady state of fs2000 analyticaly
-% largely inspired by the program of F. Schorfheide
-function [ys,check] = fs2000k_steadystate(ys,exe)
-  global M_
-  
-  alp = M_.params(1); 
-  bet = M_.params(2); 
-  gam = M_.params(3); 
-  mst = M_.params(4); 
-  rho = M_.params(5); 
-  psi = M_.params(6); 
-  del = M_.params(7); 
-
-  check = 0;
-  
-  dA = exp(gam);
-  gst = 1/dA;
-  m = mst;
-  
-  khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1));
-  xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1);
-  nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp );
-  n  = xist/(nust+xist);
-  P  = xist + nust;
-  k  = khst*n;
-
-  l  = psi*mst*n/( (1-psi)*(1-n) );
-  c  = mst/P;
-  d  = l - mst + 1;
-  y  = k^alp*n^(1-alp)*gst^alp;
-  R  = mst/bet;
-  W  = l/n;
-  ist  = y-c;
-  q  = 1 - d;
-
-  e = 1;
-  
-  gp_obs = m/dA;
-  gy_obs = dA;
-  
-  P_obs = 1;
-  Y_obs = 1;
-  
-  P2=P;
-  c2=c;
-  
-  ys =[
-    m     
-    P     
-    c     
-    e     
-    W     
-    R     
-    k     
-    d     
-    n     
-    l     
-    gy_obs
-    gp_obs
-    Y_obs 
-    P_obs 
-    y     
-    dA
-    P2
+% computes the steady state of fs2000 analyticaly
+% largely inspired by the program of F. Schorfheide
+function [ys,check] = fs2000k_steadystate(ys,exe)
+  global M_
+  
+  alp = M_.params(1); 
+  bet = M_.params(2); 
+  gam = M_.params(3); 
+  mst = M_.params(4); 
+  rho = M_.params(5); 
+  psi = M_.params(6); 
+  del = M_.params(7); 
+
+  check = 0;
+  
+  dA = exp(gam);
+  gst = 1/dA;
+  m = mst;
+  
+  khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1));
+  xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1);
+  nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp );
+  n  = xist/(nust+xist);
+  P  = xist + nust;
+  k  = khst*n;
+
+  l  = psi*mst*n/( (1-psi)*(1-n) );
+  c  = mst/P;
+  d  = l - mst + 1;
+  y  = k^alp*n^(1-alp)*gst^alp;
+  R  = mst/bet;
+  W  = l/n;
+  ist  = y-c;
+  q  = 1 - d;
+
+  e = 1;
+  
+  gp_obs = m/dA;
+  gy_obs = dA;
+  
+  P_obs = 1;
+  Y_obs = 1;
+  
+  P2=P;
+  c2=c;
+  
+  ys =[
+    m     
+    P     
+    c     
+    e     
+    W     
+    R     
+    k     
+    d     
+    n     
+    l     
+    gy_obs
+    gp_obs
+    Y_obs 
+    P_obs 
+    y     
+    dA
+    P2
     c2  ];
\ No newline at end of file
diff --git a/tests/AIM/fs2000_b1L1L_steadystate.m b/tests/AIM/fs2000_b1L1L_steadystate.m
index 3d427d7d1089bb3e521f04ae2d066d75e2885da9..24b9ebc273a3a5eea4ef472e8cf6bc250c0903a4 100644
--- a/tests/AIM/fs2000_b1L1L_steadystate.m
+++ b/tests/AIM/fs2000_b1L1L_steadystate.m
@@ -1,65 +1,65 @@
-% computes the steady state of fs2000 analyticaly
-% largely inspired by the program of F. Schorfheide
-function [ys,check] = fs2000k_steadystate(ys,exe)
-  global M_
-  
-  alp = M_.params(1); 
-  bet = M_.params(2); 
-  gam = M_.params(3); 
-  mst = M_.params(4); 
-  rho = M_.params(5); 
-  psi = M_.params(6); 
-  del = M_.params(7); 
-
-  check = 0;
-  
-  dA = exp(gam);
-  gst = 1/dA;
-  m = mst;
-  
-  khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1));
-  xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1);
-  nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp );
-  n  = xist/(nust+xist);
-  P  = xist + nust;
-  k  = khst*n;
-
-  l  = psi*mst*n/( (1-psi)*(1-n) );
-  c  = mst/P;
-  d  = l - mst + 1;
-  y  = k^alp*n^(1-alp)*gst^alp;
-  R  = mst/bet;
-  W  = l/n;
-  ist  = y-c;
-  q  = 1 - d;
-
-  e = 1;
-  
-  gp_obs = m/dA;
-  gy_obs = dA;
-  
-  P_obs = 1;
-  Y_obs = 1;
-  
-  P2=P;
-  c2=c;
-  
-  ys =[
-    m     
-    P     
-    c     
-    e     
-    W     
-    R     
-    k     
-    d     
-    n     
-    l     
-    gy_obs
-    gp_obs
-    Y_obs 
-    P_obs 
-    y     
-    dA
-    P2
+% computes the steady state of fs2000 analyticaly
+% largely inspired by the program of F. Schorfheide
+function [ys,check] = fs2000_b1L1L_steadystate(ys,exe)
+  global M_
+  
+  alp = M_.params(1); 
+  bet = M_.params(2); 
+  gam = M_.params(3); 
+  mst = M_.params(4); 
+  rho = M_.params(5); 
+  psi = M_.params(6); 
+  del = M_.params(7); 
+
+  check = 0;
+  
+  dA = exp(gam);
+  gst = 1/dA;
+  m = mst;
+  
+  khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1));
+  xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1);
+  nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp );
+  n  = xist/(nust+xist);
+  P  = xist + nust;
+  k  = khst*n;
+
+  l  = psi*mst*n/( (1-psi)*(1-n) );
+  c  = mst/P;
+  d  = l - mst + 1;
+  y  = k^alp*n^(1-alp)*gst^alp;
+  R  = mst/bet;
+  W  = l/n;
+  ist  = y-c;
+  q  = 1 - d;
+
+  e = 1;
+  
+  gp_obs = m/dA;
+  gy_obs = dA;
+  
+  P_obs = 1;
+  Y_obs = 1;
+  
+  P2=P;
+  c2=c;
+  
+  ys =[
+    m     
+    P     
+    c     
+    e     
+    W     
+    R     
+    k     
+    d     
+    n     
+    l     
+    gy_obs
+    gp_obs
+    Y_obs 
+    P_obs 
+    y     
+    dA
+    P2
     c2  ];
\ No newline at end of file
diff --git a/tests/AIM/fsdat.m b/tests/AIM/fsdat.m
index 5a0e3658d4031fe8f32bee59f33c515549b8ee23..aba209b908a794044e570302331b8efe9eaac673 100644
--- a/tests/AIM/fsdat.m
+++ b/tests/AIM/fsdat.m
@@ -1,210 +1,210 @@
-data_q = [
-18.02 1474.5 150.2
-17.94 1538.2 150.9
-18.01 1584.5 151.4
-18.42 1644.1 152
-18.73 1678.6 152.7
-19.46 1693.1 153.3
-19.55 1724   153.9
-19.56 1758.2 154.7
-19.79 1760.6 155.4
-19.77 1779.2 156
-19.82 1778.8 156.6
-20.03 1790.9 157.3
-20.12 1846   158
-20.1  1882.6 158.6
-20.14 1897.3 159.2
-20.22 1887.4 160
-20.27 1858.2 160.7
-20.34 1849.9 161.4
-20.39 1848.5 162
-20.42 1868.9 162.8
-20.47 1905.6 163.6
-20.56 1959.6 164.3
-20.62 1994.4 164.9
-20.78 2020.1 165.7
-21    2030.5 166.5
-21.2  2023.6 167.2
-21.33 2037.7 167.9
-21.62 2033.4 168.7
-21.71 2066.2 169.5
-22.01 2077.5 170.2
-22.15 2071.9 170.9
-22.27 2094   171.7
-22.29 2070.8 172.5
-22.56 2012.6 173.1
-22.64 2024.7 173.8
-22.77 2072.3 174.5
-22.88 2120.6 175.3
-22.92 2165   176.045
-22.91 2223.3  176.727
-22.94 2221.4  177.481
-23.03 2230.95 178.268
-23.13 2279.22 179.694
-23.22 2265.48 180.335
-23.32 2268.29 181.094
-23.4  2238.57 181.915
-23.45 2251.68 182.634
-23.51 2292.02 183.337
-23.56 2332.61 184.103
-23.63 2381.01 184.894
-23.75 2422.59 185.553
-23.81 2448.01 186.203
-23.87 2471.86 186.926
-23.94 2476.67 187.68
-24    2508.7  188.299
-24.07 2538.05 188.906
-24.12 2586.26 189.631
-24.29 2604.62 190.362
-24.35 2666.69 190.954
-24.41 2697.54 191.56
-24.52 2729.63 192.256
-24.64 2739.75 192.938
-24.77 2808.88 193.467
-24.88 2846.34 193.994
-25.01 2898.79 194.647
-25.17 2970.48 195.279
-25.32 3042.35 195.763
-25.53 3055.53 196.277
-25.79 3076.51 196.877
-26.02 3102.36 197.481
-26.14 3127.15 197.967
-26.31 3129.53 198.455
-26.6  3154.19 199.012
-26.9  3177.98 199.572
-27.21 3236.18 199.995
-27.49 3292.07 200.452
-27.75 3316.11 200.997
-28.12 3331.22 201.538
-28.39 3381.86 201.955
-28.73 3390.23 202.419
-29.14 3409.65 202.986
-29.51 3392.6  203.584
-29.94 3386.49 204.086
-30.36 3391.61 204.721
-30.61 3422.95 205.419
-31.02 3389.36 206.13
-31.5  3481.4  206.763
-31.93 3500.95 207.362
-32.27 3523.8  208
-32.54 3533.79 208.642
-33.02 3604.73 209.142
-33.2  3687.9  209.637
-33.49 3726.18 210.181
-33.95 3790.44 210.737
-34.36 3892.22 211.192
-34.94 3919.01 211.663
-35.61 3907.08 212.191
-36.29 3947.11 212.708
-37.01 3908.15 213.144
-37.79 3922.57 213.602
-38.96 3879.98 214.147
-40.13 3854.13 214.7
-41.05 3800.93 215.135
-41.66 3835.21 215.652
-42.41 3907.02 216.289
-43.19 3952.48 216.848
-43.69 4044.59 217.314
-44.15 4072.19 217.776
-44.77 4088.49 218.338
-45.57 4126.39 218.917
-46.32 4176.28 219.427
-47.07 4260.08 219.956
-47.66 4329.46 220.573
-48.63 4328.33 221.201
-49.42 4345.51 221.719
-50.41 4510.73 222.281
-51.27 4552.14 222.933
-52.35 4603.65 223.583
-53.51 4605.65 224.152
-54.65 4615.64 224.737
-55.82 4644.93 225.418
-56.92 4656.23 226.117
-58.18 4678.96 226.754
-59.55 4566.62 227.389
-61.01 4562.25 228.07
-62.59 4651.86 228.689
-64.15 4739.16 229.155
-65.37 4696.82 229.674
-66.65 4753.02 230.301
-67.87 4693.76 230.903
-68.86 4615.89 231.395
-69.72 4634.88 231.906
-70.66 4612.08 232.498
-71.44 4618.26 233.074
-72.08 4662.97 233.546
-72.83 4763.57 234.028
-73.48 4849    234.603
-74.19 4939.23 235.153
-75.02 5053.56 235.605
-75.58 5132.87 236.082
-76.25 5170.34 236.657
-76.81 5203.68 237.232
-77.63 5257.26 237.673
-78.25 5283.73 238.176
-78.76 5359.6  238.789
-79.45 5393.57 239.387
-79.81 5460.83 239.861
-80.22 5466.95 240.368
-80.84 5496.29 240.962
-81.45 5526.77 241.539
-82.09 5561.8  242.009
-82.68 5618    242.52
-83.33 5667.39 243.12
-84.09 5750.57 243.721
-84.67 5785.29 244.208
-85.56 5844.05 244.716
-86.66 5878.7  245.354
-87.44 5952.83 245.966
-88.45 6010.96 246.46
-89.39 6055.61 247.017
-90.13 6087.96 247.698
-90.88 6093.51 248.374
-92    6152.59 248.928
-93.18 6171.57 249.564
-94.14 6142.1  250.299
-95.11 6078.96 251.031
-96.27 6047.49 251.65
-97    6074.66 252.295
-97.7  6090.14 253.033
-98.31 6105.25 253.743
-99.13 6175.69 254.338
-99.79 6214.22 255.032
-100.17 6260.74 255.815
-100.88 6327.12 256.543
-101.84 6327.93 257.151
-102.35 6359.9  257.785
-102.83 6393.5  258.516
-103.51 6476.86 259.191
-104.13 6524.5  259.738
-104.71 6600.31 260.351
-105.39 6629.47 261.04
-106.09 6688.61 261.692
-106.75 6717.46 262.236
-107.24 6724.2  262.847
-107.75 6779.53 263.527
-108.29 6825.8  264.169
-108.91 6882    264.681
-109.24 6983.91 265.258
-109.74 7020    265.887
-110.23 7093.12 266.491
-111    7166.68 266.987
-111.43 7236.5  267.545
-111.76 7311.24 268.171
-112.08 7364.63 268.815
-];
-%GDPD  GDPQ   GPOP
-
-series = zeros(193,2);
-series(:,2) = data_q(:,1);
-series(:,1) = 1000*data_q(:,2)./data_q(:,3);
-
-Y_obs = series(:,1);
-P_obs = series(:,2);
-
-series = series(2:193,:)./series(1:192,:);
-
-gy_obs = series(:,1);
-gp_obs = series(:,2);
-
+data_q = [
+18.02 1474.5 150.2
+17.94 1538.2 150.9
+18.01 1584.5 151.4
+18.42 1644.1 152
+18.73 1678.6 152.7
+19.46 1693.1 153.3
+19.55 1724   153.9
+19.56 1758.2 154.7
+19.79 1760.6 155.4
+19.77 1779.2 156
+19.82 1778.8 156.6
+20.03 1790.9 157.3
+20.12 1846   158
+20.1  1882.6 158.6
+20.14 1897.3 159.2
+20.22 1887.4 160
+20.27 1858.2 160.7
+20.34 1849.9 161.4
+20.39 1848.5 162
+20.42 1868.9 162.8
+20.47 1905.6 163.6
+20.56 1959.6 164.3
+20.62 1994.4 164.9
+20.78 2020.1 165.7
+21    2030.5 166.5
+21.2  2023.6 167.2
+21.33 2037.7 167.9
+21.62 2033.4 168.7
+21.71 2066.2 169.5
+22.01 2077.5 170.2
+22.15 2071.9 170.9
+22.27 2094   171.7
+22.29 2070.8 172.5
+22.56 2012.6 173.1
+22.64 2024.7 173.8
+22.77 2072.3 174.5
+22.88 2120.6 175.3
+22.92 2165   176.045
+22.91 2223.3  176.727
+22.94 2221.4  177.481
+23.03 2230.95 178.268
+23.13 2279.22 179.694
+23.22 2265.48 180.335
+23.32 2268.29 181.094
+23.4  2238.57 181.915
+23.45 2251.68 182.634
+23.51 2292.02 183.337
+23.56 2332.61 184.103
+23.63 2381.01 184.894
+23.75 2422.59 185.553
+23.81 2448.01 186.203
+23.87 2471.86 186.926
+23.94 2476.67 187.68
+24    2508.7  188.299
+24.07 2538.05 188.906
+24.12 2586.26 189.631
+24.29 2604.62 190.362
+24.35 2666.69 190.954
+24.41 2697.54 191.56
+24.52 2729.63 192.256
+24.64 2739.75 192.938
+24.77 2808.88 193.467
+24.88 2846.34 193.994
+25.01 2898.79 194.647
+25.17 2970.48 195.279
+25.32 3042.35 195.763
+25.53 3055.53 196.277
+25.79 3076.51 196.877
+26.02 3102.36 197.481
+26.14 3127.15 197.967
+26.31 3129.53 198.455
+26.6  3154.19 199.012
+26.9  3177.98 199.572
+27.21 3236.18 199.995
+27.49 3292.07 200.452
+27.75 3316.11 200.997
+28.12 3331.22 201.538
+28.39 3381.86 201.955
+28.73 3390.23 202.419
+29.14 3409.65 202.986
+29.51 3392.6  203.584
+29.94 3386.49 204.086
+30.36 3391.61 204.721
+30.61 3422.95 205.419
+31.02 3389.36 206.13
+31.5  3481.4  206.763
+31.93 3500.95 207.362
+32.27 3523.8  208
+32.54 3533.79 208.642
+33.02 3604.73 209.142
+33.2  3687.9  209.637
+33.49 3726.18 210.181
+33.95 3790.44 210.737
+34.36 3892.22 211.192
+34.94 3919.01 211.663
+35.61 3907.08 212.191
+36.29 3947.11 212.708
+37.01 3908.15 213.144
+37.79 3922.57 213.602
+38.96 3879.98 214.147
+40.13 3854.13 214.7
+41.05 3800.93 215.135
+41.66 3835.21 215.652
+42.41 3907.02 216.289
+43.19 3952.48 216.848
+43.69 4044.59 217.314
+44.15 4072.19 217.776
+44.77 4088.49 218.338
+45.57 4126.39 218.917
+46.32 4176.28 219.427
+47.07 4260.08 219.956
+47.66 4329.46 220.573
+48.63 4328.33 221.201
+49.42 4345.51 221.719
+50.41 4510.73 222.281
+51.27 4552.14 222.933
+52.35 4603.65 223.583
+53.51 4605.65 224.152
+54.65 4615.64 224.737
+55.82 4644.93 225.418
+56.92 4656.23 226.117
+58.18 4678.96 226.754
+59.55 4566.62 227.389
+61.01 4562.25 228.07
+62.59 4651.86 228.689
+64.15 4739.16 229.155
+65.37 4696.82 229.674
+66.65 4753.02 230.301
+67.87 4693.76 230.903
+68.86 4615.89 231.395
+69.72 4634.88 231.906
+70.66 4612.08 232.498
+71.44 4618.26 233.074
+72.08 4662.97 233.546
+72.83 4763.57 234.028
+73.48 4849    234.603
+74.19 4939.23 235.153
+75.02 5053.56 235.605
+75.58 5132.87 236.082
+76.25 5170.34 236.657
+76.81 5203.68 237.232
+77.63 5257.26 237.673
+78.25 5283.73 238.176
+78.76 5359.6  238.789
+79.45 5393.57 239.387
+79.81 5460.83 239.861
+80.22 5466.95 240.368
+80.84 5496.29 240.962
+81.45 5526.77 241.539
+82.09 5561.8  242.009
+82.68 5618    242.52
+83.33 5667.39 243.12
+84.09 5750.57 243.721
+84.67 5785.29 244.208
+85.56 5844.05 244.716
+86.66 5878.7  245.354
+87.44 5952.83 245.966
+88.45 6010.96 246.46
+89.39 6055.61 247.017
+90.13 6087.96 247.698
+90.88 6093.51 248.374
+92    6152.59 248.928
+93.18 6171.57 249.564
+94.14 6142.1  250.299
+95.11 6078.96 251.031
+96.27 6047.49 251.65
+97    6074.66 252.295
+97.7  6090.14 253.033
+98.31 6105.25 253.743
+99.13 6175.69 254.338
+99.79 6214.22 255.032
+100.17 6260.74 255.815
+100.88 6327.12 256.543
+101.84 6327.93 257.151
+102.35 6359.9  257.785
+102.83 6393.5  258.516
+103.51 6476.86 259.191
+104.13 6524.5  259.738
+104.71 6600.31 260.351
+105.39 6629.47 261.04
+106.09 6688.61 261.692
+106.75 6717.46 262.236
+107.24 6724.2  262.847
+107.75 6779.53 263.527
+108.29 6825.8  264.169
+108.91 6882    264.681
+109.24 6983.91 265.258
+109.74 7020    265.887
+110.23 7093.12 266.491
+111    7166.68 266.987
+111.43 7236.5  267.545
+111.76 7311.24 268.171
+112.08 7364.63 268.815
+];
+%GDPD  GDPQ   GPOP
+
+series = zeros(193,2);
+series(:,2) = data_q(:,1);
+series(:,1) = 1000*data_q(:,2)./data_q(:,3);
+
+Y_obs = series(:,1);
+P_obs = series(:,2);
+
+series = series(2:193,:)./series(1:192,:);
+
+gy_obs = series(:,1);
+gp_obs = series(:,2);
+
 ti = [1950:0.25:1997.75];
\ No newline at end of file
diff --git a/tests/Makefile.am b/tests/Makefile.am
index bd5e7f5055ae2ab69b3d3335946eecac0d9f06fe..e1f8792521e2c902ce78019416ac43655fdd3702 100644
--- a/tests/Makefile.am
+++ b/tests/Makefile.am
@@ -7,6 +7,7 @@ MODFILES = \
 	example1_with_tags.mod \
 	example1_irf_shocks.mod \
 	example1_abs_sign.mod \
+	example1_macroif.mod \
 	t_sgu_ex1.mod \
 	osr_example.mod \
 	optimal_policy/ramsey.mod \
@@ -26,7 +27,6 @@ MODFILES = \
 	histval_sto.mod \
 	histval_det.mod \
 	auxiliary_variables/test1.mod \
-	deterministic_model_purely_forward.mod \
 	expectations/expectation.mod \
 	expectations/expectation_ss.mod \
 	expectations/expectation_ss_old.mod \
@@ -49,6 +49,7 @@ MODFILES = \
 	k_order_perturbation/fs2000k2_m.mod \
 	k_order_perturbation/fs2000k_1_m.mod \
 	k_order_perturbation/fs2000k3_m.mod \
+	k_order_perturbation/fs2000k3_p.mod \
 	partial_information/PItest3aHc0PCLsimModPiYrVarobsAll.mod \
 	partial_information/PItest3aHc0PCLsimModPiYrVarobsCNR.mod \
 	arima/mod1.mod \
@@ -65,6 +66,9 @@ MODFILES = \
 	fs2000/fs2000d.mod \
 	fs2000/fs2000_cmaes.mod \
 	fs2000/fs2000_calib.mod \
+	fs2000/fs2000_analytic_derivation.mod \
+	fs2000/fs2000_particle.mod \
+	fs2000/fs2000_missing_data.mod \
 	homotopy/homotopy1_test.mod \
 	homotopy/homotopy2_test.mod \
 	homotopy/homotopy3_test.mod \
@@ -126,13 +130,18 @@ MODFILES = \
 	second_order/ds1.mod \
 	second_order/ds2.mod \
 	ep/rbc.mod \
+	ep/rbc2.mod \
+	ep/rbcii.mod \
 	ep/linear.mod \
 	deterministic_simulations/deterministic_model_purely_forward.mod \
+	deterministic_simulations/deterministic_model_purely_backward.mod \
 	deterministic_simulations/rbc_det1.mod \
 	deterministic_simulations/rbc_det2.mod \
 	deterministic_simulations/rbc_det3.mod \
 	deterministic_simulations/rbc_det4.mod \
-	deterministic_simulations/rbc_det5.mod
+	deterministic_simulations/rbc_det5.mod \
+	fs2000/fs2000_sd.mod \
+	walsh.mod
 
 EXTRA_DIST = \
 	$(MODFILES) \
@@ -185,8 +194,7 @@ EXTRA_DIST = \
 	kalman_filter_smoother/fsdat_simul.m \
 	kalman_filter_smoother/fs2000a_steadystate.m \
 	identification/kim/kim2_steadystate.m \
-	ep/mean_preserving_spread.m \
-	ep/rbc_steadystate.m
+	ep/mean_preserving_spread.m
 
 TARGETS =
 
diff --git a/tests/analytic_derivatives/ls2003.mod b/tests/analytic_derivatives/ls2003.mod
index f35a6149f12718bb17f6597187a1848a0e17a1e5..16ee793749eab2cfc03e9e8d054418f0b42eb872 100644
--- a/tests/analytic_derivatives/ls2003.mod
+++ b/tests/analytic_derivatives/ls2003.mod
@@ -61,9 +61,6 @@ stderr e_ys,inv_gamma_pdf,1.2533,0.6551;
 stderr e_pies,inv_gamma_pdf,1.88,0.9827;
 end;
 
-options_.analytic_derivation=1;
 estimation(datafile=data_ca1,first_obs=8,nobs=79,mh_nblocks=2,
-   prefilter=1,mh_jscale=0.5,mh_replic=0, mode_compute=1);
+   prefilter=1,mh_jscale=0.5,mh_replic=0, mode_compute=1, analytic_derivation);
 
-identification;
-  
diff --git a/tests/block_bytecode/example1_varexo_det_bytecode.mod b/tests/block_bytecode/example1_varexo_det_bytecode.mod
index e567161f90f5a3d577840f82dc58298ee21819ab..7bad4480c298960e0e95a8b07bb6e5a1d3ce8568 100644
--- a/tests/block_bytecode/example1_varexo_det_bytecode.mod
+++ b/tests/block_bytecode/example1_varexo_det_bytecode.mod
@@ -1,58 +1,58 @@
-// Test for varexo_det and forecast command at order 1
-
-var y, c, k, a, h, b;
-varexo e,u;
-varexo_det ahat, bhat;
-
-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(bytecode);
-model;
-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 = ahat+ rho*a(-1)+tau*b(-1) + e;
-b = bhat+ tau*a(-1)+rho*b(-1) + u;
-end;
-
-initval;
-y = 1.08068253095672;
-c = 0.80359242014163;
-h = 0.29175631001732;
-k = 5;
-a = 0;
-b = 0;
-e = 0;
-u = 0;
-ahat = 0;
-bhat = 0;
-end;
-
-//simul(periods=20);
-shocks;
-var e; stderr 0.009;
-var u; stderr 0.009;
-var e, u = phi*0.009*0.009;
-var ahat;
-periods 1;
-values 0.1;
-var bhat;
-periods 2;
-values 0.2;
-end;
-
-stoch_simul(order=1,irf=0,noprint);
-
-forecast(periods=20);
+// Test for varexo_det and forecast command at order 1
+
+var y, c, k, a, h, b;
+varexo e,u;
+varexo_det ahat, bhat;
+
+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(bytecode);
+model;
+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 = ahat+ rho*a(-1)+tau*b(-1) + e;
+b = bhat+ tau*a(-1)+rho*b(-1) + u;
+end;
+
+initval;
+y = 1.08068253095672;
+c = 0.80359242014163;
+h = 0.29175631001732;
+k = 5;
+a = 0;
+b = 0;
+e = 0;
+u = 0;
+ahat = 0;
+bhat = 0;
+end;
+
+//simul(periods=20);
+shocks;
+var e; stderr 0.009;
+var u; stderr 0.009;
+var e, u = phi*0.009*0.009;
+var ahat;
+periods 1;
+values 0.1;
+var bhat;
+periods 2;
+values 0.2;
+end;
+
+stoch_simul(order=1,irf=0,noprint);
+
+forecast(periods=20);
diff --git a/tests/deterministic_model_purely_forward.mod b/tests/deterministic_model_purely_forward.mod
deleted file mode 100644
index c13e5e0559761d17fdfe4530ae82be767caa921f..0000000000000000000000000000000000000000
--- a/tests/deterministic_model_purely_forward.mod
+++ /dev/null
@@ -1,54 +0,0 @@
-var y i pi rbar ;
-
-varexo r tauw taus taua gn;
-
-parameters khia khiw khis phipi phiy taubs taubw tauba w sigma psi kappa alpha mu beta teta;
-
-teta = 12.7721;
-sigma = 1.1599;
-beta = 0.9970;
-alpha = 0.7747;
-mu = 0.9030;
-taubs = 0.05;
-taubw = 0.02;
-tauba = 0;
-w = 1.5692;
-phipi = 1.5;
-phiy = 0.5/4;
-
-khia = (1-beta)/(1-tauba);
-khiw = 1/(1-taubw);
-khis = 1/(1+taubs);
-psi = 1/(sigma + w);
-kappa = (1-alpha)*(1-alpha*beta)*(sigma+w)/(alpha*(1+w*teta));
-
-model(linear);
-y = y(+1)-sigma*(i-pi(+1)-r)+(gn-gn(+1))+(sigma)^-1*khis*(taus(+1)-taus)+sigma*khia*taua;
-
-pi=kappa*y+kappa*psi*(khiw*tauw+khis*taus-sigma*gn)+beta*pi(+1);
-
-i=max(0,r+phipi*pi+phiy*y);
-
-rbar = -((kappa*phipi+(1-beta*mu)*phiy)*sigma^-1*khia*taus)/((1-mu+sigma^-1*phiy)*(1-beta*mu)+kappa*sigma^-1*(phipi-mu))
-- (((1-mu)*kappa*psi*phipi+sigma^-1*mu*kappa*psi*phiy)*khiw*tauw)/((1-mu+sigma^-1*phiy)*(1-beta*mu)+kappa*sigma*(phipi-mu))
--(kappa*sigma*(1-mu)*(sigma^-1-psi)*phipi+((1-mu)*(1-beta*mu)-kappa*psi*mu)*phiy)*(gn-sigma^-1*khis*taus)/((1-mu-sigma^-1*phiy)*(1-beta*mu)+kappa*sigma^-1*(phipi-mu));
-
-end;
-
-initval;
-y=0;
-i=-log(beta);
-pi=0;
-rbar = 0;
-end;
-
-steady;
-check;
-
-shocks;
-var r;
-periods 1:9;
-values -0.0104;
-end;
-
-simul(periods=2100);
diff --git a/tests/deterministic_simulations/deterministic_model_purely_backward.mod b/tests/deterministic_simulations/deterministic_model_purely_backward.mod
new file mode 100644
index 0000000000000000000000000000000000000000..89d8014dc9610e939f49401c82b8f9b30588377e
--- /dev/null
+++ b/tests/deterministic_simulations/deterministic_model_purely_backward.mod
@@ -0,0 +1,27 @@
+var y;
+varexo eps;
+parameters rho1 rho2;
+
+rho1 = 0.1;
+
+rho2 = 0.2;
+
+model;
+log(y) = rho1*log(y(-1)) + rho2*log(y(-2)) + eps;
+end;
+
+initval;
+y=1;
+eps=0;
+end;
+
+steady;
+check;
+
+shocks;
+var eps;
+periods 1:9;
+values -0.0104;
+end;
+
+simul(periods=100);
diff --git a/tests/dsge-var/dsgevar_forward_calibrated_lambda.mod b/tests/dsge-var/dsgevar_forward_calibrated_lambda.mod
index 0f863906179394f501115205ee9b78359ba0da4c..6ebf5c2792bafd216bcd9aae08c4e39df6e438e0 100644
--- a/tests/dsge-var/dsgevar_forward_calibrated_lambda.mod
+++ b/tests/dsge-var/dsgevar_forward_calibrated_lambda.mod
@@ -1,79 +1,79 @@
-//$ Declaration of the endogenous variables of the DSGE model.
-var a g mc mrs n winf pie r rw y;
-
-//$ Declaration of the exogenous variables of the DSGE model.
-varexo e_a e_g e_lam e_ms;
-
-//$ Declaration of the deep parameters
-parameters invsig delta gam rho gampie gamy rhoa rhog bet
-	   thetabig omega eps ;
-
-eps=6;
-thetabig=2;
-bet=0.99;
-invsig=2.5;
-gampie=1.5;
-gamy=0.125;
-gam=1;
-delta=0.36;
-omega=0.54;
-rhoa=0.5;
-rhog=0.5;
-rho=0.5;
-
-
-//$ Specification of the DSGE model used as a prior of the VAR model.
-model(linear);
-
-	y=y(+1)-(1/invsig)*(r-pie(+1)+g(+1)-g);
-	y=a+(1-delta)*n;
-	mc=rw+n-y;
-	mrs=invsig*y+gam*n-g;
-	r=rho*r(-1)+(1-rho)*(gampie*pie+gamy*y)+e_ms;
-	rw=rw(-1)+winf-pie;
-	a=rhoa*a(-1)+e_a;
-	g=rhog*g(-1)+e_g;
-	rw=mrs;
-
-	//$ HYBRID PHILLIPS CURVED USED FOR THE SUMULATIONS:
-	//   pie = (omega/(1+omega*bet))*pie(-1)+(bet/(1+omega*bet))*pie(1)+(1-delta)*
-      	//   (1-(1-1/thetabig)*bet)*(1-(1-1/thetabig))/((1-1/thetabig)*(1+delta*(eps-1)))/(1+omega*bet)*(mc+e_lam);
-
-	//$ FORWARD LOOKING PHILLIPS CURVE:
-	    pie=bet*pie(+1)+(1-delta)*(1-(1-1/thetabig)*bet)*(1-(1-1/thetabig))/((1-1/thetabig)*(1+delta*(eps-1)))*(mc+e_lam);
-end;
-
-
-
-//$ Declaration of the prior beliefs about the deep parameters.
-estimated_params;
-    stderr e_a, uniform_pdf,,,0,2;
-    stderr e_g, uniform_pdf,,,0,2;
-    stderr e_ms, uniform_pdf,,,0,2;
-    stderr e_lam, uniform_pdf,,,0,2;
-
-    invsig, gamma_pdf, 2.5, 1.76;
-    gam, normal_pdf, 1, 0.5;
-    rho, uniform_pdf,,,0,1;
-    gampie, normal_pdf, 1.5, 0.25;
-    gamy, gamma_pdf, 0.125, 0.075;
-    rhoa, uniform_pdf,,,0,1;
-    rhog, uniform_pdf,,,0,1;
-    thetabig, gamma_pdf, 3, 1.42, 1, ;
-
-    //$Parameter for the hybrid Phillips curve
-    //omega, uniform_pdf,,,0,1;
-
-end;
-
-
-//$ Declaration of the observed endogenous variables. Note that they are the variables of the VAR (4 by default) and that we must
-//$ have as many observed variables as exogenous variables.
-varobs pie r rw y;
-
-options_.gradient_method = 3;
-
-//$ The option bayesian_irf triggers the computation of the DSGE-VAR and DSGE posterior distribution of the IRFs.
-//$ The Dashed lines are the first, fifth (ie the median) and ninth posterior deciles of the DSGE-VAR's IRFs, the bold dark curve is the
-//$ posterior median of the DSGE's IRfs and the shaded surface covers the space between the first and ninth posterior deciles of the DSGE's IRFs.
-estimation(datafile=datarabanal_hybrid,first_obs=50,mh_nblocks = 1,nobs=90,dsge_var=.8,mode_compute=4,mh_replic=2000,bayesian_irf);
+//$ Declaration of the endogenous variables of the DSGE model.
+var a g mc mrs n winf pie r rw y;
+
+//$ Declaration of the exogenous variables of the DSGE model.
+varexo e_a e_g e_lam e_ms;
+
+//$ Declaration of the deep parameters
+parameters invsig delta gam rho gampie gamy rhoa rhog bet
+	   thetabig omega eps ;
+
+eps=6;
+thetabig=2;
+bet=0.99;
+invsig=2.5;
+gampie=1.5;
+gamy=0.125;
+gam=1;
+delta=0.36;
+omega=0.54;
+rhoa=0.5;
+rhog=0.5;
+rho=0.5;
+
+
+//$ Specification of the DSGE model used as a prior of the VAR model.
+model(linear);
+
+	y=y(+1)-(1/invsig)*(r-pie(+1)+g(+1)-g);
+	y=a+(1-delta)*n;
+	mc=rw+n-y;
+	mrs=invsig*y+gam*n-g;
+	r=rho*r(-1)+(1-rho)*(gampie*pie+gamy*y)+e_ms;
+	rw=rw(-1)+winf-pie;
+	a=rhoa*a(-1)+e_a;
+	g=rhog*g(-1)+e_g;
+	rw=mrs;
+
+	//$ HYBRID PHILLIPS CURVED USED FOR THE SUMULATIONS:
+	//   pie = (omega/(1+omega*bet))*pie(-1)+(bet/(1+omega*bet))*pie(1)+(1-delta)*
+      	//   (1-(1-1/thetabig)*bet)*(1-(1-1/thetabig))/((1-1/thetabig)*(1+delta*(eps-1)))/(1+omega*bet)*(mc+e_lam);
+
+	//$ FORWARD LOOKING PHILLIPS CURVE:
+	    pie=bet*pie(+1)+(1-delta)*(1-(1-1/thetabig)*bet)*(1-(1-1/thetabig))/((1-1/thetabig)*(1+delta*(eps-1)))*(mc+e_lam);
+end;
+
+
+
+//$ Declaration of the prior beliefs about the deep parameters.
+estimated_params;
+    stderr e_a, uniform_pdf,,,0,2;
+    stderr e_g, uniform_pdf,,,0,2;
+    stderr e_ms, uniform_pdf,,,0,2;
+    stderr e_lam, uniform_pdf,,,0,2;
+
+    invsig, gamma_pdf, 2.5, 1.76;
+    gam, normal_pdf, 1, 0.5;
+    rho, uniform_pdf,,,0,1;
+    gampie, normal_pdf, 1.5, 0.25;
+    gamy, gamma_pdf, 0.125, 0.075;
+    rhoa, uniform_pdf,,,0,1;
+    rhog, uniform_pdf,,,0,1;
+    thetabig, gamma_pdf, 3, 1.42, 1, ;
+
+    //$Parameter for the hybrid Phillips curve
+    //omega, uniform_pdf,,,0,1;
+
+end;
+
+
+//$ Declaration of the observed endogenous variables. Note that they are the variables of the VAR (4 by default) and that we must
+//$ have as many observed variables as exogenous variables.
+varobs pie r rw y;
+
+options_.gradient_method = 3;
+
+//$ The option bayesian_irf triggers the computation of the DSGE-VAR and DSGE posterior distribution of the IRFs.
+//$ The Dashed lines are the first, fifth (ie the median) and ninth posterior deciles of the DSGE-VAR's IRFs, the bold dark curve is the
+//$ posterior median of the DSGE's IRfs and the shaded surface covers the space between the first and ninth posterior deciles of the DSGE's IRFs.
+estimation(datafile=datarabanal_hybrid,first_obs=50,mh_nblocks = 1,nobs=90,dsge_var=.8,mode_compute=4,mh_replic=2000,bayesian_irf);
diff --git a/tests/dsge-var/dsgevar_forward_estimated_lambda.mod b/tests/dsge-var/dsgevar_forward_estimated_lambda.mod
index f9ae240a019659422f9ca314e8b9cd5ad5aa5e51..a0da9f718bce29508f542029c7403e9910799c16 100644
--- a/tests/dsge-var/dsgevar_forward_estimated_lambda.mod
+++ b/tests/dsge-var/dsgevar_forward_estimated_lambda.mod
@@ -1,80 +1,80 @@
-//$ Declaration of the endogenous variables of the DSGE model.
-var a g mc mrs n winf pie r rw y;
-
-//$ Declaration of the exogenous variables of the DSGE model.
-varexo e_a e_g e_lam e_ms;
-
-//$ Declaration of the deep parameters and of dsge_prior_weight
-parameters invsig delta gam rho gampie gamy rhoa rhog bet
-	   thetabig omega eps ;
-
-eps=6;
-thetabig=2;
-bet=0.99;
-invsig=2.5;
-gampie=1.5;
-gamy=0.125;
-gam=1;
-delta=0.36;
-omega=0.54;
-rhoa=0.5;
-rhog=0.5;
-rho=0.5;
-
-
-//$ Specification of the DSGE model used as a prior of the VAR model.
-model(linear);
-
-	y=y(+1)-(1/invsig)*(r-pie(+1)+g(+1)-g);
-	y=a+(1-delta)*n;
-	mc=rw+n-y;
-	mrs=invsig*y+gam*n-g;
-	r=rho*r(-1)+(1-rho)*(gampie*pie+gamy*y)+e_ms;
-	rw=rw(-1)+winf-pie;
-	a=rhoa*a(-1)+e_a;
-	g=rhog*g(-1)+e_g;
-	rw=mrs;
-
-	//$ HYBRID PHILLIPS CURVED USED FOR THE SUMULATIONS:
-	//   pie = (omega/(1+omega*bet))*pie(-1)+(bet/(1+omega*bet))*pie(1)+(1-delta)*
-      	//   (1-(1-1/thetabig)*bet)*(1-(1-1/thetabig))/((1-1/thetabig)*(1+delta*(eps-1)))/(1+omega*bet)*(mc+e_lam);
-
-	//$ FORWARD LOOKING PHILLIPS CURVE:
-	    pie=bet*pie(+1)+(1-delta)*(1-(1-1/thetabig)*bet)*(1-(1-1/thetabig))/((1-1/thetabig)*(1+delta*(eps-1)))*(mc+e_lam);
-end;
-
-
-
-//$ Declaration of the prior beliefs about the deep parameters and the weight of the DSGE prior.
-estimated_params;
-    stderr e_a, uniform_pdf,,,0,2;
-    stderr e_g, uniform_pdf,,,0,2;
-    stderr e_ms, uniform_pdf,,,0,2;
-    stderr e_lam, uniform_pdf,,,0,2;
-
-    invsig, gamma_pdf, 2.5, 1.76;
-    gam, normal_pdf, 1, 0.5;
-    rho, uniform_pdf,,,0,1;
-    gampie, normal_pdf, 1.5, 0.25;
-    gamy, gamma_pdf, 0.125, 0.075;
-    rhoa, uniform_pdf,,,0,1;
-    rhog, uniform_pdf,,,0,1;
-    thetabig, gamma_pdf, 3, 1.42, 1, ;
-
-    //$Parameter for the hybrid Phillips curve
-    //omega, uniform_pdf,,,0,1;
-
-    dsge_prior_weight, uniform_pdf,,,0,1.9;
-end;
-
-
-//$ Declaration of the observed endogenous variables. Note that they are the variables of the VAR (4 by default) and that we must
-//$ have as many observed variables as exogenous variables.
-varobs pie r rw y;
-
-options_.gradient_method = 3;
-
-//$ The option bayesian_irf triggers the computation of the DSGE-VAR and DSGE posterior distribution of the IRFs.
-//$ The Dashed lines are the first, fifth (ie the median) and ninth posterior deciles of the DSGE-VAR's IRFs, the bold dark curve is the
-//$ posterior median of the DSGE's IRfs and the shaded surface covers the space between the first and ninth posterior deciles of the DSGE's IRFs.
-estimation(datafile=datarabanal_hybrid,first_obs=50,mh_nblocks = 1,nobs=90,dsge_var,mode_compute=4,mh_replic=2000,bayesian_irf);
+//$ Declaration of the endogenous variables of the DSGE model.
+var a g mc mrs n winf pie r rw y;
+
+//$ Declaration of the exogenous variables of the DSGE model.
+varexo e_a e_g e_lam e_ms;
+
+//$ Declaration of the deep parameters and of dsge_prior_weight
+parameters invsig delta gam rho gampie gamy rhoa rhog bet
+	   thetabig omega eps ;
+
+eps=6;
+thetabig=2;
+bet=0.99;
+invsig=2.5;
+gampie=1.5;
+gamy=0.125;
+gam=1;
+delta=0.36;
+omega=0.54;
+rhoa=0.5;
+rhog=0.5;
+rho=0.5;
+
+
+//$ Specification of the DSGE model used as a prior of the VAR model.
+model(linear);
+
+	y=y(+1)-(1/invsig)*(r-pie(+1)+g(+1)-g);
+	y=a+(1-delta)*n;
+	mc=rw+n-y;
+	mrs=invsig*y+gam*n-g;
+	r=rho*r(-1)+(1-rho)*(gampie*pie+gamy*y)+e_ms;
+	rw=rw(-1)+winf-pie;
+	a=rhoa*a(-1)+e_a;
+	g=rhog*g(-1)+e_g;
+	rw=mrs;
+
+	//$ HYBRID PHILLIPS CURVED USED FOR THE SUMULATIONS:
+	//   pie = (omega/(1+omega*bet))*pie(-1)+(bet/(1+omega*bet))*pie(1)+(1-delta)*
+      	//   (1-(1-1/thetabig)*bet)*(1-(1-1/thetabig))/((1-1/thetabig)*(1+delta*(eps-1)))/(1+omega*bet)*(mc+e_lam);
+
+	//$ FORWARD LOOKING PHILLIPS CURVE:
+	    pie=bet*pie(+1)+(1-delta)*(1-(1-1/thetabig)*bet)*(1-(1-1/thetabig))/((1-1/thetabig)*(1+delta*(eps-1)))*(mc+e_lam);
+end;
+
+
+
+//$ Declaration of the prior beliefs about the deep parameters and the weight of the DSGE prior.
+estimated_params;
+    stderr e_a, uniform_pdf,,,0,2;
+    stderr e_g, uniform_pdf,,,0,2;
+    stderr e_ms, uniform_pdf,,,0,2;
+    stderr e_lam, uniform_pdf,,,0,2;
+
+    invsig, gamma_pdf, 2.5, 1.76;
+    gam, normal_pdf, 1, 0.5;
+    rho, uniform_pdf,,,0,1;
+    gampie, normal_pdf, 1.5, 0.25;
+    gamy, gamma_pdf, 0.125, 0.075;
+    rhoa, uniform_pdf,,,0,1;
+    rhog, uniform_pdf,,,0,1;
+    thetabig, gamma_pdf, 3, 1.42, 1, ;
+
+    //$Parameter for the hybrid Phillips curve
+    //omega, uniform_pdf,,,0,1;
+
+    dsge_prior_weight, uniform_pdf,,,0,1.9;
+end;
+
+
+//$ Declaration of the observed endogenous variables. Note that they are the variables of the VAR (4 by default) and that we must
+//$ have as many observed variables as exogenous variables.
+varobs pie r rw y;
+
+options_.gradient_method = 3;
+
+//$ The option bayesian_irf triggers the computation of the DSGE-VAR and DSGE posterior distribution of the IRFs.
+//$ The Dashed lines are the first, fifth (ie the median) and ninth posterior deciles of the DSGE-VAR's IRFs, the bold dark curve is the
+//$ posterior median of the DSGE's IRfs and the shaded surface covers the space between the first and ninth posterior deciles of the DSGE's IRFs.
+estimation(datafile=datarabanal_hybrid,first_obs=50,mh_nblocks = 1,nobs=90,dsge_var,mode_compute=4,mh_replic=2000,bayesian_irf);
diff --git a/tests/dsge-var/simul_hybrid.mod b/tests/dsge-var/simul_hybrid.mod
index 130ec4b6942cd167418e7e8bc5f6e15262ae4cec..311d3f9d005fa7e10d426e3d35c7a6e9e73460cb 100644
--- a/tests/dsge-var/simul_hybrid.mod
+++ b/tests/dsge-var/simul_hybrid.mod
@@ -1,51 +1,51 @@
-var a g mc mrs n pie r rw winf y;
-varexo e_a e_g e_lam e_ms;
-
-parameters invsig delta gam rho gampie gamy rhoa rhog bet 
-    	   thetabig omega eps;
-
-eps=6;
-thetabig=2;
-bet=0.99;
-invsig=2.5;
-gampie=1.5;
-gamy=0.125;
-gam=1;
-delta=0.36;
-omega=0.54;
-rhoa=0.5;
-rhog=0.5;
-rho=0.5;
-
-
-model(linear);
-	y=y(+1)-(1/invsig)*(r-pie(+1)+g(+1)-g);
-	y=a+(1-delta)*n;
-	mc=rw+n-y;
-	mrs=invsig*y+gam*n-g;
-	r=rho*r(-1)+(1-rho)*(gampie*pie+gamy*y)+e_ms;
-	rw=rw(-1)+winf-pie;
-	a=rhoa*a(-1)+e_a;
-	g=rhog*g(-1)+e_g;
-	rw=mrs;
-
-	// HYBRID PHILLIPS CURVED USED FOR THE SUMULATIONS:
-	pie = (omega/(1+omega*bet))*pie(-1)+(bet/(1+omega*bet))*pie(1)+(1-delta)*
-      	(1-(1-1/thetabig)*bet)*(1-(1-1/thetabig))/((1-1/thetabig)*(1+delta*(eps-1)))/(1+omega*bet)*(mc+e_lam);
-
-	// FORWARD LOOKING PHILLIPS CURVE:
-	// pie=bet*pie(+1)+(1-delta)*(1-(1-1/thetabig)*bet)*(1-(1-1/thetabig))/((1-1/thetabig)*(1+delta*(eps-1)))*(mc+e_lam);
-end;
-
-shocks;
-var e_a; stderr 1;
-var e_g; stderr 1;
-var e_ms; stderr 1;
-var e_lam; stderr 1;
-end;
-
-steady;
-check;
-
-stoch_simul(periods=500,irf=0);
+var a g mc mrs n pie r rw winf y;
+varexo e_a e_g e_lam e_ms;
+
+parameters invsig delta gam rho gampie gamy rhoa rhog bet 
+    	   thetabig omega eps;
+
+eps=6;
+thetabig=2;
+bet=0.99;
+invsig=2.5;
+gampie=1.5;
+gamy=0.125;
+gam=1;
+delta=0.36;
+omega=0.54;
+rhoa=0.5;
+rhog=0.5;
+rho=0.5;
+
+
+model(linear);
+	y=y(+1)-(1/invsig)*(r-pie(+1)+g(+1)-g);
+	y=a+(1-delta)*n;
+	mc=rw+n-y;
+	mrs=invsig*y+gam*n-g;
+	r=rho*r(-1)+(1-rho)*(gampie*pie+gamy*y)+e_ms;
+	rw=rw(-1)+winf-pie;
+	a=rhoa*a(-1)+e_a;
+	g=rhog*g(-1)+e_g;
+	rw=mrs;
+
+	// HYBRID PHILLIPS CURVED USED FOR THE SUMULATIONS:
+	pie = (omega/(1+omega*bet))*pie(-1)+(bet/(1+omega*bet))*pie(1)+(1-delta)*
+      	(1-(1-1/thetabig)*bet)*(1-(1-1/thetabig))/((1-1/thetabig)*(1+delta*(eps-1)))/(1+omega*bet)*(mc+e_lam);
+
+	// FORWARD LOOKING PHILLIPS CURVE:
+	// pie=bet*pie(+1)+(1-delta)*(1-(1-1/thetabig)*bet)*(1-(1-1/thetabig))/((1-1/thetabig)*(1+delta*(eps-1)))*(mc+e_lam);
+end;
+
+shocks;
+var e_a; stderr 1;
+var e_g; stderr 1;
+var e_ms; stderr 1;
+var e_lam; stderr 1;
+end;
+
+steady;
+check;
+
+stoch_simul(periods=500,irf=0);
 datatomfile('datarabanal_hybrid',[]);
\ No newline at end of file
diff --git a/tests/ep/linear.mod b/tests/ep/linear.mod
index 5b4fe71227349cbdee743791b25539d4d21307fe..afc64ca4c38570d98e9ff07e604ed59d9d3f0d15 100644
--- a/tests/ep/linear.mod
+++ b/tests/ep/linear.mod
@@ -1,45 +1,45 @@
-var y pie r;
-varexo e_y e_pie;
-
-parameters delta sigma alpha kappa gamma1 gamma2;
-
-delta =  0.44;
-kappa =  0.18;
-alpha =  0.48;
-sigma = -0.06;
-
-gamma1 = 1.5;
-gamma2 = 0.5;
-
-model(use_dll);
-y  = delta * y(-1)  + (1-delta)*y(+1)+sigma *(r - pie(+1)) + e_y;
-pie  =   alpha * pie(-1) + (1-alpha) * pie(+1) + kappa*y + e_pie;
-r = gamma1*pie+gamma2*y;
-end;
-
-shocks;
-var e_y;
-stderr 0.63;
-var e_pie;
-stderr 0.4;
-end;
-
-steady;
-
-options_.maxit_ = 100;
-options_.ep.verbosity = 0;
-options_.ep.stochastic.status = 0;
-options_.ep.order = 0;
-options_.ep.nnodes = 0;
-options_.console_mode = 0;
-
-ts = extended_path([],100);
-
-options_.ep.stochastic.status = 1;
-options_.ep.order = 1;
-options_.ep.nnodes = 3;
-sts = extended_path([],100);
-
-if max(max(abs(ts-sts))) > 1e-12
-   error('extended path algorithm fails in ./tests/ep/linear.mod')
+var y pie r;
+varexo e_y e_pie;
+
+parameters delta sigma alpha kappa gamma1 gamma2;
+
+delta =  0.44;
+kappa =  0.18;
+alpha =  0.48;
+sigma = -0.06;
+
+gamma1 = 1.5;
+gamma2 = 0.5;
+
+model(use_dll);
+y  = delta * y(-1)  + (1-delta)*y(+1)+sigma *(r - pie(+1)) + e_y;
+pie  =   alpha * pie(-1) + (1-alpha) * pie(+1) + kappa*y + e_pie;
+r = gamma1*pie+gamma2*y;
+end;
+
+shocks;
+var e_y;
+stderr 0.63;
+var e_pie;
+stderr 0.4;
+end;
+
+steady;
+
+options_.maxit_ = 100;
+options_.ep.verbosity = 0;
+options_.ep.stochastic.status = 0;
+options_.ep.order = 0;
+options_.ep.nnodes = 0;
+options_.console_mode = 0;
+
+ts = extended_path([],100);
+
+options_.ep.stochastic.status = 1;
+options_.ep.order = 1;
+options_.ep.nnodes = 3;
+sts = extended_path([],100);
+
+if max(max(abs(ts-sts))) > 1e-12
+   error('extended path algorithm fails in ./tests/ep/linear.mod')
 end
\ No newline at end of file
diff --git a/tests/ep/mean_preserving_spread.m b/tests/ep/mean_preserving_spread.m
index 9d988fe1281b9fc4d2f734c7232e88ad05b49d49..d296ec345259f673a58f2837b165d2b8edee9193 100644
--- a/tests/ep/mean_preserving_spread.m
+++ b/tests/ep/mean_preserving_spread.m
@@ -1,4 +1,4 @@
-function m = mean_preserving_spread(autoregressive_parameter)
+function m = mean_preserving_spread(autoregressive_parameter,sigma)
 % Computes the mean preserving spread for first order autoregressive process.
 %
 % The mean preserving spread m is a constant such that the mean of the process
@@ -13,6 +13,5 @@ function m = mean_preserving_spread(autoregressive_parameter)
 % AUTHOR(S) 
 %  stephane DOT adjemian AT univ DASH lemans DOT fr
 %  frederic DOT karame AT univ DASH evry DOT fr
-global M_
 
-m = M_.Sigma_e/(1-autoregressive_parameter*autoregressive_parameter);
\ No newline at end of file
+m = sigma/(1-autoregressive_parameter*autoregressive_parameter);
\ No newline at end of file
diff --git a/tests/ep/rbc.mod b/tests/ep/rbc.mod
index 35edc823ed13a87201aef9ad6c4e3e97655e5a6f..68280a88ed1c6bfe53d3e13803ea1e98d5b99718 100644
--- a/tests/ep/rbc.mod
+++ b/tests/ep/rbc.mod
@@ -19,7 +19,7 @@ rho     =  0.950;
 effstar =  1.000;
 sigma2  =  0.0001;
 
-external_function(name=mean_preserving_spread);
+external_function(name=mean_preserving_spread,nargs=2);
 
 model(use_dll);
 
@@ -27,7 +27,7 @@ model(use_dll);
   efficiency = rho*efficiency(-1) + EfficiencyInnovation;
 
   // Eq. n°2:
-  Efficiency = effstar*exp(efficiency-mean_preserving_spread(rho));
+  Efficiency = effstar*exp(efficiency-mean_preserving_spread(rho,sigma2));
 
   // Eq. n°3:
   Output = Efficiency*(alpha*(Capital(-1)^psi)+(1-alpha)*(Labour^psi))^(1/psi);
@@ -46,6 +46,28 @@ model(use_dll);
 
 end;
 
+steady_state_model;
+efficiency = 0;
+Efficiency = effstar*exp(efficiency-mean_preserving_spread(rho,sigma2));
+// 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 = sigma2;
 end;
@@ -57,10 +79,10 @@ options_.ep.stochastic.nodes = 2;
 options_.console_mode = 0;
 
 options_.ep.stochastic.order = 0;
-ts0 = extended_path([],100);
+//ts0 = extended_path([],100);
 
 options_.ep.stochastic.order = 1;
-ts1 = extended_path([],100);
+//ts1 = extended_path([],100);
 
 options_.ep.stochastic.order = 2;
 ts2 = extended_path([],100);
diff --git a/tests/ep/rbc2.mod b/tests/ep/rbc2.mod
new file mode 100644
index 0000000000000000000000000000000000000000..6384afadcf091315316e071c9be976f3a8708ef8
--- /dev/null
+++ b/tests/ep/rbc2.mod
@@ -0,0 +1,80 @@
+// Test preprocessor interface for extended path
+
+var Capital, Output, Labour, Consumption, Efficiency, efficiency, ExpectedTerm;
+
+varexo EfficiencyInnovation;
+
+parameters beta, theta, tau, alpha, psi, delta, rho, effstar, sigma2;
+
+/*
+** 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;
+sigma2  =  0.0001;
+
+external_function(name=mean_preserving_spread,nargs=2);
+
+model(use_dll);
+
+  // Eq. n°1:
+  efficiency = rho*efficiency(-1) + EfficiencyInnovation;
+
+  // Eq. n°2:
+  Efficiency = effstar*exp(efficiency-mean_preserving_spread(rho,sigma2));
+
+  // 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*exp(efficiency-mean_preserving_spread(rho,sigma2));
+// 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 = sigma2;
+end;
+
+steady;
+
+extended_path(periods=100);
+
diff --git a/tests/ep/rbc_steadystate.m b/tests/ep/rbc_steadystate.m
deleted file mode 100644
index 74af861d7f0ca8feb378505b59ac13dbaf035111..0000000000000000000000000000000000000000
--- a/tests/ep/rbc_steadystate.m
+++ /dev/null
@@ -1,48 +0,0 @@
-function [ys, info] = rbc_steadystate(ys, exogenous)
-% Steady state routine for rbc.mod (Business Cycle model with endogenous labour and CES production function)
-
-
-% AUTHOR(S) 
-%  stephane DOT adjemian AT univ DASH lemans DOT fr
-%  frederic DOT karame AT univ DASH evry DOT fr    
-
-% 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/effstar)^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;
-% SteadyStateLabour = 1/(1 + Consumption_per_unit_of_Labour/((theta*(1-alpha)/(1-theta))*(Output_per_unit_of_Labour^(1-psi))));
-% SteadyStateConsumption = Consumption_per_unit_of_Labour*SteadyStateLabour;
-% SteadyStateCapital = SteadyStateLabour/Labour_per_unit_of_Capital;
-% SteadyStateOutput =  Output_per_unit_of_Capital*SteadyStateCapital;
-% ShareOfCapital = alpha/(alpha+(1-alpha)*Labour_per_unit_of_Capital^psi);
-    
-global M_
-    
-info = 0;
-
-% Compute steady state ratios.
-Output_per_unit_of_Capital=((1/M_.params(1)-1+M_.params(6))/M_.params(4))^(1/(1-M_.params(5)));
-Consumption_per_unit_of_Capital=Output_per_unit_of_Capital-M_.params(6);
-Labour_per_unit_of_Capital=(((Output_per_unit_of_Capital/M_.params(8))^M_.params(5)-M_.params(4))/(1-M_.params(4)))^(1/M_.params(5));
-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=M_.params(4)/(M_.params(4)+(1-M_.params(4))*Labour_per_unit_of_Capital^M_.params(5));
-
-% Compute steady state of the endogenous variables.
-SteadyStateLabour=1/(1+Consumption_per_unit_of_Labour/((1-M_.params(4))*M_.params(2)/(1-M_.params(2))*Output_per_unit_of_Labour^(1-M_.params(5))));
-SteadyStateConsumption=Consumption_per_unit_of_Labour*SteadyStateLabour;
-SteadyStateCapital=SteadyStateLabour/Labour_per_unit_of_Capital;
-SteadyStateOutput=Output_per_unit_of_Capital*SteadyStateCapital;
-
-% Fill returned argument ys with steady state values.
-ys(2)=SteadyStateOutput;
-ys(4)=SteadyStateConsumption;
-ys(1)=SteadyStateCapital;
-ys(3)=SteadyStateLabour;
-ys(5)=M_.params(8);
-ys(6)=0;
-ys(7)=M_.params(1)*((((SteadyStateConsumption^M_.params(2))*((1-SteadyStateLabour)^(1-M_.params(2))))^(1-M_.params(3)))/SteadyStateConsumption)* ...
-      (M_.params(4)*((SteadyStateOutput/SteadyStateCapital)^(1-M_.params(5)))+1-M_.params(6));
\ No newline at end of file
diff --git a/tests/ep/rbcii.mod b/tests/ep/rbcii.mod
index 2d4046c6ada189f53c9f0f8615f8358d04add959..33b4cc62c9bb0970383b917c0927c6a0d89d69af 100644
--- a/tests/ep/rbcii.mod
+++ b/tests/ep/rbcii.mod
@@ -1,6 +1,6 @@
 @#define extended_path_version = 1
 
-var Capital, Output, Labour, Consumption, Investment, Efficiency, efficiency, ExpectedTerm;
+var Capital, Output, Labour, Consumption,  Investment, Output1, Labour1, Consumption1, Output2, Labour2, Consumption2, Efficiency, efficiency, ExpectedTerm;
 
 varexo EfficiencyInnovation;
 
@@ -26,36 +26,67 @@ sigma2  =  0.001;
     rho = 0.800;
 @#endif
 
-external_function(name=mean_preserving_spread);
+external_function(name=mean_preserving_spread,nargs=2);
 
-model(use_dll);
+model;
 
-  // Eq. n°1:
   efficiency = rho*efficiency(-1) + EfficiencyInnovation;
 
-  // Eq. n°2:
-  Efficiency = effstar*exp(efficiency-mean_preserving_spread(rho));
+  Efficiency = effstar*exp(efficiency-mean_preserving_spread(rho,sigma2));
 
-  // Eq. n°3:
-  Output = Efficiency*(alpha*(Capital(-1)^psi)+(1-alpha)*(Labour^psi))^(1/psi);
+  (((Consumption1^theta)*((1-Labour1)^(1-theta)))^(1-tau))/Consumption1 - ExpectedTerm(1);
 
-  // Eq. n°4:
-  Capital = max(Output-Consumption,0) + (1-delta)*Capital(-1);
+  ExpectedTerm = beta*((((Consumption^theta)*((1-Labour)^(1-theta)))^(1-tau))/Consumption)*(alpha*((Output/Capital(-1))^(1-psi))+1-delta);
 
-  // Eq. n°5:
-  ((1-theta)/theta)*(Consumption/(1-Labour)) - (1-alpha)*(Output/Labour)^(1-psi);
+  ((1-theta)/theta)*(Consumption1/(1-Labour1)) - (1-alpha)*(Output1/Labour1)^(1-psi);
 
-  // Eq. n°6:
-  ExpectedTerm = beta*((((Consumption^theta)*((1-Labour)^(1-theta)))^(1-tau))/Consumption)*(alpha*((Output/Capital(-1))^(1-psi))+1-delta);
+  Output1 = Efficiency*(alpha*(Capital(-1)^psi)+(1-alpha)*(Labour1^psi))^(1/psi);
 
-  // Eq. n°7:
-  Investment = Capital - (1-delta)*Capital(-1);
+  Consumption2  = Output2;
+
+  ((1-theta)/theta)*(Consumption2/(1-Labour2)) - (1-alpha)*(Output2/Labour2)^(1-psi);
+
+  Output2 = Efficiency*(alpha*(Capital(-1)^psi)+(1-alpha)*(Labour2^psi))^(1/psi);
+
+  Consumption = (Output1 > Consumption1)*Consumption1 + (1-(Output1 > Consumption1))*Consumption2;
+
+  Labour = (Output1 > Consumption1)*Labour1 + (1-(Output1 > Consumption1))*Labour2;
+
+  Output = (Output1 > Consumption1)*Output1 + (1-(Output1 > Consumption1))*Output2;
 
-  // Eq. n°8: (Euler equation, to be skipped if investment is on its lower bound)
-  (Investment>0)*((((Consumption^theta)*((1-Labour)^(1-theta)))^(1-tau))/Consumption - ExpectedTerm(1)) + (1-(Investment>0))*(Output-Consumption);
+  Capital = Output-Consumption + (1-delta)*Capital(-1);
+
+  Investment = Capital - (1-delta)*Capital(-1);
 
 end;
 
+steady_state_model;
+efficiency = 0;
+Efficiency = effstar*exp(efficiency-mean_preserving_spread(rho,sigma2));
+// 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;
+Investment = delta*Capital;
+ExpectedTerm = beta*((((Consumption^theta)*((1-Labour)^(1-theta)))^(1-tau))/Consumption)*(alpha*((Output/Capital)^(1-psi))+1-delta);
+Output1 = Output;
+Output2 = Output;
+Labour1 = Labour;
+Labour2 = Labour;
+Consumption1 = Consumption;
+Consumption2 = Consumption;
+end;
 
 @#if extended_path_version
 
@@ -63,7 +94,7 @@ end;
     var EfficiencyInnovation = sigma2;
     end;
 
-    steady;
+    steady(nocheck);
 
     options_.maxit_ = 100;
     options_.ep.verbosity = 0;
@@ -75,14 +106,24 @@ end;
     options_.ep.stochastic.order = 1;
     sts = extended_path([],100);
 
-    figure(1)
-    plot(ts(2,:)-ts(4,:));
+//    options_.ep.stochastic.order = 2;
+//    sts2 = extended_path([],100);
+
+//    options_.ep.stochastic.order = 3;
+//    sts3 = extended_path([],100);
+
+//    figure(1)
+//    plot(ts(2,:)-ts(4,:));
+
+//    figure(2)
+//    plot(sts(2,:)-sts(4,:));
 
-    figure(2)
-    plot(sts(2,:)-sts(4,:));
+//    figure(3)
+//    plot(sts(2,:)-ts(2,:))
 
-    figure(3)
-    plot(sts(2,:)-ts(2,:))
+//    figure(4)
+//    plot([(ts(2,:)-ts(4,:))' (sts(2,:)-sts(4,:))' (sts2(2,:)-sts2(4,:))' (sts3(2,:)-sts3(4,:))']) 
+//    plot([(ts(2,:)-ts(4,:))' (sts(2,:)-sts(4,:))']) 
 
 @#else
 
diff --git a/tests/example1_macroif.mod b/tests/example1_macroif.mod
new file mode 100644
index 0000000000000000000000000000000000000000..02749cc3b283396ab862bc56a7c7d4af1496ee1f
--- /dev/null
+++ b/tests/example1_macroif.mod
@@ -0,0 +1,61 @@
+// Example 1 from Collard's guide to Dynare
+var y, c, k, a, h, b;
+varexo e, u;
+
+@#ifndef NOTDEFINED
+parameters beta, rho, alpha, delta, theta, psi, tau;
+@#else
+@#error "IFNDEF PROBLEM"
+@#endif
+
+@#ifdef NOTDEFINED
+@#error "IFDEF PROBLEM"
+@#else
+alpha = 0.36;
+rho   = 0.95;
+tau   = 0.025;
+beta  = 0.99;
+delta = 0.025;
+psi   = 0;
+theta = 2.95;
+phi   = 0.1;
+@#endif
+
+model;
+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;
+
+@#define DEFINED=0
+
+@#ifndef DEFINED
+@#error "IFNDEF PROBLEM"
+@#else
+shocks;
+var e; stderr 0.009;
+var u; stderr 0.009;
+var e, u = phi*0.009*0.009;
+end;
+@#endif
+
+@#ifdef DEFINED
+stoch_simul;
+@#else
+@#error "IFDEF PROBLEM"
+@#endif
diff --git a/tests/first_order/fs2000_cr.mod b/tests/first_order/fs2000_cr.mod
new file mode 100644
index 0000000000000000000000000000000000000000..a84eddadecea21c523ed81c1fb4df16b830a4712
--- /dev/null
+++ b/tests/first_order/fs2000_cr.mod
@@ -0,0 +1,73 @@
+// See fs2000.mod in the examples/ directory for details on the model
+
+@#define countries = 1:100
+
+var 
+@#for c in countries
+ m_@{c} P_@{c} c_@{c} e_@{c} W_@{c} R_@{c} k_@{c} d_@{c} n_@{c} l_@{c} gy_obs_@{c} gp_obs_@{c} y_@{c} dA_@{c}
+@#endfor
+;
+varexo e_a e_m;
+
+parameters alp bet gam mst rho psi del;
+
+alp = 0.33;
+bet = 0.99;
+gam = 0.003;
+mst = 1.011;
+rho = 0.7;
+psi = 0.787;
+del = 0.02;
+
+model;
+@#for c in countries
+dA_@{c} = exp(gam+e_a);
+log(m_@{c}) = (1-rho)*log(mst) + rho*log(m_@{c}(-1))+e_m;
+-P_@{c}/(c_@{c}(+1)*P_@{c}(+1)*m_@{c})+bet*P_@{c}(+1)*(alp*exp(-alp*(gam+log(e_@{c}(+1))))*k_@{c}^(alp-1)*n_@{c}(+1)^(1-alp)+(1-del)*exp(-(gam+log(e_@{c}(+1)))))/(c_@{c}(+2)*P_@{c}(+2)*m_@{c}(+1))=0;
+W_@{c} = l_@{c}/n_@{c};
+-(psi/(1-psi))*(c_@{c}*P_@{c}/(1-n_@{c}))+l_@{c}/n_@{c} = 0;
+R_@{c} = P_@{c}*(1-alp)*exp(-alp*(gam+e_a))*k_@{c}(-1)^alp*n_@{c}^(-alp)/W_@{c};
+1/(c_@{c}*P_@{c})-bet*P_@{c}*(1-alp)*exp(-alp*(gam+e_a))*k_@{c}(-1)^alp*n_@{c}^(1-alp)/(m_@{c}*l_@{c}*c_@{c}(+1)*P_@{c}(+1)) = 0;
+c_@{c}+k_@{c} = exp(-alp*(gam+e_a))*k_@{c}(-1)^alp*n_@{c}^(1-alp)+(1-del)*exp(-(gam+e_a))*k_@{c}(-1);
+P_@{c}*c_@{c} = m_@{c};
+m_@{c}-1+d_@{c} = l_@{c};
+e_@{c} = exp(e_a);
+y_@{c} = k_@{c}(-1)^alp*n_@{c}^(1-alp)*exp(-alp*(gam+e_a));
+gy_obs_@{c} = dA_@{c}*y_@{c}/y_@{c}(-1);
+gp_obs_@{c} = (P_@{c}/P_@{c}(-1))*m_@{c}(-1)/dA_@{c};
+@#endfor
+end;
+
+initval;
+@#for c in countries
+k_@{c} = 6;
+m_@{c} = mst;
+P_@{c} = 2.25;
+c_@{c} = 0.45;
+e_@{c} = 1;
+W_@{c} = 4;
+R_@{c} = 1.02;
+d_@{c} = 0.85;
+n_@{c} = 0.19;
+l_@{c} = 0.86;
+y_@{c} = 0.6;
+gy_obs_@{c} = exp(gam);
+gp_obs_@{c} = exp(-gam);
+dA_@{c} = exp(gam);
+@#endfor
+end;
+
+shocks;
+var e_a; stderr 0.014;
+var e_m; stderr 0.005;
+end;
+
+steady;
+
+tic;
+check;
+disp(toc);
+
+tic;
+stoch_simul(order=1,dr=cycle_reduction,irf=0,nomoments,noprint);
+disp(toc);
diff --git a/tests/fs2000/fs2000_analytic_derivation.mod b/tests/fs2000/fs2000_analytic_derivation.mod
new file mode 100644
index 0000000000000000000000000000000000000000..a1c589c2a59dd664244ca1927da1a1d86f21079d
--- /dev/null
+++ b/tests/fs2000/fs2000_analytic_derivation.mod
@@ -0,0 +1,75 @@
+// Tests the analytic_derivation option
+
+var m P c e W R k d n l gy_obs gp_obs y dA;
+varexo e_a e_m;
+
+parameters alp bet gam mst rho psi del;
+
+alp = 0.33;
+bet = 0.99;
+gam = 0.003;
+mst = 1.011;
+rho = 0.7;
+psi = 0.787;
+del = 0.02;
+
+model;
+dA = exp(gam+e_a);
+log(m) = (1-rho)*log(mst) + rho*log(m(-1))+e_m;
+-P/(c(+1)*P(+1)*m)+bet*P(+1)*(alp*exp(-alp*(gam+log(e(+1))))*k^(alp-1)*n(+1)^(1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c(+2)*P(+2)*m(+1))=0;
+W = l/n;
+-(psi/(1-psi))*(c*P/(1-n))+l/n = 0;
+R = P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(-alp)/W;
+1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)/(m*l*c(+1)*P(+1)) = 0;
+c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1);
+P*c = m;
+m-1+d = l;
+e = exp(e_a);
+y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a));
+gy_obs = dA*y/y(-1);
+gp_obs = (P/P(-1))*m(-1)/dA;
+end;
+
+initval;
+k = 6;
+m = mst;
+P = 2.25;
+c = 0.45;
+e = 1;
+W = 4;
+R = 1.02;
+d = 0.85;
+n = 0.19;
+l = 0.86;
+y = 0.6;
+gy_obs = exp(gam);
+gp_obs = exp(-gam);
+dA = exp(gam);
+end;
+
+shocks;
+var e_a; stderr 0.014;
+var e_m; stderr 0.005;
+end;
+
+steady;
+
+check;
+
+estimated_params;
+alp, beta_pdf, 0.356, 0.02;
+bet, beta_pdf, 0.993, 0.002;
+gam, normal_pdf, 0.0085, 0.003;
+mst, normal_pdf, 1.0002, 0.007;
+rho, beta_pdf, 0.129, 0.223;
+psi, beta_pdf, 0.65, 0.05;
+del, beta_pdf, 0.01, 0.005;
+stderr e_a, inv_gamma_pdf, 0.035449, inf;
+stderr e_m, inv_gamma_pdf, 0.008862, inf;
+end;
+
+varobs gp_obs gy_obs;
+
+options_.solve_tolf = 1e-12;
+
+estimation(order=1,analytic_derivation,datafile=fsdat_simul,nobs=192,mh_replic=2000,mh_nblocks=2,mh_jscale=0.8);
diff --git a/tests/fs2000/fs2000_missing_data.mod b/tests/fs2000/fs2000_missing_data.mod
new file mode 100644
index 0000000000000000000000000000000000000000..1c02fd45657b8041ca8ec4fb916df1b2c494c293
--- /dev/null
+++ b/tests/fs2000/fs2000_missing_data.mod
@@ -0,0 +1,83 @@
+// Tests kalman filter with missing observations
+
+var m P c e W R k d n l gy_obs gp_obs y dA;
+varexo e_a e_m;
+
+parameters alp bet gam mst rho psi del;
+
+alp = 0.33;
+bet = 0.99;
+gam = 0.003;
+mst = 1.011;
+rho = 0.7;
+psi = 0.787;
+del = 0.02;
+
+model;
+dA = exp(gam+e_a);
+log(m) = (1-rho)*log(mst) + rho*log(m(-1))+e_m;
+-P/(c(+1)*P(+1)*m)+bet*P(+1)*(alp*exp(-alp*(gam+log(e(+1))))*k^(alp-1)*n(+1)^(1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c(+2)*P(+2)*m(+1))=0;
+W = l/n;
+-(psi/(1-psi))*(c*P/(1-n))+l/n = 0;
+R = P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(-alp)/W;
+1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)/(m*l*c(+1)*P(+1)) = 0;
+c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1);
+P*c = m;
+m-1+d = l;
+e = exp(e_a);
+y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a));
+gy_obs = dA*y/y(-1);
+gp_obs = (P/P(-1))*m(-1)/dA;
+end;
+
+initval;
+k = 6;
+m = mst;
+P = 2.25;
+c = 0.45;
+e = 1;
+W = 4;
+R = 1.02;
+d = 0.85;
+n = 0.19;
+l = 0.86;
+y = 0.6;
+gy_obs = exp(gam);
+gp_obs = exp(-gam);
+dA = exp(gam);
+end;
+
+shocks;
+var e_a; stderr 0.014;
+var e_m; stderr 0.005;
+end;
+
+steady;
+
+check;
+
+estimated_params;
+alp, beta_pdf, 0.356, 0.02;
+bet, beta_pdf, 0.993, 0.002;
+gam, normal_pdf, 0.0085, 0.003;
+mst, normal_pdf, 1.0002, 0.007;
+rho, beta_pdf, 0.129, 0.223;
+psi, beta_pdf, 0.65, 0.05;
+del, beta_pdf, 0.01, 0.005;
+stderr e_a, inv_gamma_pdf, 0.035449, inf;
+stderr e_m, inv_gamma_pdf, 0.008862, inf;
+end;
+
+varobs gp_obs gy_obs;
+
+estimation(order=1, datafile=fsdat_simul_missing_obs, nobs=192, loglinear, mh_replic=2000, mh_nblocks=2, mh_jscale=0.8);
+
+
+/*
+ * The following lines were used to generate the data file. If you want to
+ * generate another random data file, comment the "estimation" line and uncomment
+ * the following lines.
+ */
+
+//stoch_simul(periods=200, order=1);
+//datatomfile('fsdat_simul', char('gy_obs', 'gp_obs'));
diff --git a/tests/fs2000/fs2000_particle.mod b/tests/fs2000/fs2000_particle.mod
new file mode 100644
index 0000000000000000000000000000000000000000..ea87fb38dd8dfff56246003b91f824cfd4e19a39
--- /dev/null
+++ b/tests/fs2000/fs2000_particle.mod
@@ -0,0 +1,76 @@
+// See fs2000.mod in the examples/ directory for details on the model
+
+var m P c e W R k d n l gy_obs gp_obs y dA;
+varexo e_a e_m;
+
+parameters alp bet gam mst rho psi del;
+
+alp = 0.33;
+bet = 0.99;
+gam = 0.003;
+mst = 1.011;
+rho = 0.7;
+psi = 0.787;
+del = 0.02;
+
+model;
+dA = exp(gam+e_a);
+log(m) = (1-rho)*log(mst) + rho*log(m(-1))+e_m;
+-P/(c(+1)*P(+1)*m)+bet*P(+1)*(alp*exp(-alp*(gam+log(e(+1))))*k^(alp-1)*n(+1)^(1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c(+2)*P(+2)*m(+1))=0;
+W = l/n;
+-(psi/(1-psi))*(c*P/(1-n))+l/n = 0;
+R = P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(-alp)/W;
+1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)/(m*l*c(+1)*P(+1)) = 0;
+c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1);
+P*c = m;
+m-1+d = l;
+e = exp(e_a);
+y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a));
+gy_obs = dA*y/y(-1);
+gp_obs = (P/P(-1))*m(-1)/dA;
+end;
+
+initval;
+k = 6;
+m = mst;
+P = 2.25;
+c = 0.45;
+e = 1;
+W = 4;
+R = 1.02;
+d = 0.85;
+n = 0.19;
+l = 0.86;
+y = 0.6;
+gy_obs = exp(gam);
+gp_obs = exp(-gam);
+dA = exp(gam);
+end;
+
+shocks;
+var e_a; stderr 0.014;
+var e_m; stderr 0.005;
+end;
+
+steady;
+
+check;
+
+estimated_params;
+alp, beta_pdf, 0.356, 0.02;
+bet, beta_pdf, 0.993, 0.002;
+gam, normal_pdf, 0.0085, 0.003;
+mst, normal_pdf, 1.0002, 0.007;
+rho, beta_pdf, 0.129, 0.223;
+psi, beta_pdf, 0.65, 0.05;
+del, beta_pdf, 0.01, 0.005;
+stderr e_a, inv_gamma_pdf, 0.035449, inf;
+stderr e_m, inv_gamma_pdf, 0.008862, inf;
+end;
+
+varobs gp_obs gy_obs;
+
+options_.solve_tolf = 1e-12;
+
+/* Not computing the mode because it is very expensive, just running a small MH */
+estimation(order=2,mode_compute=0,datafile=fsdat_simul,nobs=192,loglinear,mh_replic=50);
diff --git a/tests/fs2000/fs2000_sd.mod b/tests/fs2000/fs2000_sd.mod
new file mode 100644
index 0000000000000000000000000000000000000000..3f517398dd2616282ecdb8c5e845a7274bab244d
--- /dev/null
+++ b/tests/fs2000/fs2000_sd.mod
@@ -0,0 +1,77 @@
+// See fs2000.mod in the examples/ directory for details on the model
+
+var m P c e W R k d n l gy_obs gp_obs y dA;
+varexo e_a e_m;
+
+parameters alp bet gam mst rho psi del;
+
+alp = 0.33;
+bet = 0.99;
+gam = 0.003;
+mst = 1.011;
+rho = 0.7;
+psi = 0.787;
+del = 0.02;
+
+model;
+dA = exp(gam+e_a);
+log(m) = (1-rho)*log(mst) + rho*log(m(-1))+e_m;
+-P/(c(+1)*P(+1)*m)+bet*P(+1)*(alp*exp(-alp*(gam+log(e(+1))))*k^(alp-1)*n(+1)^(1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c(+2)*P(+2)*m(+1))=0;
+W = l/n;
+-(psi/(1-psi))*(c*P/(1-n))+l/n = 0;
+R = P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(-alp)/W;
+1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)/(m*l*c(+1)*P(+1)) = 0;
+c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1);
+P*c = m;
+m-1+d = l;
+e = exp(e_a);
+y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a));
+gy_obs = dA*y/y(-1);
+gp_obs = (P/P(-1))*m(-1)/dA;
+end;
+
+initval;
+k = 6;
+m = mst;
+P = 2.25;
+c = 0.45;
+e = 1;
+W = 4;
+R = 1.02;
+d = 0.85;
+n = 0.19;
+l = 0.86;
+y = 0.6;
+gy_obs = exp(gam);
+gp_obs = exp(-gam);
+dA = exp(gam);
+end;
+
+shocks;
+var e_a; stderr 0.014;
+var e_m; stderr 0.005;
+end;
+
+steady;
+
+check;
+
+estimated_params;
+alp, beta_pdf, 0.356, 0.02;
+bet, beta_pdf, 0.993, 0.002;
+gam, normal_pdf, 0.0085, 0.003;
+mst, normal_pdf, 1.0002, 0.007;
+rho, beta_pdf, 0.129, 0.223;
+psi, beta_pdf, 0.65, 0.05;
+del, beta_pdf, 0.01, 0.005;
+stderr e_a, inv_gamma_pdf, 0.035449, inf;
+stderr e_m, inv_gamma_pdf, 0.008862, inf;
+end;
+
+varobs gp_obs gy_obs;
+
+options_.solve_tolf = 1e-12;
+
+estimation(order=1,datafile=fsdat_simul,nobs=192,loglinear,mh_replic=0);
+
+shock_decomposition(parameter_set=posterior_mode) gp_obs, gy_obs;
\ No newline at end of file
diff --git a/tests/fs2000/fs2000a_steadystate.m b/tests/fs2000/fs2000a_steadystate.m
index 4833e8b9601223500ccf285e63ebfdd828da6940..0692f23e0433b2837c98f0c6c95c2c4edcafaff3 100644
--- a/tests/fs2000/fs2000a_steadystate.m
+++ b/tests/fs2000/fs2000a_steadystate.m
@@ -1,60 +1,60 @@
-% computes the steady state of fs2000 analyticaly
-% largely inspired by the program of F. Schorfheide
-function [ys,check] = fs2000a_steadystate(ys,exe)
-  global M_
-  
-  alp = M_.params(1); 
-  bet = M_.params(2); 
-  gam = M_.params(3); 
-  mst = M_.params(4); 
-  rho = M_.params(5); 
-  psi = M_.params(6); 
-  del = M_.params(7); 
-
-  check = 0;
-  
-  dA = exp(gam);
-  gst = 1/dA;
-  m = mst;
-  
-  khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1));
-  xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1);
-  nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp );
-  n  = xist/(nust+xist);
-  P  = xist + nust;
-  k  = khst*n;
-
-  l  = psi*mst*n/( (1-psi)*(1-n) );
-  c  = mst/P;
-  d  = l - mst + 1;
-  y  = k^alp*n^(1-alp)*gst^alp;
-  R  = mst/bet;
-  W  = l/n;
-  ist  = y-c;
-  q  = 1 - d;
-
-  e = 1;
-  
-  gp_obs = m/dA;
-  gy_obs = dA;
-  
-  P_obs = 1;
-  Y_obs = 1;
-  
-  ys =[
-m     
-P     
-c     
-e     
-W     
-R     
-k     
-d     
-n     
-l     
-gy_obs
-gp_obs
-Y_obs 
-P_obs 
-y     
+% computes the steady state of fs2000 analyticaly
+% largely inspired by the program of F. Schorfheide
+function [ys,check] = fs2000a_steadystate(ys,exe)
+  global M_
+  
+  alp = M_.params(1); 
+  bet = M_.params(2); 
+  gam = M_.params(3); 
+  mst = M_.params(4); 
+  rho = M_.params(5); 
+  psi = M_.params(6); 
+  del = M_.params(7); 
+
+  check = 0;
+  
+  dA = exp(gam);
+  gst = 1/dA;
+  m = mst;
+  
+  khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1));
+  xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1);
+  nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp );
+  n  = xist/(nust+xist);
+  P  = xist + nust;
+  k  = khst*n;
+
+  l  = psi*mst*n/( (1-psi)*(1-n) );
+  c  = mst/P;
+  d  = l - mst + 1;
+  y  = k^alp*n^(1-alp)*gst^alp;
+  R  = mst/bet;
+  W  = l/n;
+  ist  = y-c;
+  q  = 1 - d;
+
+  e = 1;
+  
+  gp_obs = m/dA;
+  gy_obs = dA;
+  
+  P_obs = 1;
+  Y_obs = 1;
+  
+  ys =[
+m     
+P     
+c     
+e     
+W     
+R     
+k     
+d     
+n     
+l     
+gy_obs
+gp_obs
+Y_obs 
+P_obs 
+y     
 dA          ];
\ No newline at end of file
diff --git a/tests/fs2000/fsdat_simul_missing_obs.m b/tests/fs2000/fsdat_simul_missing_obs.m
new file mode 100644
index 0000000000000000000000000000000000000000..fe9dc57794097461946cbe594ffdb53e3fac91c3
--- /dev/null
+++ b/tests/fs2000/fsdat_simul_missing_obs.m
@@ -0,0 +1,416 @@
+% Generated data, used by fs2000.mod
+
+gy_obs          =[
+      NaN
+      1.0002599
+     0.99104664
+      1.0321162
+      1.0223545
+      1.0043614
+     0.98626929
+      1.0092127
+      1.0357197
+      1.0150827
+      1.0051548
+     0.98465775
+     0.99132132
+     0.99904153
+      1.0044641
+      1.0179198
+      1.0113462
+     0.99409421
+     0.99904293
+      1.0448336
+     0.99932433
+      1.0057004
+     0.99619787
+      1.0267504
+      1.0077645
+      1.0058026
+      1.0025891
+      0.9939097
+     0.99604693
+     0.99908569
+      1.0151094
+     0.99348134
+      1.0039124
+      1.0145805
+     0.99800868
+     0.98578138
+      1.0065771
+     0.99843919
+     0.97979062
+     0.98413351
+     0.96468174
+      1.0273857
+      1.0225211
+     0.99958667
+      1.0111157
+      1.0099585
+     0.99480311
+      1.0079265
+     0.98924573
+      1.0070613
+      1.0075706
+      0.9937151
+      1.0224711
+      1.0018891
+     0.99051863
+      1.0042944
+      1.0184055
+     0.99419508
+     0.99756624
+      1.0015983
+      0.9845772
+      1.0004407
+      1.0116237
+      0.9861885
+      1.0073094
+     0.99273355
+      1.0013224
+     0.99777979
+      1.0301686
+     0.96809556
+     0.99917088
+     0.99949253
+     0.96590004
+      1.0083938
+     0.96662298
+      1.0221454
+      1.0069792
+      1.0343996
+      1.0066531
+      1.0072525
+     0.99743563
+     0.99723703
+       1.000372
+     0.99013917
+      1.0095223
+     0.98864268
+     0.98092242
+     0.98886488
+      1.0030341
+        1.01894
+     0.99155059
+     0.99533235
+     0.99734316
+      1.0047356
+      1.0082737
+     0.98425116
+     0.99949212
+      1.0055899
+      1.0065075
+     0.99385069
+     0.98867975
+     0.99804843
+      1.0184038
+     0.99301902
+      1.0177222
+      1.0051924
+      1.0187852
+      1.0098985
+      1.0097172
+      1.0145811
+     0.98721038
+      1.0361722
+      1.0105821
+     0.99469309
+     0.98626785
+       1.013871
+     0.99858924
+     0.99302637
+      1.0042186
+     0.99623745
+     0.98545708
+      1.0225435
+      1.0011861
+      1.0130321
+     0.97861347
+      1.0228193
+     0.99627435
+      1.0272779
+      1.0075172
+      1.0096762
+      1.0129306
+     0.99966549
+      1.0262882
+      1.0026914
+      1.0061475
+       1.009523
+      1.0036127
+     0.99762992
+     0.99092634
+      1.0058469
+     0.99887292
+      1.0060653
+     0.98673557
+     0.98895709
+     0.99111967
+       0.990118
+     0.99788054
+     0.97054709
+      1.0099157
+      1.0107431
+     0.99518695
+      1.0114048
+     0.99376019
+      1.0023369
+     0.98783327
+      1.0051727
+      1.0100462
+     0.98607387
+      1.0000064
+     0.99692442
+       1.012225
+     0.99574078
+     0.98642833
+     0.99008207
+      1.0197359
+      1.0112849
+     0.98711069
+     0.99402748
+      1.0242141
+      1.0135349
+     0.99842505
+      1.0130714
+     0.99887044
+      1.0059058
+      1.0185998
+      1.0073314
+     0.98687706
+      1.0084551
+     0.97698964
+     0.99482714
+      1.0015302
+      1.0105331
+      1.0261767
+      1.0232822
+      1.0084176
+     0.99785167
+     0.99619733
+      1.0055223
+      1.0076326
+     0.99205461
+      1.0030587
+      1.0137012
+      1.0145878
+      1.0190297
+      1.0000681
+      1.0153894
+      1.0140649
+      1.0007236
+     0.97961463
+      1.0125257
+      1.0169503
+      NaN
+      1.0221185
+
+];
+
+gp_obs          =[
+      1.0079715
+      1.0115853
+      1.0167502
+      1.0068957
+      1.0138189
+      1.0258364
+      1.0243817
+       1.017373
+      1.0020171
+      1.0003742
+      1.0008974
+      1.0104804
+      1.0116393
+      1.0114294
+     0.99932124
+     0.99461459
+      1.0170349
+      1.0051446
+       1.020639
+      1.0051964
+      1.0093042
+       1.007068
+        1.01086
+     NaN
+      1.0014883
+      1.0117332
+      0.9990095
+      1.0108284
+      1.0103672
+      1.0036722
+      1.0005124
+      1.0190331
+      1.0130978
+       1.007842
+      1.0285436
+      1.0322054
+      1.0213403
+      1.0246486
+      1.0419306
+      1.0258867
+      1.0156316
+     0.99818589
+      0.9894107
+      1.0127584
+      1.0146882
+      1.0136529
+      1.0340107
+      1.0343652
+        1.02971
+      1.0077932
+      1.0198114
+       1.013971
+      1.0061083
+      1.0089573
+      1.0037926
+      1.0082071
+     0.99498155
+     0.99735772
+     0.98765026
+       1.006465
+      1.0196088
+      1.0053233
+      1.0119974
+      1.0188066
+      1.0029302
+      1.0183459
+      1.0034218
+      1.0158799
+     0.98824798
+      1.0274357
+      1.0168832
+      1.0180641
+      1.0294657
+     0.98864091
+      1.0358326
+     0.99889969
+      1.0178322
+     0.99813566
+      1.0073549
+      1.0215985
+      1.0084245
+      1.0080939
+      1.0157021
+      1.0075815
+      1.0032633
+      1.0117871
+      1.0209276
+      1.0077569
+     0.99680958
+      1.0120266
+      1.0017625
+      1.0138811
+      1.0198358
+      1.0059629
+      1.0115416
+      1.0319473
+      1.0167074
+      1.0116111
+      1.0048627
+      1.0217622
+      1.0125221
+      1.0142045
+     0.99792469
+     0.99823971
+     0.99561547
+     0.99850373
+      0.9898464
+      1.0030963
+      1.0051373
+      1.0004213
+      1.0144117
+     0.97185592
+      0.9959518
+      1.0073529
+      1.0051603
+     0.98642572
+     0.99433423
+      1.0112131
+      1.0007695
+      1.0176867
+      1.0134363
+     0.99926191
+     0.99879835
+     0.99878754
+      1.0331374
+      1.0077797
+      1.0127221
+      1.0047393
+      1.0074106
+     0.99784213
+      1.0056495
+      1.0057708
+     0.98817494
+     0.98742176
+     0.99930555
+      1.0000687
+      1.0129754
+       1.009529
+      1.0226731
+      1.0149534
+      1.0164295
+      1.0239469
+      1.0293458
+       1.026199
+      1.0197525
+      1.0126818
+      1.0054473
+      1.0254423
+      1.0069461
+      1.0153135
+      1.0337515
+      1.0178187
+      1.0240469
+      1.0079489
+      1.0186953
+      1.0008628
+      1.0113799
+      1.0140118
+      1.0168007
+       1.011441
+     0.98422774
+     0.98909729
+      1.0157859
+      1.0151586
+     0.99756232
+     0.99497777
+      1.0102841
+      1.0221659
+      0.9937759
+     0.99877193
+      1.0079433
+     0.99667692
+      1.0095959
+      1.0128804
+      1.0156949
+      1.0111951
+      1.0228887
+      1.0122083
+      1.0190197
+      1.0074927
+      1.0268096
+     0.99689352
+     0.98948474
+      1.0024938
+      1.0105543
+       1.014116
+      1.0141217
+      1.0056504
+      1.0101026
+      1.0105069
+     0.99619053
+      1.0059439
+     0.99449473
+     0.99482458
+      1.0037702
+      1.0068087
+     0.99575975
+      1.0030815
+      1.0334014
+     0.99879386
+     0.99625634
+      NaN
+     0.99233844
+
+];
+
diff --git a/tests/gsa/ls2003.mod b/tests/gsa/ls2003.mod
index f1a856dfa5f5f61b053ffe47d911c17eb267bd5b..44c55420b438dc04d97982a561b87244491fa609 100644
--- a/tests/gsa/ls2003.mod
+++ b/tests/gsa/ls2003.mod
@@ -67,39 +67,34 @@ disp('NOW I DO STABILITY MAPPING and prepare sample for Reduced form Mapping');
 disp(' ');
 disp('Press ENTER to continue'); pause(5);
 
-dynare_sensitivity(redform=1, //create sample of reduced form coefficients
-alpha2_stab=0.4,
-ksstat=0);
-// NOTE: since namendo is emppty by default, 
+dynare_sensitivity(redform=1,nodisplay, graph_format=fig); //create sample of reduced form coefficients
+// NOTE: since namendo is empty by default, 
 // this call does not perform the mapping of reduced form coefficient: just prepares the sample
 
-/*
 disp(' ');
 disp('ANALYSIS OF REDUCED FORM COEFFICIENTS');
 disp(' ');
 disp('Press ENTER to continue'); pause(5);
 
-dynare_sensitivity(load_stab=1,  // loead previously generated sample analysed for stability
+dynare_sensitivity(nodisplay, graph_format=fig,load_stab=1,  // loead previously generated sample analysed for stability
 redform=1,  // do the reduced form mapping
-logtrans_redform=1,  // estimate log-transformed reduced form coefficients (default=0)
+threshold_redform=[-1 0],  // filter reduced form coefficients (default=[])
 namendo=(pie,R),  // evaluate relationships for pie and R (namendo=(:) for all variables)
 namexo=(e_R),     // evaluate relationships with exogenous e_R (use namexo=(:) for all shocks)
 namlagendo=(R),   // evaluate relationships with lagged R (use namlagendo=(:) for all lagged endogenous)
 stab=0 // don't repeat again the stability mapping
 );
-*/
+
 
 disp(' ');
 disp('THE PREVIOUS TWO CALLS COULD BE DONE TOGETHER');
 disp('BY USING THE COMBINED CALL');
 disp(' ');
-disp('dynare_sensitivity(alpha2_stab=0.4, ksstat=0, redform=1,')
-disp('logtrans_redform=1, namendo=(pie,R), namexo=(e_R), namlagendo=(R));')
+disp('dynare_sensitivity(redform=1,')
+disp('threshold_redform=[-1 0], namendo=(pie,R), namexo=(e_R), namlagendo=(R));')
 disp(' ');
 disp('Press ENTER to continue'); pause(5);
 //dynare_sensitivity(
-//alpha2_stab=0.4,
-//ksstat=0,
 //redform=1, //create sample of reduced form coefficients
 //logtrans_redform=1,  // estimate log-transformed reduced form coefficients (default=0)
 //namendo=(pie,R),  // evaluate relationships for pie and R (namendo=(:) for all variables)
@@ -113,31 +108,24 @@ disp(' ');
 disp('MC FILTERING(rmse=1), TO MAP THE FIT FROM PRIORS');
 disp('Press ENTER to continue'); pause(5);
 
-dynare_sensitivity(datafile=data_ca1,first_obs=8,nobs=79,prefilter=1, // also presample=2,loglinear, are admissible
+dynare_sensitivity(nodisplay, graph_format=fig,datafile=data_ca1,first_obs=8,nobs=79,prefilter=1, // also presample=2,loglinear, are admissible
 load_stab=1,     // load prior sample
 istart_rmse=2,   //start computing rmse from second observation (i.e. rmse does not inlude initial big error)
 stab=0,          // don't  plot again stability analysis results
-rmse=1,          // do rmse analysis
-pfilt_rmse=0.1,  // filtering criterion, i.e. filter the best 10 percent rmse's
-alpha2_rmse=0.3, // critical value for correlations in the rmse filterting analysis: 
-                 // if ==1, means no corrleation analysis done
-alpha_rmse=1     // critical value for smirnov statistics of filtered samples
-                 // if ==1, no smornov analysis is done
+rmse=1          // do rmse analysis
 );
 
 disp(' ');
 disp('THE PREVIOUS THREE CALLS COULD BE DONE TOGETHER');
 disp('BY USING THE COMBINED CALL');
 disp(' ');
-disp('dynare_sensitivity(alpha2_stab=0.4, ksstat=0, redform=1,')
+disp('dynare_sensitivity(redform=1,')
 disp('logtrans_redform=1, namendo=(pie,R), namexo=(e_R), namlagendo=(R),')   
 disp('datafile=data_ca1,first_obs=8,nobs=79,prefilter=1,')
-disp('istart_rmse=2, rmse=1, pfilt_rmse=0.1, alpha2_rmse=0.3, alpha_rmse=1);')
+disp('istart_rmse=2, rmse=1);')
 disp(' ');
 disp('Press ENTER to continue'); pause(5);
 //dynare_sensitivity(
-//alpha2_stab=0.4,
-//ksstat=0,
 //redform=1, //create sample of reduced form coefficients
 //logtrans_redform=1,  // estimate log-transformed reduced form coefficients (default=0)
 //namendo=(pie,R),  // evaluate relationships for pie and R (namendo=(:) for all variables)
@@ -146,11 +134,6 @@ disp('Press ENTER to continue'); pause(5);
 //datafile=data_ca1,first_obs=8,nobs=79,prefilter=1, 
 //istart_rmse=2,   //start computing rmse from second observation (i.e. rmse does not inlude initial big error)
 //rmse=1,          // do rmse analysis
-//pfilt_rmse=0.1,  // filtering criterion, i.e. filter the best 10 percent rmse's
-//alpha2_rmse=0.3, // critical value for correlations in the rmse filterting analysis: 
-//                 // if ==1, means no corrleation analysis done
-//alpha_rmse=1     // critical value for smirnov statistics of filtered samples
-//                 // if ==1, no smirnov sensitivity analysis is done
 //);
 
 
@@ -162,13 +145,13 @@ disp('Press ENTER to continue'); pause(5);
 
 // run this to generate posterior mode and Metropolis files if not yet done
 estimation(datafile=data_ca1,first_obs=8,nobs=79,mh_nblocks=2,
-   prefilter=1,mh_jscale=0.5,mh_replic=5000, mode_compute=4, nograph, mh_drop=0.6,
+   prefilter=1,mh_jscale=0.5,mh_replic=5000, mode_compute=4, mh_drop=0.6, nodisplay, graph_format=fig,
    bayesian_irf, filtered_vars, smoother) y_obs R_obs pie_obs dq de;
 
 
 // run this to produce posterior samples of filtered, smoothed and irf variables, if not yet done
 //estimation(datafile=data_ca1,first_obs=8,nobs=79,mh_nblocks=2,prefilter=1,mh_jscale=0.3,
-//          mh_replic=0, mode_file=ls2003_mode, mode_compute=0, nograph, load_mh_file, bayesian_irf,
+//          mh_replic=0, mode_file=ls2003_mode, mode_compute=0, load_mh_file, bayesian_irf,
 //		  filtered_vars, smoother, mh_drop=0.6);
 
 disp(' ');
@@ -178,10 +161,10 @@ disp('Typical for ML estimation, also feasible for posterior mode');
 disp(' ');
 disp('Press ENTER to continue'); pause(5);
 
-dynare_sensitivity(pprior=0,Nsam=2048,alpha2_stab=0.4,neighborhood_width=0.2,
+dynare_sensitivity(nodisplay, graph_format=fig,pprior=0,Nsam=2048,neighborhood_width=0.2,
 mode_file=ls2003_mode,  // specifies the mode file where the mode and Hessian are stored
 datafile=data_ca1,first_obs=8,nobs=79,prefilter=1,
-rmse=1, alpha2_rmse=1, alpha_rmse=1);
+rmse=1);
 
 disp(' ');
 disp('WE DO STABILITY MAPPING AGAIN, BUT FOR MULTIVARIATE SAMPLE AT THE POSTERIOR MODE (or ML) and Hessian (pprior=0 & ppost=0)');
@@ -189,7 +172,7 @@ disp('Typical for ML estimation, also feasible for posterior mode');
 disp(' ');
 disp('Press ENTER to continue'); pause(5);
 
-dynare_sensitivity(pprior=0,Nsam=2048,alpha2_stab=0.4,
+dynare_sensitivity(nodisplay, graph_format=fig,pprior=0,Nsam=2048,
 mode_file=ls2003_mode  // specifies the mode file where the mode and Hessian are stored
 );
 
@@ -198,13 +181,13 @@ disp(' ');
 disp('RMSE ANALYSIS FOR MULTIVARIATE SAMPLE AT THE POSTERIOR MODE');
 disp(' ');
 disp('Press ENTER to continue'); pause(5);
-dynare_sensitivity(mode_file=ls2003_mode,
+dynare_sensitivity(nodisplay, graph_format=fig,mode_file=ls2003_mode,
 datafile=data_ca1,first_obs=8,nobs=79,prefilter=1,
 pprior=0,
 stab=0,
 rmse=1,
-alpha2_rmse=1, // no correlation analysis
-alpha_rmse=1  // no Smirnov sensitivity analysis
+alpha2_rmse=0, // no correlation analysis
+alpha_rmse=0  // no Smirnov sensitivity analysis
 );
 
 disp(' ');
@@ -213,14 +196,14 @@ disp('BY USING THE COMBINED CALL');
 disp(' ');
 disp('dynare_sensitivity(pprior=0,Nsam=2048,alpha2_stab=0.4,mode_file=ls2003_mode,')
 disp('datafile=data_ca1,first_obs=8,nobs=79,prefilter=1,')
-disp('rmse=1, alpha2_rmse=1, alpha_rmse=1);')
+disp('rmse=1, alpha2_rmse=0, alpha_rmse=0);')
 disp(' ');
 disp('Press ENTER to continue'); pause(5);
 //dynare_sensitivity(pprior=0,Nsam=2048,alpha2_stab=0.4,mode_file=ls2003_mode,
 //datafile=data_ca1,first_obs=8,nobs=79,prefilter=1,
 //rmse=1,
-//alpha2_rmse=1, // no correlation analysis
-//alpha_rmse=1  // no Smirnov sensitivity analysis
+//alpha2_rmse=0, // no correlation analysis
+//alpha_rmse=0  // no Smirnov sensitivity analysis
 //);
 
 disp(' ');
@@ -228,8 +211,8 @@ disp('RMSE ANALYSIS FOR POSTERIOR MCMC sample (ppost=1)');
 disp('Needs a call to dynare_estimation to load all MH environment');
 disp('Press ENTER to continue'); pause(5);
 //estimation(datafile=data_ca1,first_obs=8,nobs=79,mh_nblocks=2, mode_file=ls2003_mode, load_mh_file,
-//  prefilter=1,mh_jscale=0.5,mh_replic=0, mode_compute=0, nograph, mh_drop=0.6);
+//  prefilter=1,mh_jscale=0.5,mh_replic=0, mode_compute=0, mh_drop=0.6);
 
-dynare_sensitivity(stab=0, // no need for stability analysis since the posterior sample is surely OK
-rmse=1,ppost=1,alpha2_rmse=1,alpha_rmse=1);
+dynare_sensitivity(nodisplay, graph_format=fig,stab=0, // no need for stability analysis since the posterior sample is surely OK
+rmse=1,ppost=1);
 
diff --git a/tests/gsa/ls2003ide.mod b/tests/gsa/ls2003ide.mod
index 547f0dcec1cc86f34b6625da4bde4477defb962e..134e2240cfae5b6f2d0f0930ee7a3cffe5475e2b 100644
--- a/tests/gsa/ls2003ide.mod
+++ b/tests/gsa/ls2003ide.mod
@@ -66,23 +66,14 @@ disp('CREATE SCREENING SAMPLE, CHECK FOR STABILITY AND PERFORM A SCREENING FOR I
 disp('TYPE II ERRORS')
 disp(' ')
 disp('PRESS ENTER TO CONTUNUE');
-pause;
+pause(5);
 
 dynare_sensitivity(identification=1, morris_nliv=6, morris_ntra=50);
 
 disp('CREATE MC SAMPLE, CHECK FOR STABILITY AND PERFORM IDENTIFICATION ANALYSIS');
-disp('TYPE I (main effects)')
-disp(' ')
-disp('PRESS ENTER TO CONTUNUE');
-pause;
-dynare_sensitivity(identification=1, morris=0);
-
-disp('USE PREVIOUS MC SAMPLE AND PERFORM IDENTIFICATION ANALYSIS');
 disp('WIth analytic derivatives')
 disp(' ')
 disp('PRESS ENTER TO CONTUNUE');
-pause;
-dynare_sensitivity(identification=1, load_stab=1, stab=0, morris=2);
-
+pause(5);
+dynare_sensitivity(identification=1, morris=2);
 
-stoch_simul(order=1,irf=40);
diff --git a/tests/k_order_perturbation/fs2000k3_p.mod b/tests/k_order_perturbation/fs2000k3_p.mod
new file mode 100644
index 0000000000000000000000000000000000000000..2d0c6bff12d3a967888e5003a26bb600c69533e8
--- /dev/null
+++ b/tests/k_order_perturbation/fs2000k3_p.mod
@@ -0,0 +1,58 @@
+// checks whether second order coefficients are the same with order=2 and order=3 with k_order_solver=1
+
+var m P c e W R k d n l gy_obs gp_obs y dA ;
+varexo e_a e_m;
+
+parameters alp bet gam mst rho psi del;
+
+alp = 0.33;
+bet = 0.99;
+gam = 0.003;
+mst = 1.011;
+rho = 0.7;
+psi = 0.787;
+del = 0.02;
+
+model;
+dA = exp(gam+e_a);
+log(m) = (1-rho)*log(mst) + rho*log(m(-1))+e_m;
+-P/(c(+1)*P(+1)*m)+bet*P(+1)*(alp*exp(-alp*(gam+log(e(+1))))*k^(alp-1)*n(+1)^(1-alp)+(1-del)*exp(-(gam+log(e(+1)))))/(c(+2)*P(+2)*m(+1))=0;
+W = l/n;
+-(psi/(1-psi))*(c*P/(1-n))+l/n = 0;
+R = P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(-alp)/W;
+1/(c*P)-bet*P*(1-alp)*exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)/(m*l*c(+1)*P(+1)) = 0;
+c+k = exp(-alp*(gam+e_a))*k(-1)^alp*n^(1-alp)+(1-del)*exp(-(gam+e_a))*k(-1);
+P*c = m;
+m-1+d = l;
+e = exp(e_a);
+y = k(-1)^alp*n^(1-alp)*exp(-alp*(gam+e_a));
+gy_obs = dA*y/y(-1);
+gp_obs = (P/P(-1))*m(-1)/dA;
+end;
+
+initval;
+m = mst;
+P = 2.25;
+c = 0.45;
+e = 1;
+W = 4;
+R = 1.02;
+k = 6;
+d = 0.85;
+n = 0.19;
+l = 0.86;
+y = 0.6;
+gy_obs = exp(gam);
+gp_obs = exp(-gam); 
+dA = exp(gam);
+end;
+
+shocks;
+var e_a; stderr 0.014;
+var e_m; stderr 0.005;
+end;
+
+steady;
+
+stoch_simul(order=3,periods=1000,drop=0,pruning);
+
diff --git a/tests/kalman_filter_smoother/fs2000a_steadystate.m b/tests/kalman_filter_smoother/fs2000a_steadystate.m
index 4833e8b9601223500ccf285e63ebfdd828da6940..0692f23e0433b2837c98f0c6c95c2c4edcafaff3 100644
--- a/tests/kalman_filter_smoother/fs2000a_steadystate.m
+++ b/tests/kalman_filter_smoother/fs2000a_steadystate.m
@@ -1,60 +1,60 @@
-% computes the steady state of fs2000 analyticaly
-% largely inspired by the program of F. Schorfheide
-function [ys,check] = fs2000a_steadystate(ys,exe)
-  global M_
-  
-  alp = M_.params(1); 
-  bet = M_.params(2); 
-  gam = M_.params(3); 
-  mst = M_.params(4); 
-  rho = M_.params(5); 
-  psi = M_.params(6); 
-  del = M_.params(7); 
-
-  check = 0;
-  
-  dA = exp(gam);
-  gst = 1/dA;
-  m = mst;
-  
-  khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1));
-  xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1);
-  nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp );
-  n  = xist/(nust+xist);
-  P  = xist + nust;
-  k  = khst*n;
-
-  l  = psi*mst*n/( (1-psi)*(1-n) );
-  c  = mst/P;
-  d  = l - mst + 1;
-  y  = k^alp*n^(1-alp)*gst^alp;
-  R  = mst/bet;
-  W  = l/n;
-  ist  = y-c;
-  q  = 1 - d;
-
-  e = 1;
-  
-  gp_obs = m/dA;
-  gy_obs = dA;
-  
-  P_obs = 1;
-  Y_obs = 1;
-  
-  ys =[
-m     
-P     
-c     
-e     
-W     
-R     
-k     
-d     
-n     
-l     
-gy_obs
-gp_obs
-Y_obs 
-P_obs 
-y     
+% computes the steady state of fs2000 analyticaly
+% largely inspired by the program of F. Schorfheide
+function [ys,check] = fs2000a_steadystate(ys,exe)
+  global M_
+  
+  alp = M_.params(1); 
+  bet = M_.params(2); 
+  gam = M_.params(3); 
+  mst = M_.params(4); 
+  rho = M_.params(5); 
+  psi = M_.params(6); 
+  del = M_.params(7); 
+
+  check = 0;
+  
+  dA = exp(gam);
+  gst = 1/dA;
+  m = mst;
+  
+  khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1));
+  xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1);
+  nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp );
+  n  = xist/(nust+xist);
+  P  = xist + nust;
+  k  = khst*n;
+
+  l  = psi*mst*n/( (1-psi)*(1-n) );
+  c  = mst/P;
+  d  = l - mst + 1;
+  y  = k^alp*n^(1-alp)*gst^alp;
+  R  = mst/bet;
+  W  = l/n;
+  ist  = y-c;
+  q  = 1 - d;
+
+  e = 1;
+  
+  gp_obs = m/dA;
+  gy_obs = dA;
+  
+  P_obs = 1;
+  Y_obs = 1;
+  
+  ys =[
+m     
+P     
+c     
+e     
+W     
+R     
+k     
+d     
+n     
+l     
+gy_obs
+gp_obs
+Y_obs 
+P_obs 
+y     
 dA          ];
\ No newline at end of file
diff --git a/tests/kalman_filter_smoother/testsmoother.m b/tests/kalman_filter_smoother/testsmoother.m
index 71ca84a33d9b7fadac1a5cfd0dd10f1c8ce6bf64..2e633bc2345c0a612ede5569c1b0a148ac80c9d9 100644
--- a/tests/kalman_filter_smoother/testsmoother.m
+++ b/tests/kalman_filter_smoother/testsmoother.m
@@ -1,56 +1,56 @@
-load test
-% $$$ Y = Y(1:2,:);
-% $$$ mf = mf(1:2);
-% $$$ H=H(1:2,1:2);
-% $$$ pp = pp-1;
-% $$$ trend =trend(1:2,:);
-Pinf1(1,1) = 1;
-Pstar1(1,1) = 0;
-Pstar1(4,1) = 0;
-Pstar1(1,4) = 0;
-[alphahat1,epsilonhat1,etahat1,a11, aK1] = DiffuseKalmanSmootherH1(T,R,Q,H, ...
-						  Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf);
-[alphahat2,epsilonhat2,etahat2,a12, aK2] = DiffuseKalmanSmootherH3(T,R,Q,H, ...
-						  Pinf1,Pstar1,Y,trend, ...
-						  pp,mm,smpl,mf);
-max(max(abs(alphahat1-alphahat2)))
-max(max(abs(epsilonhat1-epsilonhat2)))
-max(max(abs(etahat1-etahat2)))
-max(max(abs(a11-a12)))
-max(max(abs(aK1-aK2)))
-
-return
-[alphahat1,etahat1,a11, aK1] = DiffuseKalmanSmoother1(T,R,Q, ...
-						  Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf);
-[alphahat2,etahat2,a12, aK2] = DiffuseKalmanSmoother3(T,R,Q, ...
-						  Pinf1,Pstar1,Y,trend, ...
-						  pp,mm,smpl,mf);
-
-
-max(max(abs(alphahat1-alphahat2)))
-max(max(abs(etahat1-etahat2)))
-max(max(abs(a11-a12)))
-%max(max(abs(aK1-aK2)))
-
-
-H = zeros(size(H));
-[alphahat1,etahat1,a11, aK1] = DiffuseKalmanSmoother1(T,R,Q, ...
-						  Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf);
-[alphahat2,epsilonhat2,etahat2,a12, aK2] = DiffuseKalmanSmootherH1(T,R,Q,H, ...
-						  Pinf1,Pstar1,Y,trend, ...
-						  pp,mm,smpl,mf);
-max(max(abs(alphahat1-alphahat2)))
-max(max(abs(etahat1-etahat2)))
-max(max(abs(a11-a12)))
-%max(max(abs(aK1-aK2)))
-
-
-[alphahat1,etahat1,a11, aK1] = DiffuseKalmanSmoother3(T,R,Q, ...
-						  Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf);
-[alphahat2,epsilonhat2,etahat2,a12, aK2] = DiffuseKalmanSmootherH3(T,R,Q, H, ...
-						  Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf);
-
-max(max(abs(alphahat1-alphahat2)))
-max(max(abs(etahat1-etahat2)))
-max(max(abs(a11-a12)))
-%max(max(abs(aK1-aK2)))
+load test
+% $$$ Y = Y(1:2,:);
+% $$$ mf = mf(1:2);
+% $$$ H=H(1:2,1:2);
+% $$$ pp = pp-1;
+% $$$ trend =trend(1:2,:);
+Pinf1(1,1) = 1;
+Pstar1(1,1) = 0;
+Pstar1(4,1) = 0;
+Pstar1(1,4) = 0;
+[alphahat1,epsilonhat1,etahat1,a11, aK1] = DiffuseKalmanSmootherH1(T,R,Q,H, ...
+						  Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf);
+[alphahat2,epsilonhat2,etahat2,a12, aK2] = DiffuseKalmanSmootherH3(T,R,Q,H, ...
+						  Pinf1,Pstar1,Y,trend, ...
+						  pp,mm,smpl,mf);
+max(max(abs(alphahat1-alphahat2)))
+max(max(abs(epsilonhat1-epsilonhat2)))
+max(max(abs(etahat1-etahat2)))
+max(max(abs(a11-a12)))
+max(max(abs(aK1-aK2)))
+
+return
+[alphahat1,etahat1,a11, aK1] = DiffuseKalmanSmoother1(T,R,Q, ...
+						  Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf);
+[alphahat2,etahat2,a12, aK2] = DiffuseKalmanSmoother3(T,R,Q, ...
+						  Pinf1,Pstar1,Y,trend, ...
+						  pp,mm,smpl,mf);
+
+
+max(max(abs(alphahat1-alphahat2)))
+max(max(abs(etahat1-etahat2)))
+max(max(abs(a11-a12)))
+%max(max(abs(aK1-aK2)))
+
+
+H = zeros(size(H));
+[alphahat1,etahat1,a11, aK1] = DiffuseKalmanSmoother1(T,R,Q, ...
+						  Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf);
+[alphahat2,epsilonhat2,etahat2,a12, aK2] = DiffuseKalmanSmootherH1(T,R,Q,H, ...
+						  Pinf1,Pstar1,Y,trend, ...
+						  pp,mm,smpl,mf);
+max(max(abs(alphahat1-alphahat2)))
+max(max(abs(etahat1-etahat2)))
+max(max(abs(a11-a12)))
+%max(max(abs(aK1-aK2)))
+
+
+[alphahat1,etahat1,a11, aK1] = DiffuseKalmanSmoother3(T,R,Q, ...
+						  Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf);
+[alphahat2,epsilonhat2,etahat2,a12, aK2] = DiffuseKalmanSmootherH3(T,R,Q, H, ...
+						  Pinf1,Pstar1,Y,trend,pp,mm,smpl,mf);
+
+max(max(abs(alphahat1-alphahat2)))
+max(max(abs(etahat1-etahat2)))
+max(max(abs(a11-a12)))
+%max(max(abs(aK1-aK2)))
diff --git a/tests/ls2003/data_ca1.m b/tests/ls2003/data_ca1.m
index b0b4f054613b41ebd91b9492f4edca5d38f6cb26..c28fae1a2800e83eda0e6343196e8aeafad2935f 100644
--- a/tests/ls2003/data_ca1.m
+++ b/tests/ls2003/data_ca1.m
@@ -1,100 +1,100 @@
-data = [0.928467646476  11.8716889412   20  0.418037507392  0.227382377518 ...
--0.705994063083 11.7522582094   21.25   1.09254424511   -1.29488274994 ...
--0.511895351926 9.68144025625   17.25   -1.66150408407  0.331508393098 ...
--0.990955971267 10.0890781236   17  1.43016275252   -2.43589670141 ...
--0.981233061806 12.1094840679   18.25   2.91293288733   -0.790246576864 ...
--0.882182844512 8.54559460406   15  0.419579139481  0.358729719566 ...
--0.930893002836 6.19238374422   12.5    -1.48847457959  0.739779938797 ...
-1.53158206947   2.76544271886   11.5    -0.336216769682 0.455559918769 ...
-2.2659052834    5.47418162513   11  0.306436789767  -0.0707985731221 ...
-1.05419803797   6.35698426189   11  0.140700250477  0.620401487202 ...
-1.20161076793   3.4253301593    11  0.461296492351  0.14354323987 ...
-1.73934077971   4.70926070322   11.5    1.35798282982   0.38564694435 ...
-1.71735262584   3.54232079749   12.5    2.9097529155    -0.804308583301 ...
-0.426343657844  3.32719108897   13  1.64214862652   -1.18214664701 ...
-1.67751812324   2.93444727338   11.25   0.344434910651  -1.6529373719 ...
-1.37013301099   4.72303361923   11.75   2.61511526582   0.327684243041 ...
-0.281231073781  4.4893853071    10.5    1.17043449257   1.12855106649 ...
-1.53638992834   3.7325309699    10.25   -0.683947046728 0.11943538737 ...
-1.68081431462   3.34729969129   10  1.41159342106   -1.59065680853 ...
--0.343321601133 5.05563513564   12  1.75117366498   -2.40127764642 ...
-0.873415608666  3.2779996255    10.25   -1.39895866711  0.0971444398216 ...
-0.26399696544   4.78229419828   9.75    0.0914692438124 0.299310457612 ...
--0.562233624818 3.88598638237   9.75    -0.0505384765105    0.332826708151 ...
-2.15161914936   3.84859710132   8.75    -3.44811080489  0.789138678784 ...
-1.2345093726    5.62225030942   9.5 -0.366945407434 2.32974981198 ...
-1.62554967459   4.24667132831   10  -0.800958371402 0.0293183770935 ...
-1.33035402527   2.75248979249   9.75    -0.855723113225 0.852493939813 ...
-1.52078814077   3.53415985826   9.75    -3.37963469203  -1.05133958119 ...
-1.16704983697   4.92754079464   10.75   -3.0142303324   0.459907431978 ...
-0.277213572101  4.55532133037   11.75   -0.851995599415 2.03242034852 ...
-0.842215068977  3.11164509647   12.25   -1.08290421696  0.014323281961 ...
-1.05325028606   4.92882647578   13.5    -1.1953883867   0.706764750654 ...
-0.453051253568  6.82998950103   13.5    0.111803656462  0.088462593153 ...
-0.199885995525  5.82643354662   13.5    -0.920501518421 -0.26504958666 ...
-0.137907999624  2.66076369132   13.5    -1.17122929812  -0.995642430514 ...
-0.721949686709  5.70497876823   14.25   1.19378169018   -1.10644839651 ...
--0.418465249225 3.75861110232   14.75   -1.03131674824  0.188507675831 ...
--0.644028342116 4.15104788154   13.75   -1.48911756546  0.204560913792 ...
--0.848213852668 5.65580324027   12.75   0.677011703877  -0.849628054542 ...
--1.51954076928  11.4866911266   11.25   -0.446024680774 -0.456342350765 ...
-0.265275055215  2.85472749592   9.75    -0.598778202436 -0.907311640831 ...
-0.356162529063  2.29614015658   9.5 -0.46820788432  -1.22130883441 ...
-0.368308864363  -0.539083504685 8   -0.781333991956 0.374007246518 ...
--0.145751412732 1.61507621789   8.25    3.68291932628   1.32438399845 ...
-0.285457283664  2.14334055993   7   1.42819405379   -0.00818660844123 ...
-0.372390129412  1.60000213334   6.25    0.626106424052  -0.10136772765 ...
-0.382720203063  1.72614243263   7.25    4.89631941021   -1.10060711916 ...
-0.737957515573  2.90430582851   6   -0.0422721010314    0.4178952497 ...
-0.649532581668  0.657135682543  6   0.692066153971  0.422299120276 ...
-0.627159201987  1.70352689913   5.75    2.62066711305   -1.29237304034 ...
-0.905441299817  1.95663197267   5.5 1.5949697565    -0.27115830703 ...
-1.49322577898   -2.08741765309  6.25    1.23027694802   0.418336889527 ...
-1.48750731567   -1.57274121871  8   3.01660550994   -0.893958254365 ...
-1.39783858087   2.22623066426   7   -0.80842319214  1.47625453886 ...
-0.89274836317   1.30378081742   8   -0.249485058661 0.159871204185 ...
-0.920652246088  4.1437741965    9.75    2.8204453623    0.178149239655 ...
--0.00264276644799   3.07989972052   8.75    -2.56342461535  2.105998353 ...
-0.0198190461681 0.766283759256  8   -1.15838865989  1.56888883418 ...
-0.440050515311  0.127570085801  7.5 0.0400753569995 0.028914333532 ...
-0.129536637901  1.78174141526   6.75    0.959943962785  0.307781224401 ...
-0.398549827172  3.03606770667   6.5 -0.340209794742 0.100979469478 ...
-1.17174775425   0.629625188037  5.75    0.403003686814  0.902394579377 ...
-0.991163981251  2.50862910684   4.75    -1.44963996982  1.16150986945 ...
-0.967603566096  2.12003739013   4.75    0.610846030775  -0.889994896068 ...
-1.14689383604   1.24185011459   4.75    2.01098091308   -1.73846431001 ...
-1.32593824054   0.990713820685  4.75    -0.0955142989332    -0.0369257308362 ...
-0.861135002644  -0.24744943605  6   1.72793107135   -0.691506789639 ...
-1.26870850151   2.09844764887   6.5 1.50720217572   -1.31399187077 ...
-0.260364987715  1.10650139716   6.5 1.13659047496   0.0720441664643 ...
-1.09731242214   0.490796381346  7.25    4.59123894147   -2.14073070763 ...
-1.63792841781   0.612652594286  6.75    1.79604605035   -0.644363995357 ...
-1.48465576034   0.978295808687  6.75    -2.00753620902  1.39437534964 ...
-1.0987608663    4.25212569087   6.25    -2.58901196498  2.56054320803 ...
-1.42592178132   2.76984518311   6.25    0.888195752358  1.03114549274 ...
-1.52958239462   1.31795955491   6.5 -0.902907564082 -0.0952198893776 ...
-1.0170168994    2.14733589918   7   -1.3054866978   2.68803738466 ...
-0.723253652257  3.43552889347   7.5 1.8213700853    0.592593586195 ...
-1.24720806008   3.87383806577   7.5 0.0522300654168 0.988871238698 ...
-0.482531471239  2.67793287032   7.5 2.9693944293    -0.108591166081 ...
-0.154056100439  0.927269031704  6.75    0.119222057561  3.30489209451 ...
-0.0694865769274 6.65916526788   6.25    0.889014476084  -2.83976849035 ...
--0.121267434867 0.341442615696  5.25    0.323053239216  -3.49289229012 ...
-0.726473690375  -3.5423730964   4   2.19149290449   -3.20855054004 ...
-1.39271709108   2.63121085718   3.75    0.88406577736   0.75622580197 ...
-1.07502077727   5.88578836799   4.25    -2.55088273352  2.89018116374 ...
-0.759049251607  4.24703604223   4.5 0.575687665685  -0.388292506167 ...
-]; 
- 
-data = reshape(data,5,86)'; 
-y_obs = data(:,1); 
-pie_obs = data(:,2); 
-R_obs = data(:,3); 
-de = data(:,4); 
-dq = data(:,5); 
- 
-%Country: Canada 
-%Sample Range: 1981:2 to 2002:3 
-%Observations: 86 
-%Variables: Real GDP Growth [%], Inflation [annualized %], Nom Rate [%], 
-%           Exchange Rate Change [%], Terms of Trade Change [%] 
+data = [0.928467646476  11.8716889412   20  0.418037507392  0.227382377518 ...
+-0.705994063083 11.7522582094   21.25   1.09254424511   -1.29488274994 ...
+-0.511895351926 9.68144025625   17.25   -1.66150408407  0.331508393098 ...
+-0.990955971267 10.0890781236   17  1.43016275252   -2.43589670141 ...
+-0.981233061806 12.1094840679   18.25   2.91293288733   -0.790246576864 ...
+-0.882182844512 8.54559460406   15  0.419579139481  0.358729719566 ...
+-0.930893002836 6.19238374422   12.5    -1.48847457959  0.739779938797 ...
+1.53158206947   2.76544271886   11.5    -0.336216769682 0.455559918769 ...
+2.2659052834    5.47418162513   11  0.306436789767  -0.0707985731221 ...
+1.05419803797   6.35698426189   11  0.140700250477  0.620401487202 ...
+1.20161076793   3.4253301593    11  0.461296492351  0.14354323987 ...
+1.73934077971   4.70926070322   11.5    1.35798282982   0.38564694435 ...
+1.71735262584   3.54232079749   12.5    2.9097529155    -0.804308583301 ...
+0.426343657844  3.32719108897   13  1.64214862652   -1.18214664701 ...
+1.67751812324   2.93444727338   11.25   0.344434910651  -1.6529373719 ...
+1.37013301099   4.72303361923   11.75   2.61511526582   0.327684243041 ...
+0.281231073781  4.4893853071    10.5    1.17043449257   1.12855106649 ...
+1.53638992834   3.7325309699    10.25   -0.683947046728 0.11943538737 ...
+1.68081431462   3.34729969129   10  1.41159342106   -1.59065680853 ...
+-0.343321601133 5.05563513564   12  1.75117366498   -2.40127764642 ...
+0.873415608666  3.2779996255    10.25   -1.39895866711  0.0971444398216 ...
+0.26399696544   4.78229419828   9.75    0.0914692438124 0.299310457612 ...
+-0.562233624818 3.88598638237   9.75    -0.0505384765105    0.332826708151 ...
+2.15161914936   3.84859710132   8.75    -3.44811080489  0.789138678784 ...
+1.2345093726    5.62225030942   9.5 -0.366945407434 2.32974981198 ...
+1.62554967459   4.24667132831   10  -0.800958371402 0.0293183770935 ...
+1.33035402527   2.75248979249   9.75    -0.855723113225 0.852493939813 ...
+1.52078814077   3.53415985826   9.75    -3.37963469203  -1.05133958119 ...
+1.16704983697   4.92754079464   10.75   -3.0142303324   0.459907431978 ...
+0.277213572101  4.55532133037   11.75   -0.851995599415 2.03242034852 ...
+0.842215068977  3.11164509647   12.25   -1.08290421696  0.014323281961 ...
+1.05325028606   4.92882647578   13.5    -1.1953883867   0.706764750654 ...
+0.453051253568  6.82998950103   13.5    0.111803656462  0.088462593153 ...
+0.199885995525  5.82643354662   13.5    -0.920501518421 -0.26504958666 ...
+0.137907999624  2.66076369132   13.5    -1.17122929812  -0.995642430514 ...
+0.721949686709  5.70497876823   14.25   1.19378169018   -1.10644839651 ...
+-0.418465249225 3.75861110232   14.75   -1.03131674824  0.188507675831 ...
+-0.644028342116 4.15104788154   13.75   -1.48911756546  0.204560913792 ...
+-0.848213852668 5.65580324027   12.75   0.677011703877  -0.849628054542 ...
+-1.51954076928  11.4866911266   11.25   -0.446024680774 -0.456342350765 ...
+0.265275055215  2.85472749592   9.75    -0.598778202436 -0.907311640831 ...
+0.356162529063  2.29614015658   9.5 -0.46820788432  -1.22130883441 ...
+0.368308864363  -0.539083504685 8   -0.781333991956 0.374007246518 ...
+-0.145751412732 1.61507621789   8.25    3.68291932628   1.32438399845 ...
+0.285457283664  2.14334055993   7   1.42819405379   -0.00818660844123 ...
+0.372390129412  1.60000213334   6.25    0.626106424052  -0.10136772765 ...
+0.382720203063  1.72614243263   7.25    4.89631941021   -1.10060711916 ...
+0.737957515573  2.90430582851   6   -0.0422721010314    0.4178952497 ...
+0.649532581668  0.657135682543  6   0.692066153971  0.422299120276 ...
+0.627159201987  1.70352689913   5.75    2.62066711305   -1.29237304034 ...
+0.905441299817  1.95663197267   5.5 1.5949697565    -0.27115830703 ...
+1.49322577898   -2.08741765309  6.25    1.23027694802   0.418336889527 ...
+1.48750731567   -1.57274121871  8   3.01660550994   -0.893958254365 ...
+1.39783858087   2.22623066426   7   -0.80842319214  1.47625453886 ...
+0.89274836317   1.30378081742   8   -0.249485058661 0.159871204185 ...
+0.920652246088  4.1437741965    9.75    2.8204453623    0.178149239655 ...
+-0.00264276644799   3.07989972052   8.75    -2.56342461535  2.105998353 ...
+0.0198190461681 0.766283759256  8   -1.15838865989  1.56888883418 ...
+0.440050515311  0.127570085801  7.5 0.0400753569995 0.028914333532 ...
+0.129536637901  1.78174141526   6.75    0.959943962785  0.307781224401 ...
+0.398549827172  3.03606770667   6.5 -0.340209794742 0.100979469478 ...
+1.17174775425   0.629625188037  5.75    0.403003686814  0.902394579377 ...
+0.991163981251  2.50862910684   4.75    -1.44963996982  1.16150986945 ...
+0.967603566096  2.12003739013   4.75    0.610846030775  -0.889994896068 ...
+1.14689383604   1.24185011459   4.75    2.01098091308   -1.73846431001 ...
+1.32593824054   0.990713820685  4.75    -0.0955142989332    -0.0369257308362 ...
+0.861135002644  -0.24744943605  6   1.72793107135   -0.691506789639 ...
+1.26870850151   2.09844764887   6.5 1.50720217572   -1.31399187077 ...
+0.260364987715  1.10650139716   6.5 1.13659047496   0.0720441664643 ...
+1.09731242214   0.490796381346  7.25    4.59123894147   -2.14073070763 ...
+1.63792841781   0.612652594286  6.75    1.79604605035   -0.644363995357 ...
+1.48465576034   0.978295808687  6.75    -2.00753620902  1.39437534964 ...
+1.0987608663    4.25212569087   6.25    -2.58901196498  2.56054320803 ...
+1.42592178132   2.76984518311   6.25    0.888195752358  1.03114549274 ...
+1.52958239462   1.31795955491   6.5 -0.902907564082 -0.0952198893776 ...
+1.0170168994    2.14733589918   7   -1.3054866978   2.68803738466 ...
+0.723253652257  3.43552889347   7.5 1.8213700853    0.592593586195 ...
+1.24720806008   3.87383806577   7.5 0.0522300654168 0.988871238698 ...
+0.482531471239  2.67793287032   7.5 2.9693944293    -0.108591166081 ...
+0.154056100439  0.927269031704  6.75    0.119222057561  3.30489209451 ...
+0.0694865769274 6.65916526788   6.25    0.889014476084  -2.83976849035 ...
+-0.121267434867 0.341442615696  5.25    0.323053239216  -3.49289229012 ...
+0.726473690375  -3.5423730964   4   2.19149290449   -3.20855054004 ...
+1.39271709108   2.63121085718   3.75    0.88406577736   0.75622580197 ...
+1.07502077727   5.88578836799   4.25    -2.55088273352  2.89018116374 ...
+0.759049251607  4.24703604223   4.5 0.575687665685  -0.388292506167 ...
+]; 
+ 
+data = reshape(data,5,86)'; 
+y_obs = data(:,1); 
+pie_obs = data(:,2); 
+R_obs = data(:,3); 
+de = data(:,4); 
+dq = data(:,5); 
+ 
+%Country: Canada 
+%Sample Range: 1981:2 to 2002:3 
+%Observations: 86 
+%Variables: Real GDP Growth [%], Inflation [annualized %], Nom Rate [%], 
+%           Exchange Rate Change [%], Terms of Trade Change [%] 
diff --git a/tests/measurement_errors/data_ca1.m b/tests/measurement_errors/data_ca1.m
index b0b4f054613b41ebd91b9492f4edca5d38f6cb26..c28fae1a2800e83eda0e6343196e8aeafad2935f 100644
--- a/tests/measurement_errors/data_ca1.m
+++ b/tests/measurement_errors/data_ca1.m
@@ -1,100 +1,100 @@
-data = [0.928467646476  11.8716889412   20  0.418037507392  0.227382377518 ...
--0.705994063083 11.7522582094   21.25   1.09254424511   -1.29488274994 ...
--0.511895351926 9.68144025625   17.25   -1.66150408407  0.331508393098 ...
--0.990955971267 10.0890781236   17  1.43016275252   -2.43589670141 ...
--0.981233061806 12.1094840679   18.25   2.91293288733   -0.790246576864 ...
--0.882182844512 8.54559460406   15  0.419579139481  0.358729719566 ...
--0.930893002836 6.19238374422   12.5    -1.48847457959  0.739779938797 ...
-1.53158206947   2.76544271886   11.5    -0.336216769682 0.455559918769 ...
-2.2659052834    5.47418162513   11  0.306436789767  -0.0707985731221 ...
-1.05419803797   6.35698426189   11  0.140700250477  0.620401487202 ...
-1.20161076793   3.4253301593    11  0.461296492351  0.14354323987 ...
-1.73934077971   4.70926070322   11.5    1.35798282982   0.38564694435 ...
-1.71735262584   3.54232079749   12.5    2.9097529155    -0.804308583301 ...
-0.426343657844  3.32719108897   13  1.64214862652   -1.18214664701 ...
-1.67751812324   2.93444727338   11.25   0.344434910651  -1.6529373719 ...
-1.37013301099   4.72303361923   11.75   2.61511526582   0.327684243041 ...
-0.281231073781  4.4893853071    10.5    1.17043449257   1.12855106649 ...
-1.53638992834   3.7325309699    10.25   -0.683947046728 0.11943538737 ...
-1.68081431462   3.34729969129   10  1.41159342106   -1.59065680853 ...
--0.343321601133 5.05563513564   12  1.75117366498   -2.40127764642 ...
-0.873415608666  3.2779996255    10.25   -1.39895866711  0.0971444398216 ...
-0.26399696544   4.78229419828   9.75    0.0914692438124 0.299310457612 ...
--0.562233624818 3.88598638237   9.75    -0.0505384765105    0.332826708151 ...
-2.15161914936   3.84859710132   8.75    -3.44811080489  0.789138678784 ...
-1.2345093726    5.62225030942   9.5 -0.366945407434 2.32974981198 ...
-1.62554967459   4.24667132831   10  -0.800958371402 0.0293183770935 ...
-1.33035402527   2.75248979249   9.75    -0.855723113225 0.852493939813 ...
-1.52078814077   3.53415985826   9.75    -3.37963469203  -1.05133958119 ...
-1.16704983697   4.92754079464   10.75   -3.0142303324   0.459907431978 ...
-0.277213572101  4.55532133037   11.75   -0.851995599415 2.03242034852 ...
-0.842215068977  3.11164509647   12.25   -1.08290421696  0.014323281961 ...
-1.05325028606   4.92882647578   13.5    -1.1953883867   0.706764750654 ...
-0.453051253568  6.82998950103   13.5    0.111803656462  0.088462593153 ...
-0.199885995525  5.82643354662   13.5    -0.920501518421 -0.26504958666 ...
-0.137907999624  2.66076369132   13.5    -1.17122929812  -0.995642430514 ...
-0.721949686709  5.70497876823   14.25   1.19378169018   -1.10644839651 ...
--0.418465249225 3.75861110232   14.75   -1.03131674824  0.188507675831 ...
--0.644028342116 4.15104788154   13.75   -1.48911756546  0.204560913792 ...
--0.848213852668 5.65580324027   12.75   0.677011703877  -0.849628054542 ...
--1.51954076928  11.4866911266   11.25   -0.446024680774 -0.456342350765 ...
-0.265275055215  2.85472749592   9.75    -0.598778202436 -0.907311640831 ...
-0.356162529063  2.29614015658   9.5 -0.46820788432  -1.22130883441 ...
-0.368308864363  -0.539083504685 8   -0.781333991956 0.374007246518 ...
--0.145751412732 1.61507621789   8.25    3.68291932628   1.32438399845 ...
-0.285457283664  2.14334055993   7   1.42819405379   -0.00818660844123 ...
-0.372390129412  1.60000213334   6.25    0.626106424052  -0.10136772765 ...
-0.382720203063  1.72614243263   7.25    4.89631941021   -1.10060711916 ...
-0.737957515573  2.90430582851   6   -0.0422721010314    0.4178952497 ...
-0.649532581668  0.657135682543  6   0.692066153971  0.422299120276 ...
-0.627159201987  1.70352689913   5.75    2.62066711305   -1.29237304034 ...
-0.905441299817  1.95663197267   5.5 1.5949697565    -0.27115830703 ...
-1.49322577898   -2.08741765309  6.25    1.23027694802   0.418336889527 ...
-1.48750731567   -1.57274121871  8   3.01660550994   -0.893958254365 ...
-1.39783858087   2.22623066426   7   -0.80842319214  1.47625453886 ...
-0.89274836317   1.30378081742   8   -0.249485058661 0.159871204185 ...
-0.920652246088  4.1437741965    9.75    2.8204453623    0.178149239655 ...
--0.00264276644799   3.07989972052   8.75    -2.56342461535  2.105998353 ...
-0.0198190461681 0.766283759256  8   -1.15838865989  1.56888883418 ...
-0.440050515311  0.127570085801  7.5 0.0400753569995 0.028914333532 ...
-0.129536637901  1.78174141526   6.75    0.959943962785  0.307781224401 ...
-0.398549827172  3.03606770667   6.5 -0.340209794742 0.100979469478 ...
-1.17174775425   0.629625188037  5.75    0.403003686814  0.902394579377 ...
-0.991163981251  2.50862910684   4.75    -1.44963996982  1.16150986945 ...
-0.967603566096  2.12003739013   4.75    0.610846030775  -0.889994896068 ...
-1.14689383604   1.24185011459   4.75    2.01098091308   -1.73846431001 ...
-1.32593824054   0.990713820685  4.75    -0.0955142989332    -0.0369257308362 ...
-0.861135002644  -0.24744943605  6   1.72793107135   -0.691506789639 ...
-1.26870850151   2.09844764887   6.5 1.50720217572   -1.31399187077 ...
-0.260364987715  1.10650139716   6.5 1.13659047496   0.0720441664643 ...
-1.09731242214   0.490796381346  7.25    4.59123894147   -2.14073070763 ...
-1.63792841781   0.612652594286  6.75    1.79604605035   -0.644363995357 ...
-1.48465576034   0.978295808687  6.75    -2.00753620902  1.39437534964 ...
-1.0987608663    4.25212569087   6.25    -2.58901196498  2.56054320803 ...
-1.42592178132   2.76984518311   6.25    0.888195752358  1.03114549274 ...
-1.52958239462   1.31795955491   6.5 -0.902907564082 -0.0952198893776 ...
-1.0170168994    2.14733589918   7   -1.3054866978   2.68803738466 ...
-0.723253652257  3.43552889347   7.5 1.8213700853    0.592593586195 ...
-1.24720806008   3.87383806577   7.5 0.0522300654168 0.988871238698 ...
-0.482531471239  2.67793287032   7.5 2.9693944293    -0.108591166081 ...
-0.154056100439  0.927269031704  6.75    0.119222057561  3.30489209451 ...
-0.0694865769274 6.65916526788   6.25    0.889014476084  -2.83976849035 ...
--0.121267434867 0.341442615696  5.25    0.323053239216  -3.49289229012 ...
-0.726473690375  -3.5423730964   4   2.19149290449   -3.20855054004 ...
-1.39271709108   2.63121085718   3.75    0.88406577736   0.75622580197 ...
-1.07502077727   5.88578836799   4.25    -2.55088273352  2.89018116374 ...
-0.759049251607  4.24703604223   4.5 0.575687665685  -0.388292506167 ...
-]; 
- 
-data = reshape(data,5,86)'; 
-y_obs = data(:,1); 
-pie_obs = data(:,2); 
-R_obs = data(:,3); 
-de = data(:,4); 
-dq = data(:,5); 
- 
-%Country: Canada 
-%Sample Range: 1981:2 to 2002:3 
-%Observations: 86 
-%Variables: Real GDP Growth [%], Inflation [annualized %], Nom Rate [%], 
-%           Exchange Rate Change [%], Terms of Trade Change [%] 
+data = [0.928467646476  11.8716889412   20  0.418037507392  0.227382377518 ...
+-0.705994063083 11.7522582094   21.25   1.09254424511   -1.29488274994 ...
+-0.511895351926 9.68144025625   17.25   -1.66150408407  0.331508393098 ...
+-0.990955971267 10.0890781236   17  1.43016275252   -2.43589670141 ...
+-0.981233061806 12.1094840679   18.25   2.91293288733   -0.790246576864 ...
+-0.882182844512 8.54559460406   15  0.419579139481  0.358729719566 ...
+-0.930893002836 6.19238374422   12.5    -1.48847457959  0.739779938797 ...
+1.53158206947   2.76544271886   11.5    -0.336216769682 0.455559918769 ...
+2.2659052834    5.47418162513   11  0.306436789767  -0.0707985731221 ...
+1.05419803797   6.35698426189   11  0.140700250477  0.620401487202 ...
+1.20161076793   3.4253301593    11  0.461296492351  0.14354323987 ...
+1.73934077971   4.70926070322   11.5    1.35798282982   0.38564694435 ...
+1.71735262584   3.54232079749   12.5    2.9097529155    -0.804308583301 ...
+0.426343657844  3.32719108897   13  1.64214862652   -1.18214664701 ...
+1.67751812324   2.93444727338   11.25   0.344434910651  -1.6529373719 ...
+1.37013301099   4.72303361923   11.75   2.61511526582   0.327684243041 ...
+0.281231073781  4.4893853071    10.5    1.17043449257   1.12855106649 ...
+1.53638992834   3.7325309699    10.25   -0.683947046728 0.11943538737 ...
+1.68081431462   3.34729969129   10  1.41159342106   -1.59065680853 ...
+-0.343321601133 5.05563513564   12  1.75117366498   -2.40127764642 ...
+0.873415608666  3.2779996255    10.25   -1.39895866711  0.0971444398216 ...
+0.26399696544   4.78229419828   9.75    0.0914692438124 0.299310457612 ...
+-0.562233624818 3.88598638237   9.75    -0.0505384765105    0.332826708151 ...
+2.15161914936   3.84859710132   8.75    -3.44811080489  0.789138678784 ...
+1.2345093726    5.62225030942   9.5 -0.366945407434 2.32974981198 ...
+1.62554967459   4.24667132831   10  -0.800958371402 0.0293183770935 ...
+1.33035402527   2.75248979249   9.75    -0.855723113225 0.852493939813 ...
+1.52078814077   3.53415985826   9.75    -3.37963469203  -1.05133958119 ...
+1.16704983697   4.92754079464   10.75   -3.0142303324   0.459907431978 ...
+0.277213572101  4.55532133037   11.75   -0.851995599415 2.03242034852 ...
+0.842215068977  3.11164509647   12.25   -1.08290421696  0.014323281961 ...
+1.05325028606   4.92882647578   13.5    -1.1953883867   0.706764750654 ...
+0.453051253568  6.82998950103   13.5    0.111803656462  0.088462593153 ...
+0.199885995525  5.82643354662   13.5    -0.920501518421 -0.26504958666 ...
+0.137907999624  2.66076369132   13.5    -1.17122929812  -0.995642430514 ...
+0.721949686709  5.70497876823   14.25   1.19378169018   -1.10644839651 ...
+-0.418465249225 3.75861110232   14.75   -1.03131674824  0.188507675831 ...
+-0.644028342116 4.15104788154   13.75   -1.48911756546  0.204560913792 ...
+-0.848213852668 5.65580324027   12.75   0.677011703877  -0.849628054542 ...
+-1.51954076928  11.4866911266   11.25   -0.446024680774 -0.456342350765 ...
+0.265275055215  2.85472749592   9.75    -0.598778202436 -0.907311640831 ...
+0.356162529063  2.29614015658   9.5 -0.46820788432  -1.22130883441 ...
+0.368308864363  -0.539083504685 8   -0.781333991956 0.374007246518 ...
+-0.145751412732 1.61507621789   8.25    3.68291932628   1.32438399845 ...
+0.285457283664  2.14334055993   7   1.42819405379   -0.00818660844123 ...
+0.372390129412  1.60000213334   6.25    0.626106424052  -0.10136772765 ...
+0.382720203063  1.72614243263   7.25    4.89631941021   -1.10060711916 ...
+0.737957515573  2.90430582851   6   -0.0422721010314    0.4178952497 ...
+0.649532581668  0.657135682543  6   0.692066153971  0.422299120276 ...
+0.627159201987  1.70352689913   5.75    2.62066711305   -1.29237304034 ...
+0.905441299817  1.95663197267   5.5 1.5949697565    -0.27115830703 ...
+1.49322577898   -2.08741765309  6.25    1.23027694802   0.418336889527 ...
+1.48750731567   -1.57274121871  8   3.01660550994   -0.893958254365 ...
+1.39783858087   2.22623066426   7   -0.80842319214  1.47625453886 ...
+0.89274836317   1.30378081742   8   -0.249485058661 0.159871204185 ...
+0.920652246088  4.1437741965    9.75    2.8204453623    0.178149239655 ...
+-0.00264276644799   3.07989972052   8.75    -2.56342461535  2.105998353 ...
+0.0198190461681 0.766283759256  8   -1.15838865989  1.56888883418 ...
+0.440050515311  0.127570085801  7.5 0.0400753569995 0.028914333532 ...
+0.129536637901  1.78174141526   6.75    0.959943962785  0.307781224401 ...
+0.398549827172  3.03606770667   6.5 -0.340209794742 0.100979469478 ...
+1.17174775425   0.629625188037  5.75    0.403003686814  0.902394579377 ...
+0.991163981251  2.50862910684   4.75    -1.44963996982  1.16150986945 ...
+0.967603566096  2.12003739013   4.75    0.610846030775  -0.889994896068 ...
+1.14689383604   1.24185011459   4.75    2.01098091308   -1.73846431001 ...
+1.32593824054   0.990713820685  4.75    -0.0955142989332    -0.0369257308362 ...
+0.861135002644  -0.24744943605  6   1.72793107135   -0.691506789639 ...
+1.26870850151   2.09844764887   6.5 1.50720217572   -1.31399187077 ...
+0.260364987715  1.10650139716   6.5 1.13659047496   0.0720441664643 ...
+1.09731242214   0.490796381346  7.25    4.59123894147   -2.14073070763 ...
+1.63792841781   0.612652594286  6.75    1.79604605035   -0.644363995357 ...
+1.48465576034   0.978295808687  6.75    -2.00753620902  1.39437534964 ...
+1.0987608663    4.25212569087   6.25    -2.58901196498  2.56054320803 ...
+1.42592178132   2.76984518311   6.25    0.888195752358  1.03114549274 ...
+1.52958239462   1.31795955491   6.5 -0.902907564082 -0.0952198893776 ...
+1.0170168994    2.14733589918   7   -1.3054866978   2.68803738466 ...
+0.723253652257  3.43552889347   7.5 1.8213700853    0.592593586195 ...
+1.24720806008   3.87383806577   7.5 0.0522300654168 0.988871238698 ...
+0.482531471239  2.67793287032   7.5 2.9693944293    -0.108591166081 ...
+0.154056100439  0.927269031704  6.75    0.119222057561  3.30489209451 ...
+0.0694865769274 6.65916526788   6.25    0.889014476084  -2.83976849035 ...
+-0.121267434867 0.341442615696  5.25    0.323053239216  -3.49289229012 ...
+0.726473690375  -3.5423730964   4   2.19149290449   -3.20855054004 ...
+1.39271709108   2.63121085718   3.75    0.88406577736   0.75622580197 ...
+1.07502077727   5.88578836799   4.25    -2.55088273352  2.89018116374 ...
+0.759049251607  4.24703604223   4.5 0.575687665685  -0.388292506167 ...
+]; 
+ 
+data = reshape(data,5,86)'; 
+y_obs = data(:,1); 
+pie_obs = data(:,2); 
+R_obs = data(:,3); 
+de = data(:,4); 
+dq = data(:,5); 
+ 
+%Country: Canada 
+%Sample Range: 1981:2 to 2002:3 
+%Observations: 86 
+%Variables: Real GDP Growth [%], Inflation [annualized %], Nom Rate [%], 
+%           Exchange Rate Change [%], Terms of Trade Change [%] 
diff --git a/tests/ms-sbvar/archive-files/ftd_2s_caseall_upperchol3v.m b/tests/ms-sbvar/archive-files/ftd_2s_caseall_upperchol3v.m
index 621a59411a1d5f8311f017cf588dc1035b610e1b..ce6156c7b99c9fcc358c986ec4a71c98e2323277 100644
--- a/tests/ms-sbvar/archive-files/ftd_2s_caseall_upperchol3v.m
+++ b/tests/ms-sbvar/archive-files/ftd_2s_caseall_upperchol3v.m
@@ -1,228 +1,228 @@
-function [Ui,Vi,n0,np] = ftd_2s_caseall_upperchol3v(lags,nvar,nStates,indxEqnTv_m,nexo)
-% Case 2&3: Policy a0j and a+j have only time-varying structural variances -- Case 2.
-%           All policy and nonpolicy a0j's and the corresponding constant terms are completely time-varying and only the scale
-%             of each variable in d+j,1** (excluding the constant term) is time-varying -- Case 3.
-%
-% Variables: Pcom, M2, FFR, y, P, U.  Equations: information, policy, money demand, y, P, U.
-% Exporting orthonormal matrices for the deterministic linear restrictions
-%     (equation by equation) with time-varying A0 and D+** equations.
-% See Model II.3 on pp.71k-71r in TVBVAR NOTES (and Waggoner and Zha's Gibbs sampling paper and TVBVAR NOTES p.58).
-%
-% lags: Maximum length of lag.
-% nvar:  Number of endogeous variables.
-% nStates:  Number of states.
-% indxEqnTv_m: nvar-by-2. Stores equation characteristics.
-%                   1st column: labels of equations [1:nvar]'.
-%                   2nd column: labels of time-varying features with
-%                        1: indxConst -- all coefficients are constant,
-%                        2: indxStv -- only shocks are time-varying,
-%                        3: indxTva0pv -- a0 are freely time-varying and each variable i for d+ is time-varying only by the scale lambda_i(s_t).
-%                        4: indxTva0ps -- a0 are freely time-varying and only the scale for the whole of d+ is time-varying.
-%                        5: indxTv -- time-varying for all coeffficients (a0 and a+) where the lag length for a+ may be shorter.
-% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant.
-%          So far this function is written to handle one exogenous variable, which is a constant term.
-%-----------------
-% Ui: nvar-by-1 cell.  In each cell, nvar*nStates-by-qi*si orthonormal basis for the null of the ith
-%           equation contemporaneous restriction matrix where qi is the number of free parameters
-%           within the state and si is the number of free states.
-%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
-%           of total original parameters and bi is a vector of free parameters. When no
-%           restrictions are imposed, we have Ui = I.  There must be at least one free
-%           parameter left for the ith equation in the order of [a_i for 1st state, ..., a_i for last state].
-% Vi: nvar-by-1 cell.  In each cell, k*nStates-by-ri*si orthonormal basis for the null of the ith
-%           equation lagged restriction matrix where k is a total of exogenous variables and
-%           ri is the number of free parameters within the state and si is the number of free states.
-%           With this transformation, we have fi = Vi*gi or Vi'*fi = gi where fi is a vector of total original
-%           parameters and gi is a vector of free parameters.  The ith equation is in the order of [nvar variables
-%           for 1st lag and 1st state, ..., nvar variables for last lag and 1st state, const for 1st state, nvar
-%           variables for 1st lag and 2nd state, nvar variables for last lag and 2nd state, const for 2nd state, and so on].
-% n0: nvar-by-1, whose ith element represents the number of free A0 parameters in ith equation in *all states*.
-% np: nvar-by-1, whose ith element represents the number of free D+ parameters in ith equation in *all states*.
-%
-% Tao Zha, February 2003
-
-
-
-Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
-Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
-n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation in all states.
-np = zeros(nvar,1); % ith element represents the number of free D+ parameters in ith equation in all states.
-
-if (nargin==3)
-   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
-end
-
-
-n = nvar*nStates;
-kvar=lags*nvar+nexo;  % Maximum number of lagged and exogenous variables in each equation under each state.
-k = kvar*nStates;  % Maximum number of lagged and exogenous variables in each equation in all states.
-
-Qi = zeros(n,n,nvar);   % 3rd dim: nvar contemporaneous equations.
-Ri = zeros(k,k,nvar);    % 1st and 2nd dims: lagged and exogenous equations.
-   % Row corresponds to equation with nvar variables for state 1, ..., nvar variables for state nState.
-   %        0 means no restriction.
-   %        1 and -1 or any other number means the linear combination of the corresponding parameters is restricted to 0.
-   %        1 (only 1) means that the corresponding parameter is restricted to 0.
-
-%nfvar = 6;   % number of foreign (Granger causing) variables
-%nhvar = nvar-nfvar;  % number of home (affected) variables.
-
-
-%-------------------------------------------------------------
-%  Beginning the manual input of the restrictions one quation at a time for A0_s.
-%-------------------------------------------------------------
-%
-
-%======== The first equation ===========
-eqninx = 1;
-nreseqn = 2;  % Number of linear restrictions for A0(:,eqninx) for each state.
-if (indxEqnTv_m(eqninx, 2)<=2)
-   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
-      1  0  0      -1  0  0
-      0  1  0       0 -1  0
-      0  0  1       0  0 -1
-
-      0 0 0       0 1 0
-      0 0 0       0 0 1
-                         ];
-   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   for si=1:nStates-1
-      for ki=1:kvar
-         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-      end
-   end
-else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
-   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:nreseqn*nStates,:,eqninx) = [
-      0 1 0       0 0 0
-      0 0 1       0 0 0
-
-      0 0 0       0 1 0
-      0 0 0       0 0 1
-                         ];
-
-   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   else
-      error('.../ftd_2s_caseall_*.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
-   end
-end
-
-
-%======== The second equation ===========
-eqninx = 2;
-nreseqn = 1;  % Number of linear restrictions for A0(:,eqninx) for each state.
-if (indxEqnTv_m(eqninx, 2)<=2)
-   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
-      1  0  0     -1  0  0
-      0  1  0      0 -1  0
-      0  0  1      0  0 -1
-
-      0 0 0      0 0 1
-                         ];
-   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   for si=1:nStates-1
-      for ki=1:kvar
-         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-      end
-   end
-else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
-   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:nreseqn*nStates,:,eqninx) = [
-      0 0 1       0 0 0
-
-      0 0 0      0 0 1
-                         ];
-
-   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   else
-      error('.../ftd_3s_case3a.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
-   end
-
-   %==== For freely time-varying A+ for only the first 6 lags.
-   %====       Lagged restrictions: zeros on all lags except the first 6 lags in the MS equation.
-   %  nlagsno0 = 6;   % Number of lags to be nonzero.
-   %  for si=1:nStates
-   %     for ki = 1:lags-nlagsno0
-   %        for kj=1:nvar
-   %           Ri(kvar*(si-1)+nlagsno0*nvar+nvar*(ki-1)+kj,kvar*(si-1)+nlagsno0*nvar+nvar*(ki-1)+kj,2) = 1;
-   %        end
-   %     end
-   %  end
-   %**** For constant D+_s except the first two lags and the constant term.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   %  for si=1:nStates-1
-   %     for ki=[2*nvar+1:kvar-1]
-   %        Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-   %     end
-   %  end
-end
-
-
-%======== The third equation (money demand) ===========
-eqninx = 3;
-nreseqn = 0;  % Number of linear restrictions for the equation for each state.
-if (indxEqnTv_m(eqninx, 2)<=2)
-   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
-      1  0  0      -1  0  0
-      0  1  0       0 -1  0
-      0  0  1       0  0 -1
-                         ];
-   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   for si=1:nStates-1
-      for ki=1:kvar
-         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-      end
-   end
-else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
-   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   else
-      error('.../ftd_2s_caseall_*.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
-   end
-end
-
-
-
-for ki=1:nvar   %  initializing loop for each equation
-   Ui{ki} = null(Qi(:,:,ki));
-   Vi{ki} = null(Ri(:,:,ki));
-   n0(ki) = size(Ui{ki},2);
-   np(ki) = size(Vi{ki},2);
-end
+function [Ui,Vi,n0,np] = ftd_2s_caseall_upperchol3v(lags,nvar,nStates,indxEqnTv_m,nexo)
+% Case 2&3: Policy a0j and a+j have only time-varying structural variances -- Case 2.
+%           All policy and nonpolicy a0j's and the corresponding constant terms are completely time-varying and only the scale
+%             of each variable in d+j,1** (excluding the constant term) is time-varying -- Case 3.
+%
+% Variables: Pcom, M2, FFR, y, P, U.  Equations: information, policy, money demand, y, P, U.
+% Exporting orthonormal matrices for the deterministic linear restrictions
+%     (equation by equation) with time-varying A0 and D+** equations.
+% See Model II.3 on pp.71k-71r in TVBVAR NOTES (and Waggoner and Zha's Gibbs sampling paper and TVBVAR NOTES p.58).
+%
+% lags: Maximum length of lag.
+% nvar:  Number of endogeous variables.
+% nStates:  Number of states.
+% indxEqnTv_m: nvar-by-2. Stores equation characteristics.
+%                   1st column: labels of equations [1:nvar]'.
+%                   2nd column: labels of time-varying features with
+%                        1: indxConst -- all coefficients are constant,
+%                        2: indxStv -- only shocks are time-varying,
+%                        3: indxTva0pv -- a0 are freely time-varying and each variable i for d+ is time-varying only by the scale lambda_i(s_t).
+%                        4: indxTva0ps -- a0 are freely time-varying and only the scale for the whole of d+ is time-varying.
+%                        5: indxTv -- time-varying for all coeffficients (a0 and a+) where the lag length for a+ may be shorter.
+% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant.
+%          So far this function is written to handle one exogenous variable, which is a constant term.
+%-----------------
+% Ui: nvar-by-1 cell.  In each cell, nvar*nStates-by-qi*si orthonormal basis for the null of the ith
+%           equation contemporaneous restriction matrix where qi is the number of free parameters
+%           within the state and si is the number of free states.
+%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
+%           of total original parameters and bi is a vector of free parameters. When no
+%           restrictions are imposed, we have Ui = I.  There must be at least one free
+%           parameter left for the ith equation in the order of [a_i for 1st state, ..., a_i for last state].
+% Vi: nvar-by-1 cell.  In each cell, k*nStates-by-ri*si orthonormal basis for the null of the ith
+%           equation lagged restriction matrix where k is a total of exogenous variables and
+%           ri is the number of free parameters within the state and si is the number of free states.
+%           With this transformation, we have fi = Vi*gi or Vi'*fi = gi where fi is a vector of total original
+%           parameters and gi is a vector of free parameters.  The ith equation is in the order of [nvar variables
+%           for 1st lag and 1st state, ..., nvar variables for last lag and 1st state, const for 1st state, nvar
+%           variables for 1st lag and 2nd state, nvar variables for last lag and 2nd state, const for 2nd state, and so on].
+% n0: nvar-by-1, whose ith element represents the number of free A0 parameters in ith equation in *all states*.
+% np: nvar-by-1, whose ith element represents the number of free D+ parameters in ith equation in *all states*.
+%
+% Tao Zha, February 2003
+
+
+
+Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
+Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
+n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation in all states.
+np = zeros(nvar,1); % ith element represents the number of free D+ parameters in ith equation in all states.
+
+if (nargin==3)
+   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
+end
+
+
+n = nvar*nStates;
+kvar=lags*nvar+nexo;  % Maximum number of lagged and exogenous variables in each equation under each state.
+k = kvar*nStates;  % Maximum number of lagged and exogenous variables in each equation in all states.
+
+Qi = zeros(n,n,nvar);   % 3rd dim: nvar contemporaneous equations.
+Ri = zeros(k,k,nvar);    % 1st and 2nd dims: lagged and exogenous equations.
+   % Row corresponds to equation with nvar variables for state 1, ..., nvar variables for state nState.
+   %        0 means no restriction.
+   %        1 and -1 or any other number means the linear combination of the corresponding parameters is restricted to 0.
+   %        1 (only 1) means that the corresponding parameter is restricted to 0.
+
+%nfvar = 6;   % number of foreign (Granger causing) variables
+%nhvar = nvar-nfvar;  % number of home (affected) variables.
+
+
+%-------------------------------------------------------------
+%  Beginning the manual input of the restrictions one quation at a time for A0_s.
+%-------------------------------------------------------------
+%
+
+%======== The first equation ===========
+eqninx = 1;
+nreseqn = 2;  % Number of linear restrictions for A0(:,eqninx) for each state.
+if (indxEqnTv_m(eqninx, 2)<=2)
+   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
+      1  0  0      -1  0  0
+      0  1  0       0 -1  0
+      0  0  1       0  0 -1
+
+      0 0 0       0 1 0
+      0 0 0       0 0 1
+                         ];
+   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   for si=1:nStates-1
+      for ki=1:kvar
+         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+      end
+   end
+else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
+   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:nreseqn*nStates,:,eqninx) = [
+      0 1 0       0 0 0
+      0 0 1       0 0 0
+
+      0 0 0       0 1 0
+      0 0 0       0 0 1
+                         ];
+
+   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   else
+      error('.../ftd_2s_caseall_*.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
+   end
+end
+
+
+%======== The second equation ===========
+eqninx = 2;
+nreseqn = 1;  % Number of linear restrictions for A0(:,eqninx) for each state.
+if (indxEqnTv_m(eqninx, 2)<=2)
+   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
+      1  0  0     -1  0  0
+      0  1  0      0 -1  0
+      0  0  1      0  0 -1
+
+      0 0 0      0 0 1
+                         ];
+   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   for si=1:nStates-1
+      for ki=1:kvar
+         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+      end
+   end
+else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
+   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:nreseqn*nStates,:,eqninx) = [
+      0 0 1       0 0 0
+
+      0 0 0      0 0 1
+                         ];
+
+   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   else
+      error('.../ftd_3s_case3a.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
+   end
+
+   %==== For freely time-varying A+ for only the first 6 lags.
+   %====       Lagged restrictions: zeros on all lags except the first 6 lags in the MS equation.
+   %  nlagsno0 = 6;   % Number of lags to be nonzero.
+   %  for si=1:nStates
+   %     for ki = 1:lags-nlagsno0
+   %        for kj=1:nvar
+   %           Ri(kvar*(si-1)+nlagsno0*nvar+nvar*(ki-1)+kj,kvar*(si-1)+nlagsno0*nvar+nvar*(ki-1)+kj,2) = 1;
+   %        end
+   %     end
+   %  end
+   %**** For constant D+_s except the first two lags and the constant term.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   %  for si=1:nStates-1
+   %     for ki=[2*nvar+1:kvar-1]
+   %        Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+   %     end
+   %  end
+end
+
+
+%======== The third equation (money demand) ===========
+eqninx = 3;
+nreseqn = 0;  % Number of linear restrictions for the equation for each state.
+if (indxEqnTv_m(eqninx, 2)<=2)
+   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
+      1  0  0      -1  0  0
+      0  1  0       0 -1  0
+      0  0  1       0  0 -1
+                         ];
+   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   for si=1:nStates-1
+      for ki=1:kvar
+         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+      end
+   end
+else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
+   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   else
+      error('.../ftd_2s_caseall_*.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
+   end
+end
+
+
+
+for ki=1:nvar   %  initializing loop for each equation
+   Ui{ki} = null(Qi(:,:,ki));
+   Vi{ki} = null(Ri(:,:,ki));
+   n0(ki) = size(Ui{ki},2);
+   np(ki) = size(Vi{ki},2);
+end
diff --git a/tests/ms-sbvar/archive-files/ftd_2s_caseall_upperchol4v.m b/tests/ms-sbvar/archive-files/ftd_2s_caseall_upperchol4v.m
index d83a90b3723b85d45b23be36fb8894876da2a500..bc3215cdeb318494043b56b4ed1302f44b2e1081 100644
--- a/tests/ms-sbvar/archive-files/ftd_2s_caseall_upperchol4v.m
+++ b/tests/ms-sbvar/archive-files/ftd_2s_caseall_upperchol4v.m
@@ -1,331 +1,331 @@
-function [Ui,Vi,n0,np] = ftd_2s_caseall_upperchol4v(lags,nvar,nStates,indxEqnTv_m,nexo)
-% Case 2&3: Policy a0j and a+j have only time-varying structural variances -- Case 2.
-%           All policy and nonpolicy a0j's and the corresponding constant terms are completely time-varying and only the scale
-%             of each variable in d+j,1** (excluding the constant term) is time-varying -- Case 3.
-%
-% Variables: Pcom, M2, FFR, y, P, U.  Equations: information, policy, money demand, y, P, U.
-% Exporting orthonormal matrices for the deterministic linear restrictions
-%     (equation by equation) with time-varying A0 and D+** equations.
-% See Model II.3 on pp.71k-71r in TVBVAR NOTES (and Waggoner and Zha's Gibbs sampling paper and TVBVAR NOTES p.58).
-%
-% lags: Maximum length of lag.
-% nvar:  Number of endogeous variables.
-% nStates:  Number of states.
-% indxEqnTv_m: nvar-by-2. Stores equation characteristics.
-%                   1st column: labels of equations [1:nvar]'.
-%                   2nd column: labels of time-varying features with
-%                        1: indxConst -- all coefficients are constant,
-%                        2: indxStv -- only shocks are time-varying,
-%                        3: indxTva0pv -- a0 are freely time-varying and each variable i for d+ is time-varying only by the scale lambda_i(s_t).
-%                        4: indxTva0ps -- a0 are freely time-varying and only the scale for the whole of d+ is time-varying.
-%                        5: indxTv -- time-varying for all coeffficients (a0 and a+) where the lag length for a+ may be shorter.
-% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant.
-%          So far this function is written to handle one exogenous variable, which is a constant term.
-%-----------------
-% Ui: nvar-by-1 cell.  In each cell, nvar*nStates-by-qi*si orthonormal basis for the null of the ith
-%           equation contemporaneous restriction matrix where qi is the number of free parameters
-%           within the state and si is the number of free states.
-%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
-%           of total original parameters and bi is a vector of free parameters. When no
-%           restrictions are imposed, we have Ui = I.  There must be at least one free
-%           parameter left for the ith equation in the order of [a_i for 1st state, ..., a_i for last state].
-% Vi: nvar-by-1 cell.  In each cell, k*nStates-by-ri*si orthonormal basis for the null of the ith
-%           equation lagged restriction matrix where k is a total of exogenous variables and
-%           ri is the number of free parameters within the state and si is the number of free states.
-%           With this transformation, we have fi = Vi*gi or Vi'*fi = gi where fi is a vector of total original
-%           parameters and gi is a vector of free parameters.  The ith equation is in the order of [nvar variables
-%           for 1st lag and 1st state, ..., nvar variables for last lag and 1st state, const for 1st state, nvar
-%           variables for 1st lag and 2nd state, nvar variables for last lag and 2nd state, const for 2nd state, and so on].
-% n0: nvar-by-1, whose ith element represents the number of free A0 parameters in ith equation in *all states*.
-% np: nvar-by-1, whose ith element represents the number of free D+ parameters in ith equation in *all states*.
-%
-% Tao Zha, February 2003
-
-
-
-Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
-Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
-n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation in all states.
-np = zeros(nvar,1); % ith element represents the number of free D+ parameters in ith equation in all states.
-
-if (nargin==3)
-   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
-end
-
-
-n = nvar*nStates;
-kvar=lags*nvar+nexo;  % Maximum number of lagged and exogenous variables in each equation under each state.
-k = kvar*nStates;  % Maximum number of lagged and exogenous variables in each equation in all states.
-
-Qi = zeros(n,n,nvar);   % 3rd dim: nvar contemporaneous equations.
-Ri = zeros(k,k,nvar);    % 1st and 2nd dims: lagged and exogenous equations.
-   % Row corresponds to equation with nvar variables for state 1, ..., nvar variables for state nState.
-   %        0 means no restriction.
-   %        1 and -1 or any other number means the linear combination of the corresponding parameters is restricted to 0.
-   %        1 (only 1) means that the corresponding parameter is restricted to 0.
-
-%nfvar = 6;   % number of foreign (Granger causing) variables
-%nhvar = nvar-nfvar;  % number of home (affected) variables.
-
-
-%-------------------------------------------------------------
-%  Beginning the manual input of the restrictions one quation at a time for A0_s.
-%-------------------------------------------------------------
-%
-
-%======== The first equation ===========
-eqninx = 1;
-nreseqn = 3;  % Number of linear restrictions for A0(:,eqninx) for each state.
-if (indxEqnTv_m(eqninx, 2)<=2)
-   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
-      1  0  0  0     -1  0  0  0
-      0  1  0  0      0 -1  0  0
-      0  0  1  0      0  0 -1  0
-      0  0  0  1      0  0  0 -1
-
-      0 0 0 0      0 1 0 0
-      0 0 0 0      0 0 1 0
-      0 0 0 0      0 0 0 1
-                         ];
-   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   for si=1:nStates-1
-      for ki=1:kvar
-         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-      end
-   end
-else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
-   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:nreseqn*nStates,:,eqninx) = [
-      0 1 0 0      0 0 0 0
-      0 0 1 0      0 0 0 0
-      0 0 0 1      0 0 0 0
-
-      0 0 0 0      0 1 0 0
-      0 0 0 0      0 0 1 0
-      0 0 0 0      0 0 0 1
-                         ];
-
-   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   else
-      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
-   end
-end
-
-
-%======== The second equation ===========
-eqninx = 2;
-nreseqn = 2;  % Number of linear restrictions for A0(:,eqninx) for each state.
-if (indxEqnTv_m(eqninx, 2)<=2)
-   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
-      1  0  0  0     -1  0  0  0
-      0  1  0  0      0 -1  0  0
-      0  0  1  0      0  0 -1  0
-      0  0  0  1      0  0  0 -1
-
-      0 0 0 0      0 0 1 0
-      0 0 0 0      0 0 0 1
-                         ];
-   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   for si=1:nStates-1
-      for ki=1:kvar
-         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-      end
-   end
-else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
-   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:nreseqn*nStates,:,eqninx) = [
-      0 0 1 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 1
-                         ];
-
-   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   else
-      error('.../ftd_3s_case3a.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
-   end
-
-   %==== For freely time-varying A+ for only the first 6 lags.
-   %====       Lagged restrictions: zeros on all lags except the first 6 lags in the MS equation.
-   %  nlagsno0 = 6;   % Number of lags to be nonzero.
-   %  for si=1:nStates
-   %     for ki = 1:lags-nlagsno0
-   %        for kj=1:nvar
-   %           Ri(kvar*(si-1)+nlagsno0*nvar+nvar*(ki-1)+kj,kvar*(si-1)+nlagsno0*nvar+nvar*(ki-1)+kj,2) = 1;
-   %        end
-   %     end
-   %  end
-   %**** For constant D+_s except the first two lags and the constant term.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   %  for si=1:nStates-1
-   %     for ki=[2*nvar+1:kvar-1]
-   %        Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-   %     end
-   %  end
-end
-
-
-%======== The third equation ===========
-eqninx = 3;
-nreseqn = 1;  % Number of linear restrictions for the equation for each state.
-if (indxEqnTv_m(eqninx, 2)<=2)
-   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
-      1  0  0  0     -1  0  0  0
-      0  1  0  0      0 -1  0  0
-      0  0  1  0      0  0 -1  0
-      0  0  0  1      0  0  0 -1
-
-      0 0 0 0      0 0 0 1
-                         ];
-   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   for si=1:nStates-1
-      for ki=1:kvar
-         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-      end
-   end
-else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
-   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:nreseqn*nStates,:,eqninx) = [
-      0 0 0 1      0 0 0 0
-
-      0 0 0 0      0 0 0 1
-                         ];
-   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   else
-      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
-   end
-end
-
-
-%======== The fourth equation ===========
-eqninx = 4;
-nreseqn = 0;  % Number of linear restrictions for the equation for each state.
-if (indxEqnTv_m(eqninx, 2)<=2)
-   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
-      1  0  0  0     -1  0  0  0
-      0  1  0  0      0 -1  0  0
-      0  0  1  0      0  0 -1  0
-      0  0  0  1      0  0  0 -1
-                         ];
-   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   for si=1:nStates-1
-      for ki=1:kvar
-         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-      end
-   end
-else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
-   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   else
-      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
-   end
-end
-
-
-
-
-
-
-%===== Lagged restrictions in foreign (Granger causing) block
-%nfbres = lags*(nvar-nfvar);  % number of block restrictions in each foreign equation
-%bfor = zeros(nfbres,k);  % each foreign equation
-%cnt=0;
-%for ki = 1:lags
-%   for kj=1:nvar-nfvar
-%      cnt=cnt+1;
-%      bfor(cnt,nvar*(ki-1)+nfvar+kj) = 1;
-%   end
-%end
-%%
-%if cnt~=nfbres
-%   error('Check lagged restrictions in foreign equations!')
-%end
-%%
-%for kj=1:nfvar
-%   Ri(1:nfbres,:,kj) = bfor;
-%end
-
-
-%===== Lagged restrictions in home (affected) block
-%
-%~~~~~ selected domestic equations
-%dlrindx = nfvar+1; %[nfvar+1 nfvar+2];  % index for relevant home equations
-%rfvindx = []; %[6];  %[1 2 3 5];  % index for restricted foreign variables (e.g., Poil, M2, FFR, P).
-%%nf2hvar = nfvar-length(rfvindx);  % number of free parameters -- foreign variables entering the home sector
-%nhbres = lags*length(rfvindx);  % number of block restrictions in each home equation
-%bhom = zeros(nhbres,k);  % each home equation
-%cnt=0;
-%for ki = 1:lags
-%   for kj=1:length(rfvindx)
-%      cnt=cnt+1;
-%      bhom(cnt,nvar*(ki-1)+rfvindx(kj)) = 1;
-%   end
-%end
-%%
-%if cnt~=nhbres
-%   error('Check lagged restrictions in domestic equations!')
-%end
-%%
-%for kj=dlrindx
-%   Ri(1:nhbres,:,kj) = bhom;
-%end
-
-
-
-for ki=1:nvar   %  initializing loop for each equation
-   Ui{ki} = null(Qi(:,:,ki));
-   Vi{ki} = null(Ri(:,:,ki));
-   n0(ki) = size(Ui{ki},2);
-   np(ki) = size(Vi{ki},2);
-end
+function [Ui,Vi,n0,np] = ftd_2s_caseall_upperchol4v(lags,nvar,nStates,indxEqnTv_m,nexo)
+% Case 2&3: Policy a0j and a+j have only time-varying structural variances -- Case 2.
+%           All policy and nonpolicy a0j's and the corresponding constant terms are completely time-varying and only the scale
+%             of each variable in d+j,1** (excluding the constant term) is time-varying -- Case 3.
+%
+% Variables: Pcom, M2, FFR, y, P, U.  Equations: information, policy, money demand, y, P, U.
+% Exporting orthonormal matrices for the deterministic linear restrictions
+%     (equation by equation) with time-varying A0 and D+** equations.
+% See Model II.3 on pp.71k-71r in TVBVAR NOTES (and Waggoner and Zha's Gibbs sampling paper and TVBVAR NOTES p.58).
+%
+% lags: Maximum length of lag.
+% nvar:  Number of endogeous variables.
+% nStates:  Number of states.
+% indxEqnTv_m: nvar-by-2. Stores equation characteristics.
+%                   1st column: labels of equations [1:nvar]'.
+%                   2nd column: labels of time-varying features with
+%                        1: indxConst -- all coefficients are constant,
+%                        2: indxStv -- only shocks are time-varying,
+%                        3: indxTva0pv -- a0 are freely time-varying and each variable i for d+ is time-varying only by the scale lambda_i(s_t).
+%                        4: indxTva0ps -- a0 are freely time-varying and only the scale for the whole of d+ is time-varying.
+%                        5: indxTv -- time-varying for all coeffficients (a0 and a+) where the lag length for a+ may be shorter.
+% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant.
+%          So far this function is written to handle one exogenous variable, which is a constant term.
+%-----------------
+% Ui: nvar-by-1 cell.  In each cell, nvar*nStates-by-qi*si orthonormal basis for the null of the ith
+%           equation contemporaneous restriction matrix where qi is the number of free parameters
+%           within the state and si is the number of free states.
+%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
+%           of total original parameters and bi is a vector of free parameters. When no
+%           restrictions are imposed, we have Ui = I.  There must be at least one free
+%           parameter left for the ith equation in the order of [a_i for 1st state, ..., a_i for last state].
+% Vi: nvar-by-1 cell.  In each cell, k*nStates-by-ri*si orthonormal basis for the null of the ith
+%           equation lagged restriction matrix where k is a total of exogenous variables and
+%           ri is the number of free parameters within the state and si is the number of free states.
+%           With this transformation, we have fi = Vi*gi or Vi'*fi = gi where fi is a vector of total original
+%           parameters and gi is a vector of free parameters.  The ith equation is in the order of [nvar variables
+%           for 1st lag and 1st state, ..., nvar variables for last lag and 1st state, const for 1st state, nvar
+%           variables for 1st lag and 2nd state, nvar variables for last lag and 2nd state, const for 2nd state, and so on].
+% n0: nvar-by-1, whose ith element represents the number of free A0 parameters in ith equation in *all states*.
+% np: nvar-by-1, whose ith element represents the number of free D+ parameters in ith equation in *all states*.
+%
+% Tao Zha, February 2003
+
+
+
+Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
+Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
+n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation in all states.
+np = zeros(nvar,1); % ith element represents the number of free D+ parameters in ith equation in all states.
+
+if (nargin==3)
+   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
+end
+
+
+n = nvar*nStates;
+kvar=lags*nvar+nexo;  % Maximum number of lagged and exogenous variables in each equation under each state.
+k = kvar*nStates;  % Maximum number of lagged and exogenous variables in each equation in all states.
+
+Qi = zeros(n,n,nvar);   % 3rd dim: nvar contemporaneous equations.
+Ri = zeros(k,k,nvar);    % 1st and 2nd dims: lagged and exogenous equations.
+   % Row corresponds to equation with nvar variables for state 1, ..., nvar variables for state nState.
+   %        0 means no restriction.
+   %        1 and -1 or any other number means the linear combination of the corresponding parameters is restricted to 0.
+   %        1 (only 1) means that the corresponding parameter is restricted to 0.
+
+%nfvar = 6;   % number of foreign (Granger causing) variables
+%nhvar = nvar-nfvar;  % number of home (affected) variables.
+
+
+%-------------------------------------------------------------
+%  Beginning the manual input of the restrictions one quation at a time for A0_s.
+%-------------------------------------------------------------
+%
+
+%======== The first equation ===========
+eqninx = 1;
+nreseqn = 3;  % Number of linear restrictions for A0(:,eqninx) for each state.
+if (indxEqnTv_m(eqninx, 2)<=2)
+   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
+      1  0  0  0     -1  0  0  0
+      0  1  0  0      0 -1  0  0
+      0  0  1  0      0  0 -1  0
+      0  0  0  1      0  0  0 -1
+
+      0 0 0 0      0 1 0 0
+      0 0 0 0      0 0 1 0
+      0 0 0 0      0 0 0 1
+                         ];
+   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   for si=1:nStates-1
+      for ki=1:kvar
+         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+      end
+   end
+else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
+   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:nreseqn*nStates,:,eqninx) = [
+      0 1 0 0      0 0 0 0
+      0 0 1 0      0 0 0 0
+      0 0 0 1      0 0 0 0
+
+      0 0 0 0      0 1 0 0
+      0 0 0 0      0 0 1 0
+      0 0 0 0      0 0 0 1
+                         ];
+
+   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   else
+      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
+   end
+end
+
+
+%======== The second equation ===========
+eqninx = 2;
+nreseqn = 2;  % Number of linear restrictions for A0(:,eqninx) for each state.
+if (indxEqnTv_m(eqninx, 2)<=2)
+   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
+      1  0  0  0     -1  0  0  0
+      0  1  0  0      0 -1  0  0
+      0  0  1  0      0  0 -1  0
+      0  0  0  1      0  0  0 -1
+
+      0 0 0 0      0 0 1 0
+      0 0 0 0      0 0 0 1
+                         ];
+   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   for si=1:nStates-1
+      for ki=1:kvar
+         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+      end
+   end
+else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
+   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:nreseqn*nStates,:,eqninx) = [
+      0 0 1 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 1
+                         ];
+
+   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   else
+      error('.../ftd_3s_case3a.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
+   end
+
+   %==== For freely time-varying A+ for only the first 6 lags.
+   %====       Lagged restrictions: zeros on all lags except the first 6 lags in the MS equation.
+   %  nlagsno0 = 6;   % Number of lags to be nonzero.
+   %  for si=1:nStates
+   %     for ki = 1:lags-nlagsno0
+   %        for kj=1:nvar
+   %           Ri(kvar*(si-1)+nlagsno0*nvar+nvar*(ki-1)+kj,kvar*(si-1)+nlagsno0*nvar+nvar*(ki-1)+kj,2) = 1;
+   %        end
+   %     end
+   %  end
+   %**** For constant D+_s except the first two lags and the constant term.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   %  for si=1:nStates-1
+   %     for ki=[2*nvar+1:kvar-1]
+   %        Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+   %     end
+   %  end
+end
+
+
+%======== The third equation ===========
+eqninx = 3;
+nreseqn = 1;  % Number of linear restrictions for the equation for each state.
+if (indxEqnTv_m(eqninx, 2)<=2)
+   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
+      1  0  0  0     -1  0  0  0
+      0  1  0  0      0 -1  0  0
+      0  0  1  0      0  0 -1  0
+      0  0  0  1      0  0  0 -1
+
+      0 0 0 0      0 0 0 1
+                         ];
+   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   for si=1:nStates-1
+      for ki=1:kvar
+         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+      end
+   end
+else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
+   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:nreseqn*nStates,:,eqninx) = [
+      0 0 0 1      0 0 0 0
+
+      0 0 0 0      0 0 0 1
+                         ];
+   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   else
+      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
+   end
+end
+
+
+%======== The fourth equation ===========
+eqninx = 4;
+nreseqn = 0;  % Number of linear restrictions for the equation for each state.
+if (indxEqnTv_m(eqninx, 2)<=2)
+   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
+      1  0  0  0     -1  0  0  0
+      0  1  0  0      0 -1  0  0
+      0  0  1  0      0  0 -1  0
+      0  0  0  1      0  0  0 -1
+                         ];
+   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   for si=1:nStates-1
+      for ki=1:kvar
+         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+      end
+   end
+else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
+   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   else
+      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
+   end
+end
+
+
+
+
+
+
+%===== Lagged restrictions in foreign (Granger causing) block
+%nfbres = lags*(nvar-nfvar);  % number of block restrictions in each foreign equation
+%bfor = zeros(nfbres,k);  % each foreign equation
+%cnt=0;
+%for ki = 1:lags
+%   for kj=1:nvar-nfvar
+%      cnt=cnt+1;
+%      bfor(cnt,nvar*(ki-1)+nfvar+kj) = 1;
+%   end
+%end
+%%
+%if cnt~=nfbres
+%   error('Check lagged restrictions in foreign equations!')
+%end
+%%
+%for kj=1:nfvar
+%   Ri(1:nfbres,:,kj) = bfor;
+%end
+
+
+%===== Lagged restrictions in home (affected) block
+%
+%~~~~~ selected domestic equations
+%dlrindx = nfvar+1; %[nfvar+1 nfvar+2];  % index for relevant home equations
+%rfvindx = []; %[6];  %[1 2 3 5];  % index for restricted foreign variables (e.g., Poil, M2, FFR, P).
+%%nf2hvar = nfvar-length(rfvindx);  % number of free parameters -- foreign variables entering the home sector
+%nhbres = lags*length(rfvindx);  % number of block restrictions in each home equation
+%bhom = zeros(nhbres,k);  % each home equation
+%cnt=0;
+%for ki = 1:lags
+%   for kj=1:length(rfvindx)
+%      cnt=cnt+1;
+%      bhom(cnt,nvar*(ki-1)+rfvindx(kj)) = 1;
+%   end
+%end
+%%
+%if cnt~=nhbres
+%   error('Check lagged restrictions in domestic equations!')
+%end
+%%
+%for kj=dlrindx
+%   Ri(1:nhbres,:,kj) = bhom;
+%end
+
+
+
+for ki=1:nvar   %  initializing loop for each equation
+   Ui{ki} = null(Qi(:,:,ki));
+   Vi{ki} = null(Ri(:,:,ki));
+   n0(ki) = size(Ui{ki},2);
+   np(ki) = size(Vi{ki},2);
+end
diff --git a/tests/ms-sbvar/archive-files/ftd_2s_caseall_upperchol6v.m b/tests/ms-sbvar/archive-files/ftd_2s_caseall_upperchol6v.m
index 4fa71200b891c69370b5acd3cb61f8f9bbaa2ba1..389109df7adc60a840dff7574284435d98d6fb7d 100644
--- a/tests/ms-sbvar/archive-files/ftd_2s_caseall_upperchol6v.m
+++ b/tests/ms-sbvar/archive-files/ftd_2s_caseall_upperchol6v.m
@@ -1,455 +1,455 @@
-function [Ui,Vi,n0,np] = ftd_2s_caseall_upperchol6v(lags,nvar,nStates,indxEqnTv_m,nexo)
-% Case 2&3: Policy a0j and a+j have only time-varying structural variances -- Case 2.
-%           All policy and nonpolicy a0j's and the corresponding constant terms are completely time-varying and only the scale
-%             of each variable in d+j,1** (excluding the constant term) is time-varying -- Case 3.
-%
-% Variables: Pcom, M2, FFR, y, P, U.  Equations: information, policy, money demand, y, P, U.
-% Exporting orthonormal matrices for the deterministic linear restrictions
-%     (equation by equation) with time-varying A0 and D+** equations.
-% See Model II.3 on pp.71k-71r in TVBVAR NOTES (and Waggoner and Zha's Gibbs sampling paper and TVBVAR NOTES p.58).
-%
-% lags: Maximum length of lag.
-% nvar:  Number of endogeous variables.
-% nStates:  Number of states.
-% indxEqnTv_m: nvar-by-2. Stores equation characteristics.
-%                   1st column: labels of equations [1:nvar]'.
-%                   2nd column: labels of time-varying features with
-%                        1: indxConst -- all coefficients are constant,
-%                        2: indxStv -- only shocks are time-varying,
-%                        3: indxTva0pv -- a0 are freely time-varying and each variable i for d+ is time-varying only by the scale lambda_i(s_t).
-%                        4: indxTva0ps -- a0 are freely time-varying and only the scale for the whole of d+ is time-varying.
-%                        5: indxTv -- time-varying for all coeffficients (a0 and a+) where the lag length for a+ may be shorter.
-% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant.
-%          So far this function is written to handle one exogenous variable, which is a constant term.
-%-----------------
-% Ui: nvar-by-1 cell.  In each cell, nvar*nStates-by-qi*si orthonormal basis for the null of the ith
-%           equation contemporaneous restriction matrix where qi is the number of free parameters
-%           within the state and si is the number of free states.
-%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
-%           of total original parameters and bi is a vector of free parameters. When no
-%           restrictions are imposed, we have Ui = I.  There must be at least one free
-%           parameter left for the ith equation in the order of [a_i for 1st state, ..., a_i for last state].
-% Vi: nvar-by-1 cell.  In each cell, k*nStates-by-ri*si orthonormal basis for the null of the ith
-%           equation lagged restriction matrix where k is a total of exogenous variables and
-%           ri is the number of free parameters within the state and si is the number of free states.
-%           With this transformation, we have fi = Vi*gi or Vi'*fi = gi where fi is a vector of total original
-%           parameters and gi is a vector of free parameters.  The ith equation is in the order of [nvar variables
-%           for 1st lag and 1st state, ..., nvar variables for last lag and 1st state, const for 1st state, nvar
-%           variables for 1st lag and 2nd state, nvar variables for last lag and 2nd state, const for 2nd state, and so on].
-% n0: nvar-by-1, whose ith element represents the number of free A0 parameters in ith equation in *all states*.
-% np: nvar-by-1, whose ith element represents the number of free D+ parameters in ith equation in *all states*.
-%
-% Tao Zha, February 2003
-
-
-
-Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
-Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
-n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation in all states.
-np = zeros(nvar,1); % ith element represents the number of free D+ parameters in ith equation in all states.
-
-if (nargin==3)
-   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
-end
-
-
-n = nvar*nStates;
-kvar=lags*nvar+nexo;  % Maximum number of lagged and exogenous variables in each equation under each state.
-k = kvar*nStates;  % Maximum number of lagged and exogenous variables in each equation in all states.
-
-Qi = zeros(n,n,nvar);   % 3rd dim: nvar contemporaneous equations.
-Ri = zeros(k,k,nvar);    % 1st and 2nd dims: lagged and exogenous equations.
-   % Row corresponds to equation with nvar variables for state 1, ..., nvar variables for state nState.
-   %        0 means no restriction.
-   %        1 and -1 or any other number means the linear combination of the corresponding parameters is restricted to 0.
-   %        1 (only 1) means that the corresponding parameter is restricted to 0.
-
-%nfvar = 6;   % number of foreign (Granger causing) variables
-%nhvar = nvar-nfvar;  % number of home (affected) variables.
-
-
-%-------------------------------------------------------------
-%  Beginning the manual input of the restrictions one quation at a time for A0_s.
-%-------------------------------------------------------------
-%
-
-%======== The first equation ===========
-eqninx = 1;
-nreseqn = 5;  % Number of linear restrictions for A0(:,eqninx) for each state.
-if (indxEqnTv_m(eqninx, 2)<=2)
-   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
-      1  0  0  0  0  0     -1  0  0  0  0  0
-      0  1  0  0  0  0      0 -1  0  0  0  0
-      0  0  1  0  0  0      0  0 -1  0  0  0
-      0  0  0  1  0  0      0  0  0 -1  0  0
-      0  0  0  0  1  0      0  0  0  0 -1  0
-      0  0  0  0  0  1      0  0  0  0  0 -1
-
-      0 0 0 0 0 0     0 1 0 0 0 0
-      0 0 0 0 0 0     0 0 1 0 0 0
-      0 0 0 0 0 0     0 0 0 1 0 0
-      0 0 0 0 0 0     0 0 0 0 1 0
-      0 0 0 0 0 0     0 0 0 0 0 1
-                         ];
-   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   for si=1:nStates-1
-      for ki=1:kvar
-         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-      end
-   end
-else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
-   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:nreseqn*nStates,:,eqninx) = [
-      0 1 0 0 0 0     0 0 0 0 0 0
-      0 0 1 0 0 0     0 0 0 0 0 0
-      0 0 0 1 0 0     0 0 0 0 0 0
-      0 0 0 0 1 0     0 0 0 0 0 0
-      0 0 0 0 0 1     0 0 0 0 0 0
-
-      0 0 0 0 0 0     0 1 0 0 0 0
-      0 0 0 0 0 0     0 0 1 0 0 0
-      0 0 0 0 0 0     0 0 0 1 0 0
-      0 0 0 0 0 0     0 0 0 0 1 0
-      0 0 0 0 0 0     0 0 0 0 0 1
-                         ];
-
-   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   else
-      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
-   end
-end
-
-
-
-%======== The second equation ===========
-eqninx = 2;
-nreseqn = 4;  % Number of linear restrictions for A0(:,eqninx) for each state.
-if (indxEqnTv_m(eqninx, 2)<=2)
-   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
-      1  0  0  0  0  0     -1  0  0  0  0  0
-      0  1  0  0  0  0      0 -1  0  0  0  0
-      0  0  1  0  0  0      0  0 -1  0  0  0
-      0  0  0  1  0  0      0  0  0 -1  0  0
-      0  0  0  0  1  0      0  0  0  0 -1  0
-      0  0  0  0  0  1      0  0  0  0  0 -1
-
-      0 0 0 0 0 0     0 0 1 0 0 0
-      0 0 0 0 0 0     0 0 0 1 0 0
-      0 0 0 0 0 0     0 0 0 0 1 0
-      0 0 0 0 0 0     0 0 0 0 0 1
-                         ];
-   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   for si=1:nStates-1
-      for ki=1:kvar
-         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-      end
-   end
-else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
-   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:nreseqn*nStates,:,eqninx) = [
-      0 0 1 0 0 0     0 0 0 0 0 0
-      0 0 0 1 0 0     0 0 0 0 0 0
-      0 0 0 0 1 0     0 0 0 0 0 0
-      0 0 0 0 0 1     0 0 0 0 0 0
-
-      0 0 0 0 0 0     0 0 1 0 0 0
-      0 0 0 0 0 0     0 0 0 1 0 0
-      0 0 0 0 0 0     0 0 0 0 1 0
-      0 0 0 0 0 0     0 0 0 0 0 1
-                         ];
-
-   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   else
-      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
-   end
-end
-
-
-%======== The third equation ===========
-eqninx = 3;
-nreseqn = 3;  % Number of linear restrictions for A0(:,eqninx) for each state.
-if (indxEqnTv_m(eqninx, 2)<=2)
-   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
-      1  0  0  0  0  0     -1  0  0  0  0  0
-      0  1  0  0  0  0      0 -1  0  0  0  0
-      0  0  1  0  0  0      0  0 -1  0  0  0
-      0  0  0  1  0  0      0  0  0 -1  0  0
-      0  0  0  0  1  0      0  0  0  0 -1  0
-      0  0  0  0  0  1      0  0  0  0  0 -1
-
-      0 0 0 0 0 0     0 0 0 1 0 0
-      0 0 0 0 0 0     0 0 0 0 1 0
-      0 0 0 0 0 0     0 0 0 0 0 1
-                         ];
-   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   for si=1:nStates-1
-      for ki=1:kvar
-         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-      end
-   end
-else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
-   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:nreseqn*nStates,:,eqninx) = [
-      0 0 0 1 0 0     0 0 0 0 0 0
-      0 0 0 0 1 0     0 0 0 0 0 0
-      0 0 0 0 0 1     0 0 0 0 0 0
-
-      0 0 0 0 0 0     0 0 0 1 0 0
-      0 0 0 0 0 0     0 0 0 0 1 0
-      0 0 0 0 0 0     0 0 0 0 0 1
-                         ];
-
-   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   else
-      error('.../ftd_3s_case3a.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
-   end
-
-   %==== For freely time-varying A+ for only the first 6 lags.
-   %====       Lagged restrictions: zeros on all lags except the first 6 lags in the MS equation.
-   %  nlagsno0 = 6;   % Number of lags to be nonzero.
-   %  for si=1:nStates
-   %     for ki = 1:lags-nlagsno0
-   %        for kj=1:nvar
-   %           Ri(kvar*(si-1)+nlagsno0*nvar+nvar*(ki-1)+kj,kvar*(si-1)+nlagsno0*nvar+nvar*(ki-1)+kj,2) = 1;
-   %        end
-   %     end
-   %  end
-   %**** For constant D+_s except the first two lags and the constant term.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   %  for si=1:nStates-1
-   %     for ki=[2*nvar+1:kvar-1]
-   %        Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-   %     end
-   %  end
-end
-
-
-%======== The fourth equation ===========
-eqninx = 4;
-nreseqn = 2;  % Number of linear restrictions for the equation for each state.
-if (indxEqnTv_m(eqninx, 2)<=2)
-   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
-      1  0  0  0  0  0     -1  0  0  0  0  0
-      0  1  0  0  0  0      0 -1  0  0  0  0
-      0  0  1  0  0  0      0  0 -1  0  0  0
-      0  0  0  1  0  0      0  0  0 -1  0  0
-      0  0  0  0  1  0      0  0  0  0 -1  0
-      0  0  0  0  0  1      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 0 1
-                         ];
-   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   for si=1:nStates-1
-      for ki=1:kvar
-         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-      end
-   end
-else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
-   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:nreseqn*nStates,:,eqninx) = [
-      0 0 0 0 1 0     0 0 0 0 0 0
-      0 0 0 0 0 1     0 0 0 0 0 0
-
-      0 0 0 0 0 0     0 0 0 0 1 0
-      0 0 0 0 0 0     0 0 0 0 0 1
-                         ];
-   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   else
-      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
-   end
-end
-
-
-%======== The fifth equation ===========
-eqninx = 5;
-nreseqn = 1;  % Number of linear restrictions for the equation for each state.
-if (indxEqnTv_m(eqninx, 2)<=2)
-   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
-      1  0  0  0  0  0     -1  0  0  0  0  0
-      0  1  0  0  0  0      0 -1  0  0  0  0
-      0  0  1  0  0  0      0  0 -1  0  0  0
-      0  0  0  1  0  0      0  0  0 -1  0  0
-      0  0  0  0  1  0      0  0  0  0 -1  0
-      0  0  0  0  0  1      0  0  0  0  0 -1
-
-      0 0 0 0 0 0     0 0 0 0 0 1
-                         ];
-   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   for si=1:nStates-1
-      for ki=1:kvar
-         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-      end
-   end
-else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
-   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:nreseqn*nStates,:,eqninx) = [
-      0 0 0 0 0 1     0 0 0 0 0 0
-
-      0 0 0 0 0 0     0 0 0 0 0 1
-                         ];
-   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   else
-      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
-   end
-end
-
-
-%======== The sixth equation ===========
-eqninx = 6;
-nreseqn = 0;  % Number of linear restrictions for the equation for each state.
-if (indxEqnTv_m(eqninx, 2)<=2)
-   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
-      1  0  0  0  0  0     -1  0  0  0  0  0
-      0  1  0  0  0  0      0 -1  0  0  0  0
-      0  0  1  0  0  0      0  0 -1  0  0  0
-      0  0  0  1  0  0      0  0  0 -1  0  0
-      0  0  0  0  1  0      0  0  0  0 -1  0
-      0  0  0  0  0  1      0  0  0  0  0 -1
-                         ];
-   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   for si=1:nStates-1
-      for ki=1:kvar
-         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-      end
-   end
-else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
-   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   else
-      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
-   end
-end
-
-
-
-
-
-%===== Lagged restrictions in foreign (Granger causing) block
-%nfbres = lags*(nvar-nfvar);  % number of block restrictions in each foreign equation
-%bfor = zeros(nfbres,k);  % each foreign equation
-%cnt=0;
-%for ki = 1:lags
-%   for kj=1:nvar-nfvar
-%      cnt=cnt+1;
-%      bfor(cnt,nvar*(ki-1)+nfvar+kj) = 1;
-%   end
-%end
-%%
-%if cnt~=nfbres
-%   error('Check lagged restrictions in foreign equations!')
-%end
-%%
-%for kj=1:nfvar
-%   Ri(1:nfbres,:,kj) = bfor;
-%end
-
-
-%===== Lagged restrictions in home (affected) block
-%
-%~~~~~ selected domestic equations
-%dlrindx = nfvar+1; %[nfvar+1 nfvar+2];  % index for relevant home equations
-%rfvindx = []; %[6];  %[1 2 3 5];  % index for restricted foreign variables (e.g., Poil, M2, FFR, P).
-%%nf2hvar = nfvar-length(rfvindx);  % number of free parameters -- foreign variables entering the home sector
-%nhbres = lags*length(rfvindx);  % number of block restrictions in each home equation
-%bhom = zeros(nhbres,k);  % each home equation
-%cnt=0;
-%for ki = 1:lags
-%   for kj=1:length(rfvindx)
-%      cnt=cnt+1;
-%      bhom(cnt,nvar*(ki-1)+rfvindx(kj)) = 1;
-%   end
-%end
-%%
-%if cnt~=nhbres
-%   error('Check lagged restrictions in domestic equations!')
-%end
-%%
-%for kj=dlrindx
-%   Ri(1:nhbres,:,kj) = bhom;
-%end
-
-
-
-for ki=1:nvar   %  initializing loop for each equation
-   Ui{ki} = null(Qi(:,:,ki));
-   Vi{ki} = null(Ri(:,:,ki));
-   n0(ki) = size(Ui{ki},2);
-   np(ki) = size(Vi{ki},2);
-end
+function [Ui,Vi,n0,np] = ftd_2s_caseall_upperchol6v(lags,nvar,nStates,indxEqnTv_m,nexo)
+% Case 2&3: Policy a0j and a+j have only time-varying structural variances -- Case 2.
+%           All policy and nonpolicy a0j's and the corresponding constant terms are completely time-varying and only the scale
+%             of each variable in d+j,1** (excluding the constant term) is time-varying -- Case 3.
+%
+% Variables: Pcom, M2, FFR, y, P, U.  Equations: information, policy, money demand, y, P, U.
+% Exporting orthonormal matrices for the deterministic linear restrictions
+%     (equation by equation) with time-varying A0 and D+** equations.
+% See Model II.3 on pp.71k-71r in TVBVAR NOTES (and Waggoner and Zha's Gibbs sampling paper and TVBVAR NOTES p.58).
+%
+% lags: Maximum length of lag.
+% nvar:  Number of endogeous variables.
+% nStates:  Number of states.
+% indxEqnTv_m: nvar-by-2. Stores equation characteristics.
+%                   1st column: labels of equations [1:nvar]'.
+%                   2nd column: labels of time-varying features with
+%                        1: indxConst -- all coefficients are constant,
+%                        2: indxStv -- only shocks are time-varying,
+%                        3: indxTva0pv -- a0 are freely time-varying and each variable i for d+ is time-varying only by the scale lambda_i(s_t).
+%                        4: indxTva0ps -- a0 are freely time-varying and only the scale for the whole of d+ is time-varying.
+%                        5: indxTv -- time-varying for all coeffficients (a0 and a+) where the lag length for a+ may be shorter.
+% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant.
+%          So far this function is written to handle one exogenous variable, which is a constant term.
+%-----------------
+% Ui: nvar-by-1 cell.  In each cell, nvar*nStates-by-qi*si orthonormal basis for the null of the ith
+%           equation contemporaneous restriction matrix where qi is the number of free parameters
+%           within the state and si is the number of free states.
+%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
+%           of total original parameters and bi is a vector of free parameters. When no
+%           restrictions are imposed, we have Ui = I.  There must be at least one free
+%           parameter left for the ith equation in the order of [a_i for 1st state, ..., a_i for last state].
+% Vi: nvar-by-1 cell.  In each cell, k*nStates-by-ri*si orthonormal basis for the null of the ith
+%           equation lagged restriction matrix where k is a total of exogenous variables and
+%           ri is the number of free parameters within the state and si is the number of free states.
+%           With this transformation, we have fi = Vi*gi or Vi'*fi = gi where fi is a vector of total original
+%           parameters and gi is a vector of free parameters.  The ith equation is in the order of [nvar variables
+%           for 1st lag and 1st state, ..., nvar variables for last lag and 1st state, const for 1st state, nvar
+%           variables for 1st lag and 2nd state, nvar variables for last lag and 2nd state, const for 2nd state, and so on].
+% n0: nvar-by-1, whose ith element represents the number of free A0 parameters in ith equation in *all states*.
+% np: nvar-by-1, whose ith element represents the number of free D+ parameters in ith equation in *all states*.
+%
+% Tao Zha, February 2003
+
+
+
+Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
+Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
+n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation in all states.
+np = zeros(nvar,1); % ith element represents the number of free D+ parameters in ith equation in all states.
+
+if (nargin==3)
+   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
+end
+
+
+n = nvar*nStates;
+kvar=lags*nvar+nexo;  % Maximum number of lagged and exogenous variables in each equation under each state.
+k = kvar*nStates;  % Maximum number of lagged and exogenous variables in each equation in all states.
+
+Qi = zeros(n,n,nvar);   % 3rd dim: nvar contemporaneous equations.
+Ri = zeros(k,k,nvar);    % 1st and 2nd dims: lagged and exogenous equations.
+   % Row corresponds to equation with nvar variables for state 1, ..., nvar variables for state nState.
+   %        0 means no restriction.
+   %        1 and -1 or any other number means the linear combination of the corresponding parameters is restricted to 0.
+   %        1 (only 1) means that the corresponding parameter is restricted to 0.
+
+%nfvar = 6;   % number of foreign (Granger causing) variables
+%nhvar = nvar-nfvar;  % number of home (affected) variables.
+
+
+%-------------------------------------------------------------
+%  Beginning the manual input of the restrictions one quation at a time for A0_s.
+%-------------------------------------------------------------
+%
+
+%======== The first equation ===========
+eqninx = 1;
+nreseqn = 5;  % Number of linear restrictions for A0(:,eqninx) for each state.
+if (indxEqnTv_m(eqninx, 2)<=2)
+   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
+      1  0  0  0  0  0     -1  0  0  0  0  0
+      0  1  0  0  0  0      0 -1  0  0  0  0
+      0  0  1  0  0  0      0  0 -1  0  0  0
+      0  0  0  1  0  0      0  0  0 -1  0  0
+      0  0  0  0  1  0      0  0  0  0 -1  0
+      0  0  0  0  0  1      0  0  0  0  0 -1
+
+      0 0 0 0 0 0     0 1 0 0 0 0
+      0 0 0 0 0 0     0 0 1 0 0 0
+      0 0 0 0 0 0     0 0 0 1 0 0
+      0 0 0 0 0 0     0 0 0 0 1 0
+      0 0 0 0 0 0     0 0 0 0 0 1
+                         ];
+   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   for si=1:nStates-1
+      for ki=1:kvar
+         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+      end
+   end
+else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
+   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:nreseqn*nStates,:,eqninx) = [
+      0 1 0 0 0 0     0 0 0 0 0 0
+      0 0 1 0 0 0     0 0 0 0 0 0
+      0 0 0 1 0 0     0 0 0 0 0 0
+      0 0 0 0 1 0     0 0 0 0 0 0
+      0 0 0 0 0 1     0 0 0 0 0 0
+
+      0 0 0 0 0 0     0 1 0 0 0 0
+      0 0 0 0 0 0     0 0 1 0 0 0
+      0 0 0 0 0 0     0 0 0 1 0 0
+      0 0 0 0 0 0     0 0 0 0 1 0
+      0 0 0 0 0 0     0 0 0 0 0 1
+                         ];
+
+   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   else
+      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
+   end
+end
+
+
+
+%======== The second equation ===========
+eqninx = 2;
+nreseqn = 4;  % Number of linear restrictions for A0(:,eqninx) for each state.
+if (indxEqnTv_m(eqninx, 2)<=2)
+   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
+      1  0  0  0  0  0     -1  0  0  0  0  0
+      0  1  0  0  0  0      0 -1  0  0  0  0
+      0  0  1  0  0  0      0  0 -1  0  0  0
+      0  0  0  1  0  0      0  0  0 -1  0  0
+      0  0  0  0  1  0      0  0  0  0 -1  0
+      0  0  0  0  0  1      0  0  0  0  0 -1
+
+      0 0 0 0 0 0     0 0 1 0 0 0
+      0 0 0 0 0 0     0 0 0 1 0 0
+      0 0 0 0 0 0     0 0 0 0 1 0
+      0 0 0 0 0 0     0 0 0 0 0 1
+                         ];
+   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   for si=1:nStates-1
+      for ki=1:kvar
+         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+      end
+   end
+else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
+   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:nreseqn*nStates,:,eqninx) = [
+      0 0 1 0 0 0     0 0 0 0 0 0
+      0 0 0 1 0 0     0 0 0 0 0 0
+      0 0 0 0 1 0     0 0 0 0 0 0
+      0 0 0 0 0 1     0 0 0 0 0 0
+
+      0 0 0 0 0 0     0 0 1 0 0 0
+      0 0 0 0 0 0     0 0 0 1 0 0
+      0 0 0 0 0 0     0 0 0 0 1 0
+      0 0 0 0 0 0     0 0 0 0 0 1
+                         ];
+
+   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   else
+      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
+   end
+end
+
+
+%======== The third equation ===========
+eqninx = 3;
+nreseqn = 3;  % Number of linear restrictions for A0(:,eqninx) for each state.
+if (indxEqnTv_m(eqninx, 2)<=2)
+   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
+      1  0  0  0  0  0     -1  0  0  0  0  0
+      0  1  0  0  0  0      0 -1  0  0  0  0
+      0  0  1  0  0  0      0  0 -1  0  0  0
+      0  0  0  1  0  0      0  0  0 -1  0  0
+      0  0  0  0  1  0      0  0  0  0 -1  0
+      0  0  0  0  0  1      0  0  0  0  0 -1
+
+      0 0 0 0 0 0     0 0 0 1 0 0
+      0 0 0 0 0 0     0 0 0 0 1 0
+      0 0 0 0 0 0     0 0 0 0 0 1
+                         ];
+   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   for si=1:nStates-1
+      for ki=1:kvar
+         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+      end
+   end
+else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
+   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:nreseqn*nStates,:,eqninx) = [
+      0 0 0 1 0 0     0 0 0 0 0 0
+      0 0 0 0 1 0     0 0 0 0 0 0
+      0 0 0 0 0 1     0 0 0 0 0 0
+
+      0 0 0 0 0 0     0 0 0 1 0 0
+      0 0 0 0 0 0     0 0 0 0 1 0
+      0 0 0 0 0 0     0 0 0 0 0 1
+                         ];
+
+   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   else
+      error('.../ftd_3s_case3a.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
+   end
+
+   %==== For freely time-varying A+ for only the first 6 lags.
+   %====       Lagged restrictions: zeros on all lags except the first 6 lags in the MS equation.
+   %  nlagsno0 = 6;   % Number of lags to be nonzero.
+   %  for si=1:nStates
+   %     for ki = 1:lags-nlagsno0
+   %        for kj=1:nvar
+   %           Ri(kvar*(si-1)+nlagsno0*nvar+nvar*(ki-1)+kj,kvar*(si-1)+nlagsno0*nvar+nvar*(ki-1)+kj,2) = 1;
+   %        end
+   %     end
+   %  end
+   %**** For constant D+_s except the first two lags and the constant term.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   %  for si=1:nStates-1
+   %     for ki=[2*nvar+1:kvar-1]
+   %        Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+   %     end
+   %  end
+end
+
+
+%======== The fourth equation ===========
+eqninx = 4;
+nreseqn = 2;  % Number of linear restrictions for the equation for each state.
+if (indxEqnTv_m(eqninx, 2)<=2)
+   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
+      1  0  0  0  0  0     -1  0  0  0  0  0
+      0  1  0  0  0  0      0 -1  0  0  0  0
+      0  0  1  0  0  0      0  0 -1  0  0  0
+      0  0  0  1  0  0      0  0  0 -1  0  0
+      0  0  0  0  1  0      0  0  0  0 -1  0
+      0  0  0  0  0  1      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 0 1
+                         ];
+   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   for si=1:nStates-1
+      for ki=1:kvar
+         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+      end
+   end
+else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
+   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:nreseqn*nStates,:,eqninx) = [
+      0 0 0 0 1 0     0 0 0 0 0 0
+      0 0 0 0 0 1     0 0 0 0 0 0
+
+      0 0 0 0 0 0     0 0 0 0 1 0
+      0 0 0 0 0 0     0 0 0 0 0 1
+                         ];
+   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   else
+      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
+   end
+end
+
+
+%======== The fifth equation ===========
+eqninx = 5;
+nreseqn = 1;  % Number of linear restrictions for the equation for each state.
+if (indxEqnTv_m(eqninx, 2)<=2)
+   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
+      1  0  0  0  0  0     -1  0  0  0  0  0
+      0  1  0  0  0  0      0 -1  0  0  0  0
+      0  0  1  0  0  0      0  0 -1  0  0  0
+      0  0  0  1  0  0      0  0  0 -1  0  0
+      0  0  0  0  1  0      0  0  0  0 -1  0
+      0  0  0  0  0  1      0  0  0  0  0 -1
+
+      0 0 0 0 0 0     0 0 0 0 0 1
+                         ];
+   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   for si=1:nStates-1
+      for ki=1:kvar
+         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+      end
+   end
+else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
+   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:nreseqn*nStates,:,eqninx) = [
+      0 0 0 0 0 1     0 0 0 0 0 0
+
+      0 0 0 0 0 0     0 0 0 0 0 1
+                         ];
+   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   else
+      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
+   end
+end
+
+
+%======== The sixth equation ===========
+eqninx = 6;
+nreseqn = 0;  % Number of linear restrictions for the equation for each state.
+if (indxEqnTv_m(eqninx, 2)<=2)
+   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
+      1  0  0  0  0  0     -1  0  0  0  0  0
+      0  1  0  0  0  0      0 -1  0  0  0  0
+      0  0  1  0  0  0      0  0 -1  0  0  0
+      0  0  0  1  0  0      0  0  0 -1  0  0
+      0  0  0  0  1  0      0  0  0  0 -1  0
+      0  0  0  0  0  1      0  0  0  0  0 -1
+                         ];
+   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   for si=1:nStates-1
+      for ki=1:kvar
+         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+      end
+   end
+else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
+   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   else
+      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
+   end
+end
+
+
+
+
+
+%===== Lagged restrictions in foreign (Granger causing) block
+%nfbres = lags*(nvar-nfvar);  % number of block restrictions in each foreign equation
+%bfor = zeros(nfbres,k);  % each foreign equation
+%cnt=0;
+%for ki = 1:lags
+%   for kj=1:nvar-nfvar
+%      cnt=cnt+1;
+%      bfor(cnt,nvar*(ki-1)+nfvar+kj) = 1;
+%   end
+%end
+%%
+%if cnt~=nfbres
+%   error('Check lagged restrictions in foreign equations!')
+%end
+%%
+%for kj=1:nfvar
+%   Ri(1:nfbres,:,kj) = bfor;
+%end
+
+
+%===== Lagged restrictions in home (affected) block
+%
+%~~~~~ selected domestic equations
+%dlrindx = nfvar+1; %[nfvar+1 nfvar+2];  % index for relevant home equations
+%rfvindx = []; %[6];  %[1 2 3 5];  % index for restricted foreign variables (e.g., Poil, M2, FFR, P).
+%%nf2hvar = nfvar-length(rfvindx);  % number of free parameters -- foreign variables entering the home sector
+%nhbres = lags*length(rfvindx);  % number of block restrictions in each home equation
+%bhom = zeros(nhbres,k);  % each home equation
+%cnt=0;
+%for ki = 1:lags
+%   for kj=1:length(rfvindx)
+%      cnt=cnt+1;
+%      bhom(cnt,nvar*(ki-1)+rfvindx(kj)) = 1;
+%   end
+%end
+%%
+%if cnt~=nhbres
+%   error('Check lagged restrictions in domestic equations!')
+%end
+%%
+%for kj=dlrindx
+%   Ri(1:nhbres,:,kj) = bhom;
+%end
+
+
+
+for ki=1:nvar   %  initializing loop for each equation
+   Ui{ki} = null(Qi(:,:,ki));
+   Vi{ki} = null(Ri(:,:,ki));
+   n0(ki) = size(Ui{ki},2);
+   np(ki) = size(Vi{ki},2);
+end
diff --git a/tests/ms-sbvar/archive-files/ftd_2s_caseall_upperchol7v.m b/tests/ms-sbvar/archive-files/ftd_2s_caseall_upperchol7v.m
index 6c27034d6c861c8ef3862543ecee20d98227b016..de818ab9051c8f35e4e54a92619eced157cefb1f 100644
--- a/tests/ms-sbvar/archive-files/ftd_2s_caseall_upperchol7v.m
+++ b/tests/ms-sbvar/archive-files/ftd_2s_caseall_upperchol7v.m
@@ -1,525 +1,525 @@
-function [Ui,Vi,n0,np] = ftd_2s_caseall_upperchol7v(lags,nvar,nStates,indxEqnTv_m,nexo)
-% Case 2&3: Policy a0j and a+j have only time-varying structural variances -- Case 2.
-%           All policy and nonpolicy a0j's and the corresponding constant terms are completely time-varying and only the scale
-%             of each variable in d+j,1** (excluding the constant term) is time-varying -- Case 3.
-%
-% Variables: Pcom, M2, FFR, y, P, U.  Equations: information, policy, money demand, y, P, U.
-% Exporting orthonormal matrices for the deterministic linear restrictions
-%     (equation by equation) with time-varying A0 and D+** equations.
-% See Model II.3 on pp.71k-71r in TVBVAR NOTES (and Waggoner and Zha's Gibbs sampling paper and TVBVAR NOTES p.58).
-%
-% lags: Maximum length of lag.
-% nvar:  Number of endogeous variables.
-% nStates:  Number of states.
-% indxEqnTv_m: nvar-by-2. Stores equation characteristics.
-%                   1st column: labels of equations [1:nvar]'.
-%                   2nd column: labels of time-varying features with
-%                        1: indxConst -- all coefficients are constant,
-%                        2: indxStv -- only shocks are time-varying,
-%                        3: indxTva0pv -- a0 are freely time-varying and each variable i for d+ is time-varying only by the scale lambda_i(s_t).
-%                        4: indxTva0ps -- a0 are freely time-varying and only the scale for the whole of d+ is time-varying.
-%                        5: indxTv -- time-varying for all coeffficients (a0 and a+) where the lag length for a+ may be shorter.
-% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant.
-%          So far this function is written to handle one exogenous variable, which is a constant term.
-%-----------------
-% Ui: nvar-by-1 cell.  In each cell, nvar*nStates-by-qi*si orthonormal basis for the null of the ith
-%           equation contemporaneous restriction matrix where qi is the number of free parameters
-%           within the state and si is the number of free states.
-%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
-%           of total original parameters and bi is a vector of free parameters. When no
-%           restrictions are imposed, we have Ui = I.  There must be at least one free
-%           parameter left for the ith equation in the order of [a_i for 1st state, ..., a_i for last state].
-% Vi: nvar-by-1 cell.  In each cell, k*nStates-by-ri*si orthonormal basis for the null of the ith
-%           equation lagged restriction matrix where k is a total of exogenous variables and
-%           ri is the number of free parameters within the state and si is the number of free states.
-%           With this transformation, we have fi = Vi*gi or Vi'*fi = gi where fi is a vector of total original
-%           parameters and gi is a vector of free parameters.  The ith equation is in the order of [nvar variables
-%           for 1st lag and 1st state, ..., nvar variables for last lag and 1st state, const for 1st state, nvar
-%           variables for 1st lag and 2nd state, nvar variables for last lag and 2nd state, const for 2nd state, and so on].
-% n0: nvar-by-1, whose ith element represents the number of free A0 parameters in ith equation in *all states*.
-% np: nvar-by-1, whose ith element represents the number of free D+ parameters in ith equation in *all states*.
-%
-% Tao Zha, February 2003
-
-
-
-Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
-Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
-n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation in all states.
-np = zeros(nvar,1); % ith element represents the number of free D+ parameters in ith equation in all states.
-
-if (nargin==3)
-   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
-end
-
-
-n = nvar*nStates;
-kvar=lags*nvar+nexo;  % Maximum number of lagged and exogenous variables in each equation under each state.
-k = kvar*nStates;  % Maximum number of lagged and exogenous variables in each equation in all states.
-
-Qi = zeros(n,n,nvar);   % 3rd dim: nvar contemporaneous equations.
-Ri = zeros(k,k,nvar);    % 1st and 2nd dims: lagged and exogenous equations.
-   % Row corresponds to equation with nvar variables for state 1, ..., nvar variables for state nState.
-   %        0 means no restriction.
-   %        1 and -1 or any other number means the linear combination of the corresponding parameters is restricted to 0.
-   %        1 (only 1) means that the corresponding parameter is restricted to 0.
-
-%nfvar = 6;   % number of foreign (Granger causing) variables
-%nhvar = nvar-nfvar;  % number of home (affected) variables.
-
-
-%-------------------------------------------------------------
-%  Beginning the manual input of the restrictions one quation at a time for A0_s.
-%-------------------------------------------------------------
-%
-
-%======== The first equation ===========
-eqninx = 1;
-nreseqn = 6;  % Number of linear restrictions for A0(:,eqninx) for each state.
-if (indxEqnTv_m(eqninx, 2)<=2)
-   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
-      1  0  0  0  0  0  0     -1  0  0  0  0  0  0
-      0  1  0  0  0  0  0      0 -1  0  0  0  0  0
-      0  0  1  0  0  0  0      0  0 -1  0  0  0  0
-      0  0  0  1  0  0  0      0  0  0 -1  0  0  0
-      0  0  0  0  1  0  0      0  0  0  0 -1  0  0
-      0  0  0  0  0  1  0      0  0  0  0  0 -1  0
-      0  0  0  0  0  0  1      0  0  0  0  0  0 -1
-
-      0 0 0 0 0 0 0       0 1 0 0 0 0 0
-      0 0 0 0 0 0 0       0 0 1 0 0 0 0
-      0 0 0 0 0 0 0       0 0 0 1 0 0 0
-      0 0 0 0 0 0 0       0 0 0 0 1 0 0
-      0 0 0 0 0 0 0       0 0 0 0 0 1 0
-      0 0 0 0 0 0 0       0 0 0 0 0 0 1
-                         ];
-   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   for si=1:nStates-1
-      for ki=1:kvar
-         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-      end
-   end
-else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
-   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:nreseqn*nStates,:,eqninx) = [
-      0 1 0 0 0 0 0    0 0 0 0 0 0 0
-      0 0 1 0 0 0 0    0 0 0 0 0 0 0
-      0 0 0 1 0 0 0    0 0 0 0 0 0 0
-      0 0 0 0 1 0 0    0 0 0 0 0 0 0
-      0 0 0 0 0 1 0    0 0 0 0 0 0 0
-      0 0 0 0 0 0 1    0 0 0 0 0 0 0
-
-      0 0 0 0 0 0 0       0 1 0 0 0 0 0
-      0 0 0 0 0 0 0       0 0 1 0 0 0 0
-      0 0 0 0 0 0 0       0 0 0 1 0 0 0
-      0 0 0 0 0 0 0       0 0 0 0 1 0 0
-      0 0 0 0 0 0 0       0 0 0 0 0 1 0
-      0 0 0 0 0 0 0       0 0 0 0 0 0 1
-                         ];
-
-   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   else
-      error('.../ftd_2s_caseall_*.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
-   end
-end
-
-
-%======== The second equation ===========
-eqninx = 2;
-nreseqn = 5;  % Number of linear restrictions for A0(:,eqninx) for each state.
-if (indxEqnTv_m(eqninx, 2)<=2)
-   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
-      1  0  0  0  0  0  0     -1  0  0  0  0  0  0
-      0  1  0  0  0  0  0      0 -1  0  0  0  0  0
-      0  0  1  0  0  0  0      0  0 -1  0  0  0  0
-      0  0  0  1  0  0  0      0  0  0 -1  0  0  0
-      0  0  0  0  1  0  0      0  0  0  0 -1  0  0
-      0  0  0  0  0  1  0      0  0  0  0  0 -1  0
-      0  0  0  0  0  0  1      0  0  0  0  0  0 -1
-
-      0 0 0 0 0 0 0       0 0 1 0 0 0 0
-      0 0 0 0 0 0 0       0 0 0 1 0 0 0
-      0 0 0 0 0 0 0       0 0 0 0 1 0 0
-      0 0 0 0 0 0 0       0 0 0 0 0 1 0
-      0 0 0 0 0 0 0       0 0 0 0 0 0 1
-                         ];
-   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   for si=1:nStates-1
-      for ki=1:kvar
-         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-      end
-   end
-else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
-   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:nreseqn*nStates,:,eqninx) = [
-       0 0 1 0 0 0 0        0 0 0 0 0 0 0
-       0 0 0 1 0 0 0        0 0 0 0 0 0 0
-       0 0 0 0 1 0 0        0 0 0 0 0 0 0
-       0 0 0 0 0 1 0        0 0 0 0 0 0 0
-       0 0 0 0 0 0 1        0 0 0 0 0 0 0
-
-      0 0 0 0 0 0 0       0 0 1 0 0 0 0
-      0 0 0 0 0 0 0       0 0 0 1 0 0 0
-      0 0 0 0 0 0 0       0 0 0 0 1 0 0
-      0 0 0 0 0 0 0       0 0 0 0 0 1 0
-      0 0 0 0 0 0 0       0 0 0 0 0 0 1
-                         ];
-
-   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   else
-      error('.../ftd_2s_caseall_*.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
-   end
-end
-
-
-%======== The third equation ===========
-eqninx = 3;
-nreseqn = 4;  % Number of linear restrictions for A0(:,eqninx) for each state.
-if (indxEqnTv_m(eqninx, 2)<=2)
-   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
-      1  0  0  0  0  0  0     -1  0  0  0  0  0  0
-      0  1  0  0  0  0  0      0 -1  0  0  0  0  0
-      0  0  1  0  0  0  0      0  0 -1  0  0  0  0
-      0  0  0  1  0  0  0      0  0  0 -1  0  0  0
-      0  0  0  0  1  0  0      0  0  0  0 -1  0  0
-      0  0  0  0  0  1  0      0  0  0  0  0 -1  0
-      0  0  0  0  0  0  1      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 0 0 0 1 0 0
-      0 0 0 0 0 0 0       0 0 0 0 0 1 0
-      0 0 0 0 0 0 0       0 0 0 0 0 0 1
-                         ];
-   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   for si=1:nStates-1
-      for ki=1:kvar
-         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-      end
-   end
-else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
-   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:nreseqn*nStates,:,eqninx) = [
-      0 0 0 1 0 0 0       0 0 0 0 0 0 0
-      0 0 0 0 1 0 0       0 0 0 0 0 0 0
-      0 0 0 0 0 1 0       0 0 0 0 0 0 0
-      0 0 0 0 0 0 1       0 0 0 0 0 0 0
-
-      0 0 0 0 0 0 0       0 0 0 1 0 0 0
-      0 0 0 0 0 0 0       0 0 0 0 1 0 0
-      0 0 0 0 0 0 0       0 0 0 0 0 1 0
-      0 0 0 0 0 0 0       0 0 0 0 0 0 1
-                         ];
-
-   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   else
-      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
-   end
-end
-
-
-
-%======== The fourth equation ===========
-eqninx = 4;
-nreseqn = 3;  % Number of linear restrictions for A0(:,eqninx) for each state.
-if (indxEqnTv_m(eqninx, 2)<=2)
-   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
-      1  0  0  0  0  0  0     -1  0  0  0  0  0  0
-      0  1  0  0  0  0  0      0 -1  0  0  0  0  0
-      0  0  1  0  0  0  0      0  0 -1  0  0  0  0
-      0  0  0  1  0  0  0      0  0  0 -1  0  0  0
-      0  0  0  0  1  0  0      0  0  0  0 -1  0  0
-      0  0  0  0  0  1  0      0  0  0  0  0 -1  0
-      0  0  0  0  0  0  1      0  0  0  0  0  0 -1
-
-      0 0 0 0 0 0 0       0 0 0 0 1 0 0
-      0 0 0 0 0 0 0       0 0 0 0 0 1 0
-      0 0 0 0 0 0 0       0 0 0 0 0 0 1
-                         ];
-   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   for si=1:nStates-1
-      for ki=1:kvar
-         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-      end
-   end
-else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
-   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:nreseqn*nStates,:,eqninx) = [
-      0 0 0 0 1 0 0       0 0 0 0 0 0 0
-      0 0 0 0 0 1 0       0 0 0 0 0 0 0
-      0 0 0 0 0 0 1       0 0 0 0 0 0 0
-
-      0 0 0 0 0 0 0       0 0 0 0 1 0 0
-      0 0 0 0 0 0 0       0 0 0 0 0 1 0
-      0 0 0 0 0 0 0       0 0 0 0 0 0 1
-                         ];
-
-   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   else
-      error('.../ftd_3s_case3a.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
-   end
-
-   %==== For freely time-varying A+ for only the first 6 lags.
-   %====       Lagged restrictions: zeros on all lags except the first 6 lags in the MS equation.
-   %  nlagsno0 = 6;   % Number of lags to be nonzero.
-   %  for si=1:nStates
-   %     for ki = 1:lags-nlagsno0
-   %        for kj=1:nvar
-   %           Ri(kvar*(si-1)+nlagsno0*nvar+nvar*(ki-1)+kj,kvar*(si-1)+nlagsno0*nvar+nvar*(ki-1)+kj,2) = 1;
-   %        end
-   %     end
-   %  end
-   %**** For constant D+_s except the first two lags and the constant term.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   %  for si=1:nStates-1
-   %     for ki=[2*nvar+1:kvar-1]
-   %        Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-   %     end
-   %  end
-end
-
-
-%======== The fifth equation ===========
-eqninx = 5;
-nreseqn = 2;  % Number of linear restrictions for the equation for each state.
-if (indxEqnTv_m(eqninx, 2)<=2)
-   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
-      1  0  0  0  0  0  0     -1  0  0  0  0  0  0
-      0  1  0  0  0  0  0      0 -1  0  0  0  0  0
-      0  0  1  0  0  0  0      0  0 -1  0  0  0  0
-      0  0  0  1  0  0  0      0  0  0 -1  0  0  0
-      0  0  0  0  1  0  0      0  0  0  0 -1  0  0
-      0  0  0  0  0  1  0      0  0  0  0  0 -1  0
-      0  0  0  0  0  0  1      0  0  0  0  0  0 -1
-
-      0 0 0 0 0 0 0       0 0 0 0 0 1 0
-      0 0 0 0 0 0 0       0 0 0 0 0 0 1
-                         ];
-   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   for si=1:nStates-1
-      for ki=1:kvar
-         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-      end
-   end
-else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
-   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:nreseqn*nStates,:,eqninx) = [
-      0 0 0 0 0 1 0        0 0 0 0 0 0 0
-      0 0 0 0 0 0 1        0 0 0 0 0 0 0
-
-      0 0 0 0 0 0 0       0 0 0 0 0 1 0
-      0 0 0 0 0 0 0       0 0 0 0 0 0 1
-                         ];
-   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   else
-      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
-   end
-end
-
-
-%======== The sixth equation ===========
-eqninx = 6;
-nreseqn = 1;  % Number of linear restrictions for the equation for each state.
-if (indxEqnTv_m(eqninx, 2)<=2)
-   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
-      1  0  0  0  0  0  0     -1  0  0  0  0  0  0
-      0  1  0  0  0  0  0      0 -1  0  0  0  0  0
-      0  0  1  0  0  0  0      0  0 -1  0  0  0  0
-      0  0  0  1  0  0  0      0  0  0 -1  0  0  0
-      0  0  0  0  1  0  0      0  0  0  0 -1  0  0
-      0  0  0  0  0  1  0      0  0  0  0  0 -1  0
-      0  0  0  0  0  0  1      0  0  0  0  0  0 -1
-
-      0 0 0 0 0 0 0             0 0 0 0 0 0 1
-                         ];
-   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   for si=1:nStates-1
-      for ki=1:kvar
-         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-      end
-   end
-else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
-   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:nreseqn*nStates,:,eqninx) = [
-      0 0 0 0 0 0 1             0 0 0 0 0 0 0
-
-      0 0 0 0 0 0 0             0 0 0 0 0 0 1
-                         ];
-   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   else
-      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
-   end
-end
-
-
-%======== The seventh equation ===========
-eqninx = 7;
-nreseqn = 0;  % Number of linear restrictions for the equation for each state.
-if (indxEqnTv_m(eqninx, 2)<=2)
-   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
-   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
-      1  0  0  0  0  0  0     -1  0  0  0  0  0  0
-      0  1  0  0  0  0  0      0 -1  0  0  0  0  0
-      0  0  1  0  0  0  0      0  0 -1  0  0  0  0
-      0  0  0  1  0  0  0      0  0  0 -1  0  0  0
-      0  0  0  0  1  0  0      0  0  0  0 -1  0  0
-      0  0  0  0  0  1  0      0  0  0  0  0 -1  0
-      0  0  0  0  0  0  1      0  0  0  0  0  0 -1
-                         ];
-   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   for si=1:nStates-1
-      for ki=1:kvar
-         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-      end
-   end
-else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
-   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
-   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
-      for si=1:nStates-1
-         for ki=1:kvar
-            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
-         end
-      end
-   else
-      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
-   end
-end
-
-
-
-
-
-%===== Lagged restrictions in foreign (Granger causing) block
-%nfbres = lags*(nvar-nfvar);  % number of block restrictions in each foreign equation
-%bfor = zeros(nfbres,k);  % each foreign equation
-%cnt=0;
-%for ki = 1:lags
-%   for kj=1:nvar-nfvar
-%      cnt=cnt+1;
-%      bfor(cnt,nvar*(ki-1)+nfvar+kj) = 1;
-%   end
-%end
-%%
-%if cnt~=nfbres
-%   error('Check lagged restrictions in foreign equations!')
-%end
-%%
-%for kj=1:nfvar
-%   Ri(1:nfbres,:,kj) = bfor;
-%end
-
-
-%===== Lagged restrictions in home (affected) block
-%
-%~~~~~ selected domestic equations
-%dlrindx = nfvar+1; %[nfvar+1 nfvar+2];  % index for relevant home equations
-%rfvindx = []; %[6];  %[1 2 3 5];  % index for restricted foreign variables (e.g., Poil, M2, FFR, P).
-%%nf2hvar = nfvar-length(rfvindx);  % number of free parameters -- foreign variables entering the home sector
-%nhbres = lags*length(rfvindx);  % number of block restrictions in each home equation
-%bhom = zeros(nhbres,k);  % each home equation
-%cnt=0;
-%for ki = 1:lags
-%   for kj=1:length(rfvindx)
-%      cnt=cnt+1;
-%      bhom(cnt,nvar*(ki-1)+rfvindx(kj)) = 1;
-%   end
-%end
-%%
-%if cnt~=nhbres
-%   error('Check lagged restrictions in domestic equations!')
-%end
-%%
-%for kj=dlrindx
-%   Ri(1:nhbres,:,kj) = bhom;
-%end
-
-
-
-for ki=1:nvar   %  initializing loop for each equation
-   Ui{ki} = null(Qi(:,:,ki));
-   Vi{ki} = null(Ri(:,:,ki));
-   n0(ki) = size(Ui{ki},2);
-   np(ki) = size(Vi{ki},2);
-end
+function [Ui,Vi,n0,np] = ftd_2s_caseall_upperchol7v(lags,nvar,nStates,indxEqnTv_m,nexo)
+% Case 2&3: Policy a0j and a+j have only time-varying structural variances -- Case 2.
+%           All policy and nonpolicy a0j's and the corresponding constant terms are completely time-varying and only the scale
+%             of each variable in d+j,1** (excluding the constant term) is time-varying -- Case 3.
+%
+% Variables: Pcom, M2, FFR, y, P, U.  Equations: information, policy, money demand, y, P, U.
+% Exporting orthonormal matrices for the deterministic linear restrictions
+%     (equation by equation) with time-varying A0 and D+** equations.
+% See Model II.3 on pp.71k-71r in TVBVAR NOTES (and Waggoner and Zha's Gibbs sampling paper and TVBVAR NOTES p.58).
+%
+% lags: Maximum length of lag.
+% nvar:  Number of endogeous variables.
+% nStates:  Number of states.
+% indxEqnTv_m: nvar-by-2. Stores equation characteristics.
+%                   1st column: labels of equations [1:nvar]'.
+%                   2nd column: labels of time-varying features with
+%                        1: indxConst -- all coefficients are constant,
+%                        2: indxStv -- only shocks are time-varying,
+%                        3: indxTva0pv -- a0 are freely time-varying and each variable i for d+ is time-varying only by the scale lambda_i(s_t).
+%                        4: indxTva0ps -- a0 are freely time-varying and only the scale for the whole of d+ is time-varying.
+%                        5: indxTv -- time-varying for all coeffficients (a0 and a+) where the lag length for a+ may be shorter.
+% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant.
+%          So far this function is written to handle one exogenous variable, which is a constant term.
+%-----------------
+% Ui: nvar-by-1 cell.  In each cell, nvar*nStates-by-qi*si orthonormal basis for the null of the ith
+%           equation contemporaneous restriction matrix where qi is the number of free parameters
+%           within the state and si is the number of free states.
+%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
+%           of total original parameters and bi is a vector of free parameters. When no
+%           restrictions are imposed, we have Ui = I.  There must be at least one free
+%           parameter left for the ith equation in the order of [a_i for 1st state, ..., a_i for last state].
+% Vi: nvar-by-1 cell.  In each cell, k*nStates-by-ri*si orthonormal basis for the null of the ith
+%           equation lagged restriction matrix where k is a total of exogenous variables and
+%           ri is the number of free parameters within the state and si is the number of free states.
+%           With this transformation, we have fi = Vi*gi or Vi'*fi = gi where fi is a vector of total original
+%           parameters and gi is a vector of free parameters.  The ith equation is in the order of [nvar variables
+%           for 1st lag and 1st state, ..., nvar variables for last lag and 1st state, const for 1st state, nvar
+%           variables for 1st lag and 2nd state, nvar variables for last lag and 2nd state, const for 2nd state, and so on].
+% n0: nvar-by-1, whose ith element represents the number of free A0 parameters in ith equation in *all states*.
+% np: nvar-by-1, whose ith element represents the number of free D+ parameters in ith equation in *all states*.
+%
+% Tao Zha, February 2003
+
+
+
+Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
+Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
+n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation in all states.
+np = zeros(nvar,1); % ith element represents the number of free D+ parameters in ith equation in all states.
+
+if (nargin==3)
+   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
+end
+
+
+n = nvar*nStates;
+kvar=lags*nvar+nexo;  % Maximum number of lagged and exogenous variables in each equation under each state.
+k = kvar*nStates;  % Maximum number of lagged and exogenous variables in each equation in all states.
+
+Qi = zeros(n,n,nvar);   % 3rd dim: nvar contemporaneous equations.
+Ri = zeros(k,k,nvar);    % 1st and 2nd dims: lagged and exogenous equations.
+   % Row corresponds to equation with nvar variables for state 1, ..., nvar variables for state nState.
+   %        0 means no restriction.
+   %        1 and -1 or any other number means the linear combination of the corresponding parameters is restricted to 0.
+   %        1 (only 1) means that the corresponding parameter is restricted to 0.
+
+%nfvar = 6;   % number of foreign (Granger causing) variables
+%nhvar = nvar-nfvar;  % number of home (affected) variables.
+
+
+%-------------------------------------------------------------
+%  Beginning the manual input of the restrictions one quation at a time for A0_s.
+%-------------------------------------------------------------
+%
+
+%======== The first equation ===========
+eqninx = 1;
+nreseqn = 6;  % Number of linear restrictions for A0(:,eqninx) for each state.
+if (indxEqnTv_m(eqninx, 2)<=2)
+   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
+      1  0  0  0  0  0  0     -1  0  0  0  0  0  0
+      0  1  0  0  0  0  0      0 -1  0  0  0  0  0
+      0  0  1  0  0  0  0      0  0 -1  0  0  0  0
+      0  0  0  1  0  0  0      0  0  0 -1  0  0  0
+      0  0  0  0  1  0  0      0  0  0  0 -1  0  0
+      0  0  0  0  0  1  0      0  0  0  0  0 -1  0
+      0  0  0  0  0  0  1      0  0  0  0  0  0 -1
+
+      0 0 0 0 0 0 0       0 1 0 0 0 0 0
+      0 0 0 0 0 0 0       0 0 1 0 0 0 0
+      0 0 0 0 0 0 0       0 0 0 1 0 0 0
+      0 0 0 0 0 0 0       0 0 0 0 1 0 0
+      0 0 0 0 0 0 0       0 0 0 0 0 1 0
+      0 0 0 0 0 0 0       0 0 0 0 0 0 1
+                         ];
+   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   for si=1:nStates-1
+      for ki=1:kvar
+         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+      end
+   end
+else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
+   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:nreseqn*nStates,:,eqninx) = [
+      0 1 0 0 0 0 0    0 0 0 0 0 0 0
+      0 0 1 0 0 0 0    0 0 0 0 0 0 0
+      0 0 0 1 0 0 0    0 0 0 0 0 0 0
+      0 0 0 0 1 0 0    0 0 0 0 0 0 0
+      0 0 0 0 0 1 0    0 0 0 0 0 0 0
+      0 0 0 0 0 0 1    0 0 0 0 0 0 0
+
+      0 0 0 0 0 0 0       0 1 0 0 0 0 0
+      0 0 0 0 0 0 0       0 0 1 0 0 0 0
+      0 0 0 0 0 0 0       0 0 0 1 0 0 0
+      0 0 0 0 0 0 0       0 0 0 0 1 0 0
+      0 0 0 0 0 0 0       0 0 0 0 0 1 0
+      0 0 0 0 0 0 0       0 0 0 0 0 0 1
+                         ];
+
+   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   else
+      error('.../ftd_2s_caseall_*.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
+   end
+end
+
+
+%======== The second equation ===========
+eqninx = 2;
+nreseqn = 5;  % Number of linear restrictions for A0(:,eqninx) for each state.
+if (indxEqnTv_m(eqninx, 2)<=2)
+   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
+      1  0  0  0  0  0  0     -1  0  0  0  0  0  0
+      0  1  0  0  0  0  0      0 -1  0  0  0  0  0
+      0  0  1  0  0  0  0      0  0 -1  0  0  0  0
+      0  0  0  1  0  0  0      0  0  0 -1  0  0  0
+      0  0  0  0  1  0  0      0  0  0  0 -1  0  0
+      0  0  0  0  0  1  0      0  0  0  0  0 -1  0
+      0  0  0  0  0  0  1      0  0  0  0  0  0 -1
+
+      0 0 0 0 0 0 0       0 0 1 0 0 0 0
+      0 0 0 0 0 0 0       0 0 0 1 0 0 0
+      0 0 0 0 0 0 0       0 0 0 0 1 0 0
+      0 0 0 0 0 0 0       0 0 0 0 0 1 0
+      0 0 0 0 0 0 0       0 0 0 0 0 0 1
+                         ];
+   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   for si=1:nStates-1
+      for ki=1:kvar
+         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+      end
+   end
+else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
+   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:nreseqn*nStates,:,eqninx) = [
+       0 0 1 0 0 0 0        0 0 0 0 0 0 0
+       0 0 0 1 0 0 0        0 0 0 0 0 0 0
+       0 0 0 0 1 0 0        0 0 0 0 0 0 0
+       0 0 0 0 0 1 0        0 0 0 0 0 0 0
+       0 0 0 0 0 0 1        0 0 0 0 0 0 0
+
+      0 0 0 0 0 0 0       0 0 1 0 0 0 0
+      0 0 0 0 0 0 0       0 0 0 1 0 0 0
+      0 0 0 0 0 0 0       0 0 0 0 1 0 0
+      0 0 0 0 0 0 0       0 0 0 0 0 1 0
+      0 0 0 0 0 0 0       0 0 0 0 0 0 1
+                         ];
+
+   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   else
+      error('.../ftd_2s_caseall_*.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
+   end
+end
+
+
+%======== The third equation ===========
+eqninx = 3;
+nreseqn = 4;  % Number of linear restrictions for A0(:,eqninx) for each state.
+if (indxEqnTv_m(eqninx, 2)<=2)
+   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
+      1  0  0  0  0  0  0     -1  0  0  0  0  0  0
+      0  1  0  0  0  0  0      0 -1  0  0  0  0  0
+      0  0  1  0  0  0  0      0  0 -1  0  0  0  0
+      0  0  0  1  0  0  0      0  0  0 -1  0  0  0
+      0  0  0  0  1  0  0      0  0  0  0 -1  0  0
+      0  0  0  0  0  1  0      0  0  0  0  0 -1  0
+      0  0  0  0  0  0  1      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 0 0 0 1 0 0
+      0 0 0 0 0 0 0       0 0 0 0 0 1 0
+      0 0 0 0 0 0 0       0 0 0 0 0 0 1
+                         ];
+   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   for si=1:nStates-1
+      for ki=1:kvar
+         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+      end
+   end
+else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
+   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:nreseqn*nStates,:,eqninx) = [
+      0 0 0 1 0 0 0       0 0 0 0 0 0 0
+      0 0 0 0 1 0 0       0 0 0 0 0 0 0
+      0 0 0 0 0 1 0       0 0 0 0 0 0 0
+      0 0 0 0 0 0 1       0 0 0 0 0 0 0
+
+      0 0 0 0 0 0 0       0 0 0 1 0 0 0
+      0 0 0 0 0 0 0       0 0 0 0 1 0 0
+      0 0 0 0 0 0 0       0 0 0 0 0 1 0
+      0 0 0 0 0 0 0       0 0 0 0 0 0 1
+                         ];
+
+   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   else
+      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
+   end
+end
+
+
+
+%======== The fourth equation ===========
+eqninx = 4;
+nreseqn = 3;  % Number of linear restrictions for A0(:,eqninx) for each state.
+if (indxEqnTv_m(eqninx, 2)<=2)
+   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
+      1  0  0  0  0  0  0     -1  0  0  0  0  0  0
+      0  1  0  0  0  0  0      0 -1  0  0  0  0  0
+      0  0  1  0  0  0  0      0  0 -1  0  0  0  0
+      0  0  0  1  0  0  0      0  0  0 -1  0  0  0
+      0  0  0  0  1  0  0      0  0  0  0 -1  0  0
+      0  0  0  0  0  1  0      0  0  0  0  0 -1  0
+      0  0  0  0  0  0  1      0  0  0  0  0  0 -1
+
+      0 0 0 0 0 0 0       0 0 0 0 1 0 0
+      0 0 0 0 0 0 0       0 0 0 0 0 1 0
+      0 0 0 0 0 0 0       0 0 0 0 0 0 1
+                         ];
+   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   for si=1:nStates-1
+      for ki=1:kvar
+         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+      end
+   end
+else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
+   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:nreseqn*nStates,:,eqninx) = [
+      0 0 0 0 1 0 0       0 0 0 0 0 0 0
+      0 0 0 0 0 1 0       0 0 0 0 0 0 0
+      0 0 0 0 0 0 1       0 0 0 0 0 0 0
+
+      0 0 0 0 0 0 0       0 0 0 0 1 0 0
+      0 0 0 0 0 0 0       0 0 0 0 0 1 0
+      0 0 0 0 0 0 0       0 0 0 0 0 0 1
+                         ];
+
+   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   else
+      error('.../ftd_3s_case3a.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
+   end
+
+   %==== For freely time-varying A+ for only the first 6 lags.
+   %====       Lagged restrictions: zeros on all lags except the first 6 lags in the MS equation.
+   %  nlagsno0 = 6;   % Number of lags to be nonzero.
+   %  for si=1:nStates
+   %     for ki = 1:lags-nlagsno0
+   %        for kj=1:nvar
+   %           Ri(kvar*(si-1)+nlagsno0*nvar+nvar*(ki-1)+kj,kvar*(si-1)+nlagsno0*nvar+nvar*(ki-1)+kj,2) = 1;
+   %        end
+   %     end
+   %  end
+   %**** For constant D+_s except the first two lags and the constant term.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   %  for si=1:nStates-1
+   %     for ki=[2*nvar+1:kvar-1]
+   %        Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+   %     end
+   %  end
+end
+
+
+%======== The fifth equation ===========
+eqninx = 5;
+nreseqn = 2;  % Number of linear restrictions for the equation for each state.
+if (indxEqnTv_m(eqninx, 2)<=2)
+   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
+      1  0  0  0  0  0  0     -1  0  0  0  0  0  0
+      0  1  0  0  0  0  0      0 -1  0  0  0  0  0
+      0  0  1  0  0  0  0      0  0 -1  0  0  0  0
+      0  0  0  1  0  0  0      0  0  0 -1  0  0  0
+      0  0  0  0  1  0  0      0  0  0  0 -1  0  0
+      0  0  0  0  0  1  0      0  0  0  0  0 -1  0
+      0  0  0  0  0  0  1      0  0  0  0  0  0 -1
+
+      0 0 0 0 0 0 0       0 0 0 0 0 1 0
+      0 0 0 0 0 0 0       0 0 0 0 0 0 1
+                         ];
+   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   for si=1:nStates-1
+      for ki=1:kvar
+         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+      end
+   end
+else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
+   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:nreseqn*nStates,:,eqninx) = [
+      0 0 0 0 0 1 0        0 0 0 0 0 0 0
+      0 0 0 0 0 0 1        0 0 0 0 0 0 0
+
+      0 0 0 0 0 0 0       0 0 0 0 0 1 0
+      0 0 0 0 0 0 0       0 0 0 0 0 0 1
+                         ];
+   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   else
+      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
+   end
+end
+
+
+%======== The sixth equation ===========
+eqninx = 6;
+nreseqn = 1;  % Number of linear restrictions for the equation for each state.
+if (indxEqnTv_m(eqninx, 2)<=2)
+   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
+      1  0  0  0  0  0  0     -1  0  0  0  0  0  0
+      0  1  0  0  0  0  0      0 -1  0  0  0  0  0
+      0  0  1  0  0  0  0      0  0 -1  0  0  0  0
+      0  0  0  1  0  0  0      0  0  0 -1  0  0  0
+      0  0  0  0  1  0  0      0  0  0  0 -1  0  0
+      0  0  0  0  0  1  0      0  0  0  0  0 -1  0
+      0  0  0  0  0  0  1      0  0  0  0  0  0 -1
+
+      0 0 0 0 0 0 0             0 0 0 0 0 0 1
+                         ];
+   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   for si=1:nStates-1
+      for ki=1:kvar
+         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+      end
+   end
+else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
+   %**** For time-varying A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:nreseqn*nStates,:,eqninx) = [
+      0 0 0 0 0 0 1             0 0 0 0 0 0 0
+
+      0 0 0 0 0 0 0             0 0 0 0 0 0 1
+                         ];
+   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   else
+      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
+   end
+end
+
+
+%======== The seventh equation ===========
+eqninx = 7;
+nreseqn = 0;  % Number of linear restrictions for the equation for each state.
+if (indxEqnTv_m(eqninx, 2)<=2)
+   %**** For constant A0_s.    In the order of [a0j(1),...,a0j(nStates)] for the 2nd dim of Qi.
+   Qi(1:(nStates-1)*nvar+nreseqn,:,eqninx) = [
+      1  0  0  0  0  0  0     -1  0  0  0  0  0  0
+      0  1  0  0  0  0  0      0 -1  0  0  0  0  0
+      0  0  1  0  0  0  0      0  0 -1  0  0  0  0
+      0  0  0  1  0  0  0      0  0  0 -1  0  0  0
+      0  0  0  0  1  0  0      0  0  0  0 -1  0  0
+      0  0  0  0  0  1  0      0  0  0  0  0 -1  0
+      0  0  0  0  0  0  1      0  0  0  0  0  0 -1
+                         ];
+   %**** For constant D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   for si=1:nStates-1
+      for ki=1:kvar
+         Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+      end
+   end
+else    % Time-varying equations at least for A0_s.  For D+_s, constant-parameter equations in general.
+   %**** For D+_s.  In the order of [aj+(1),...,aj+(nStates)] for the 2nd dim of Ri.
+   if (indxEqnTv_m(eqninx, 2)==3)    % For constant D+** except the constant term.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar-1   % -1: no restrictions on the constant term, which is freely time-varying.
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   elseif (indxEqnTv_m(eqninx, 2)==4)    % For constant D+**.  In the order of [dj**(1),...,dj**(nStates)] for the 2nd dim of Ri.
+      for si=1:nStates-1
+         for ki=1:kvar
+            Ri(kvar*(si-1)+ki,[kvar*(si-1)+ki si*kvar+ki],eqninx) = [1 -1];
+         end
+      end
+   else
+      error('.../ftd_2s_caseall_simszha5v.m:  Have not got time to deal with the simple case indxEqnTv_m(eqninx, 2)=5.')
+   end
+end
+
+
+
+
+
+%===== Lagged restrictions in foreign (Granger causing) block
+%nfbres = lags*(nvar-nfvar);  % number of block restrictions in each foreign equation
+%bfor = zeros(nfbres,k);  % each foreign equation
+%cnt=0;
+%for ki = 1:lags
+%   for kj=1:nvar-nfvar
+%      cnt=cnt+1;
+%      bfor(cnt,nvar*(ki-1)+nfvar+kj) = 1;
+%   end
+%end
+%%
+%if cnt~=nfbres
+%   error('Check lagged restrictions in foreign equations!')
+%end
+%%
+%for kj=1:nfvar
+%   Ri(1:nfbres,:,kj) = bfor;
+%end
+
+
+%===== Lagged restrictions in home (affected) block
+%
+%~~~~~ selected domestic equations
+%dlrindx = nfvar+1; %[nfvar+1 nfvar+2];  % index for relevant home equations
+%rfvindx = []; %[6];  %[1 2 3 5];  % index for restricted foreign variables (e.g., Poil, M2, FFR, P).
+%%nf2hvar = nfvar-length(rfvindx);  % number of free parameters -- foreign variables entering the home sector
+%nhbres = lags*length(rfvindx);  % number of block restrictions in each home equation
+%bhom = zeros(nhbres,k);  % each home equation
+%cnt=0;
+%for ki = 1:lags
+%   for kj=1:length(rfvindx)
+%      cnt=cnt+1;
+%      bhom(cnt,nvar*(ki-1)+rfvindx(kj)) = 1;
+%   end
+%end
+%%
+%if cnt~=nhbres
+%   error('Check lagged restrictions in domestic equations!')
+%end
+%%
+%for kj=dlrindx
+%   Ri(1:nhbres,:,kj) = bhom;
+%end
+
+
+
+for ki=1:nvar   %  initializing loop for each equation
+   Ui{ki} = null(Qi(:,:,ki));
+   Vi{ki} = null(Ri(:,:,ki));
+   n0(ki) = size(Ui{ki},2);
+   np(ki) = size(Vi{ki},2);
+end
diff --git a/tests/ms-sbvar/archive-files/ftd_RSvensson_4v.m b/tests/ms-sbvar/archive-files/ftd_RSvensson_4v.m
index a93ff82b771f461ed2cf00e2d4f3c98707299641..2b24a786ab780f51242114d45a7cf0c4a02a4fcf 100644
--- a/tests/ms-sbvar/archive-files/ftd_RSvensson_4v.m
+++ b/tests/ms-sbvar/archive-files/ftd_RSvensson_4v.m
@@ -1,188 +1,188 @@
-function [Ui,Vi,n0,np,ixmC0Pres] = ftd_reac_function_4v(lags,nvar,nexo,indxC0Pres)
-%  vlist = [ff+ch fh dpgdp ffr)
-%
-%    Exporting orthonormal matrices for the deterministic linear restrictions (equation by equation)
-%    See Waggoner and Zha's Gibbs sampling paper.
-%
-%   HERE FIRTS 3 EQUATIONS ARE AR2 AND THE LAST EQUATION IS AN UNRESTRICTED
-%   REACTION FUNCTION 2 lags
-%
-% q_m:  quarter or month
-% lags: the maximum length of lag
-% nvar:  number of endogeous variables
-% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant
-% indxC0Pres: index for cross-A0-A+ restrictions.  if 1: cross-A0-and-A+ restrictions; 0: idfile is all we have
-%                Example for indxOres==1: restrictions of the form P(t) = P(t-1).
-%                These restrictions have to be manually and carefully keyed in.
-%-----------------
-% Ui: nvar-by-1 cell.  In each cell, nvar-by-qi orthonormal basis for the null of the ith
-%           equation contemporaneous restriction matrix where qi is the number of free parameters.
-%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
-%           of total original parameters and bi is a vector of free parameters. When no
-%           restrictions are imposed, we have Ui = I.  There must be at least one free
-%           parameter left for the ith equation.
-% Vi: nvar-by-1 cell.  In each cell, k-by-ri orthonormal basis for the null of the ith
-%           equation lagged restriction matrix where k is a total of exogenous variables and
-%           ri is the number of free parameters. With this transformation, we have fi = Vi*gi
-%           or Vi'*fi = gi where fi is a vector of total original parameters and gi is a
-%           vector of free parameters. There must be at least one free parameter left for
-%           the ith equation.
-% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation
-% np: nvar-by-1, ith element represents the number of free A+ parameters in ith equation
-% ixmC0Pres:  neq_cres-by-1 cell.  Effective only if indxC0Pres=1, otherwise equals NaN.
-%             neq_cres is the number of equations in which cross-A0-A+ restrictions occur.
-%             In the jth cell representing equation, we have 4 columns:
-%               1st: the jth column (equation) of A+ or A0: f_j or a_j
-%               2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-%               3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-%               4th: the number s such that f_j(i) = s * a_j(h) holds.
-%
-% Tao Zha, May 2000
-% BN
-
-nvar=4;
-lags=4;
-nexo=1;
-
-Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
-Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
-n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation
-np = zeros(nvar,1); % ith element represents the number of free A+ parameters in ith equation
-
-if (nargin==2)
-   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
-elseif (nargin==3)
-   indxC0Pres = 0;  % default is no cross-A0-and-A+ restrictions.
-end
-
-k = lags*nvar+nexo;  % maximum number of lagged and exogenous variables in each equation
-
-Qi = zeros(nvar,nvar,nvar);   % for nvar contemporaneous equations
-Ri = zeros(k,k,nvar);    % for nvar lagged and exogenous equations
-  % Row corresponds to equation. 0 means no restriction.
-  %                              1 means exclusion restriction such that the corresponding parameter is restricted to 0.
-
-%nfvar = 6;   % number of foreign (Granger causing) variables
-%nhvar = nvar-nfvar;  % number of home (affected) variables.
-
-
-%-------------------------------------------------------------
-%  Beginning the manual input of the restrictions one quation at a time
-%-------------------------------------------------------------
-%
-%======== The first equation ===========
-Qi(1:3,:,1) = [
-    0 1 0 0
-    0 0 1 0
-    0 0 0 1
-        ];
-
-%======== The second equation ===========
-Qi(1:2,:,2) = [
-    0 0 1 0
-    0 0 0 1
-        ];
-
-%======== The third equation =========== NOTE THAT WE FORBID A
-%CONTEMPORANEOUS IMPACT OF OUTPUTON PRICES TO AVOID A CONSTRAINT THAT
-%INVOLVE A0 and Aplus
-Qi(1:3,:,3) = [
-    1 0 0 0
-    0 1 0 0
-    0 0 0 1
-        ];
-
-%======== The fourth equation ===========
-
-
-% Restrictions on the A+ in order to focus strictly on the reaction fucntion
-
-% indicates free parameterers X i
-%	Ap = [
-%      X  X    X  X
-%	   X  X    X  X
-%     -a1 -b1  X  X
-%      a1 b1   0  X  (1st lag)
-%      X  X    X  X
-%	   X  X    X  X
-%     -a2 -b2  X  X
-%      b2  b2  0  X  (2nd lag)
-%      X   0   X  X
-%	   X  X    X  X
-%     -a3 -b3  X  X
-%      a3  a3  0  X  (3rd lag)
-%      X  X    X  X
-%	   X  X    X  X
-%     -a4 -b4  X  X
-%      a4  b4  0  X  (4th lag)
-%      X  X    X  X  (constant terms)
-%			  ];
-
-k=nvar*lags+nexo;
-Ri = zeros(k,k,nvar);
-% constraints on IS curve /conso+corporate investment
-for nv=1:2
-for ll=1:lags
-Ri(ll,3+lags*(ll-1),nv)=1;
-Ri(ll,4+lags*(ll-1),nv)=1;
-end
-end
-
-% constraints on IS curve /conso+corporate investment only on the long run
-% impact
-% for nv=1:2
-% for ll=1:lags
-% Ri(1,3+lags*(ll-1),nv)=1;
-% Ri(1,4+lags*(ll-1),nv)=1;
-% end
-% end
-
-
-% constraints on Ph curve / inflation does not react to interest rates
-for ll=1:lags
-Ri(ll,4+lags*(ll-1),3)=1;
-end
-
-
-for n=1:nvar   %  initializing loop for each equation
-   Ui{n} = null(Qi(:,:,n));
-   Vi{n} = null(Ri(:,:,n));
-   n0(n) = size(Ui{n},2);
-   np(n) = size(Vi{n},2);
-end
-
-
-
-%(2)-------------------------------------------------------------
-%  Cross-A0-and-A+ rerestrictions one quation at a time
-%    i.e., the first, second, ..., kjth, ..., equation
-%(2)-------------------------------------------------------------
-%
-if indxC0Pres
-   neq_cres = 3;   % the number of equations in which cross-A0-A+ restrictions occur.
-   ixmC0Pres = cell(neq_cres,1);  % in each cell representing equation, we have 4 columns:
-           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
-           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
-   %** 1st equation
-   ixmC0Pres{1} = [1 2 2 1
-                   1 7 1 1];
-   %** 2nd equation
-   ixmC0Pres{2} = [2 2 2 2];
-   %** 3rd equation
-   ixmC0Pres{3} = [3 7 1 1
-                   3 2 2 1];
-
-
-%         % 4 columns.
-%   ncres = 5;  % manually key in the number of cross-A0-A+ restrictions
-
-%           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
-%           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-%           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-%           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
-else
-   ixmC0Pres = NaN;
-end
-
+function [Ui,Vi,n0,np,ixmC0Pres] = ftd_reac_function_4v(lags,nvar,nexo,indxC0Pres)
+%  vlist = [ff+ch fh dpgdp ffr)
+%
+%    Exporting orthonormal matrices for the deterministic linear restrictions (equation by equation)
+%    See Waggoner and Zha's Gibbs sampling paper.
+%
+%   HERE FIRTS 3 EQUATIONS ARE AR2 AND THE LAST EQUATION IS AN UNRESTRICTED
+%   REACTION FUNCTION 2 lags
+%
+% q_m:  quarter or month
+% lags: the maximum length of lag
+% nvar:  number of endogeous variables
+% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant
+% indxC0Pres: index for cross-A0-A+ restrictions.  if 1: cross-A0-and-A+ restrictions; 0: idfile is all we have
+%                Example for indxOres==1: restrictions of the form P(t) = P(t-1).
+%                These restrictions have to be manually and carefully keyed in.
+%-----------------
+% Ui: nvar-by-1 cell.  In each cell, nvar-by-qi orthonormal basis for the null of the ith
+%           equation contemporaneous restriction matrix where qi is the number of free parameters.
+%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
+%           of total original parameters and bi is a vector of free parameters. When no
+%           restrictions are imposed, we have Ui = I.  There must be at least one free
+%           parameter left for the ith equation.
+% Vi: nvar-by-1 cell.  In each cell, k-by-ri orthonormal basis for the null of the ith
+%           equation lagged restriction matrix where k is a total of exogenous variables and
+%           ri is the number of free parameters. With this transformation, we have fi = Vi*gi
+%           or Vi'*fi = gi where fi is a vector of total original parameters and gi is a
+%           vector of free parameters. There must be at least one free parameter left for
+%           the ith equation.
+% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation
+% np: nvar-by-1, ith element represents the number of free A+ parameters in ith equation
+% ixmC0Pres:  neq_cres-by-1 cell.  Effective only if indxC0Pres=1, otherwise equals NaN.
+%             neq_cres is the number of equations in which cross-A0-A+ restrictions occur.
+%             In the jth cell representing equation, we have 4 columns:
+%               1st: the jth column (equation) of A+ or A0: f_j or a_j
+%               2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+%               3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+%               4th: the number s such that f_j(i) = s * a_j(h) holds.
+%
+% Tao Zha, May 2000
+% BN
+
+nvar=4;
+lags=4;
+nexo=1;
+
+Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
+Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
+n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation
+np = zeros(nvar,1); % ith element represents the number of free A+ parameters in ith equation
+
+if (nargin==2)
+   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
+elseif (nargin==3)
+   indxC0Pres = 0;  % default is no cross-A0-and-A+ restrictions.
+end
+
+k = lags*nvar+nexo;  % maximum number of lagged and exogenous variables in each equation
+
+Qi = zeros(nvar,nvar,nvar);   % for nvar contemporaneous equations
+Ri = zeros(k,k,nvar);    % for nvar lagged and exogenous equations
+  % Row corresponds to equation. 0 means no restriction.
+  %                              1 means exclusion restriction such that the corresponding parameter is restricted to 0.
+
+%nfvar = 6;   % number of foreign (Granger causing) variables
+%nhvar = nvar-nfvar;  % number of home (affected) variables.
+
+
+%-------------------------------------------------------------
+%  Beginning the manual input of the restrictions one quation at a time
+%-------------------------------------------------------------
+%
+%======== The first equation ===========
+Qi(1:3,:,1) = [
+    0 1 0 0
+    0 0 1 0
+    0 0 0 1
+        ];
+
+%======== The second equation ===========
+Qi(1:2,:,2) = [
+    0 0 1 0
+    0 0 0 1
+        ];
+
+%======== The third equation =========== NOTE THAT WE FORBID A
+%CONTEMPORANEOUS IMPACT OF OUTPUTON PRICES TO AVOID A CONSTRAINT THAT
+%INVOLVE A0 and Aplus
+Qi(1:3,:,3) = [
+    1 0 0 0
+    0 1 0 0
+    0 0 0 1
+        ];
+
+%======== The fourth equation ===========
+
+
+% Restrictions on the A+ in order to focus strictly on the reaction fucntion
+
+% indicates free parameterers X i
+%	Ap = [
+%      X  X    X  X
+%	   X  X    X  X
+%     -a1 -b1  X  X
+%      a1 b1   0  X  (1st lag)
+%      X  X    X  X
+%	   X  X    X  X
+%     -a2 -b2  X  X
+%      b2  b2  0  X  (2nd lag)
+%      X   0   X  X
+%	   X  X    X  X
+%     -a3 -b3  X  X
+%      a3  a3  0  X  (3rd lag)
+%      X  X    X  X
+%	   X  X    X  X
+%     -a4 -b4  X  X
+%      a4  b4  0  X  (4th lag)
+%      X  X    X  X  (constant terms)
+%			  ];
+
+k=nvar*lags+nexo;
+Ri = zeros(k,k,nvar);
+% constraints on IS curve /conso+corporate investment
+for nv=1:2
+for ll=1:lags
+Ri(ll,3+lags*(ll-1),nv)=1;
+Ri(ll,4+lags*(ll-1),nv)=1;
+end
+end
+
+% constraints on IS curve /conso+corporate investment only on the long run
+% impact
+% for nv=1:2
+% for ll=1:lags
+% Ri(1,3+lags*(ll-1),nv)=1;
+% Ri(1,4+lags*(ll-1),nv)=1;
+% end
+% end
+
+
+% constraints on Ph curve / inflation does not react to interest rates
+for ll=1:lags
+Ri(ll,4+lags*(ll-1),3)=1;
+end
+
+
+for n=1:nvar   %  initializing loop for each equation
+   Ui{n} = null(Qi(:,:,n));
+   Vi{n} = null(Ri(:,:,n));
+   n0(n) = size(Ui{n},2);
+   np(n) = size(Vi{n},2);
+end
+
+
+
+%(2)-------------------------------------------------------------
+%  Cross-A0-and-A+ rerestrictions one quation at a time
+%    i.e., the first, second, ..., kjth, ..., equation
+%(2)-------------------------------------------------------------
+%
+if indxC0Pres
+   neq_cres = 3;   % the number of equations in which cross-A0-A+ restrictions occur.
+   ixmC0Pres = cell(neq_cres,1);  % in each cell representing equation, we have 4 columns:
+           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
+           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
+   %** 1st equation
+   ixmC0Pres{1} = [1 2 2 1
+                   1 7 1 1];
+   %** 2nd equation
+   ixmC0Pres{2} = [2 2 2 2];
+   %** 3rd equation
+   ixmC0Pres{3} = [3 7 1 1
+                   3 2 2 1];
+
+
+%         % 4 columns.
+%   ncres = 5;  % manually key in the number of cross-A0-A+ restrictions
+
+%           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
+%           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+%           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+%           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
+else
+   ixmC0Pres = NaN;
+end
+
diff --git a/tests/ms-sbvar/archive-files/ftd_cholesky.m b/tests/ms-sbvar/archive-files/ftd_cholesky.m
index 74524c47013db1864b92dfe6fd976ea96cc66729..42126015abf5d6a6f8e2bee19450f05aeb53f3de 100644
--- a/tests/ms-sbvar/archive-files/ftd_cholesky.m
+++ b/tests/ms-sbvar/archive-files/ftd_cholesky.m
@@ -1,251 +1,251 @@
-function [Ui,Vi,n0,np,ixmC0Pres] = ftd_cholesky(lags,nvar,nexo,indxC0Pres)
-%vlist = [1:4];    % regarding "xdd", % 1: p; 2: id; 3: ik; 4: y.
-%For restricted VARs in the form: y_t'*A0 = x_t'*Ap + e_t', where y_t is a vector of endogenous variables
-%      and x_t is a vector of lagged endogenous variables and the constant term (last term).
-%      Note that the columns of A0 and Ap correspnd to equations.
-%
-%    Exporting orthonormal matrices for the deterministic linear restrictions (equation by equation)
-%    See Waggoner and Zha's Gibbs sampling paper.
-%
-% q_m:  quarter or month
-% lags: the maximum length of lag
-% nvar:  number of endogeous variables
-% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant
-% indxC0Pres: index for cross-A0-A+ restrictions.  if 1: cross-A0-and-A+ restrictions; 0: idfile is all we have
-%                Example for indxOres==1: restrictions of the form P(t) = P(t-1).
-%                These restrictions have to be manually and carefully keyed in.
-%-----------------
-% Ui: nvar-by-1 cell.  In each cell, nvar-by-qi orthonormal basis for the null of the ith
-%           equation contemporaneous restriction matrix where qi is the number of free parameters.
-%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
-%           of total original parameters and bi is a vector of free parameters. When no
-%           restrictions are imposed, we have Ui = I.  There must be at least one free
-%           parameter left for the ith equation.
-% Vi: nvar-by-1 cell.  In each cell, k-by-ri orthonormal basis for the null of the ith
-%           equation lagged restriction matrix where k is a total of exogenous variables and
-%           ri is the number of free parameters. With this transformation, we have fi = Vi*gi
-%           or Vi'*fi = gi where fi is a vector of total original parameters and gi is a
-%           vector of free parameters. There must be at least one free parameter left for
-%           the ith equation.
-% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation
-% np: nvar-by-1, ith element represents the number of free A+ parameters in ith equation
-% ixmC0Pres:  neq_cres-by-1 cell.  Effective only if indxC0Pres=1, otherwise equals NaN.
-%             neq_cres is the number of equations in which cross-A0-A+ restrictions occur.
-%             In the jth cell representing equation, we have 4 columns:
-%               1st: the jth column (equation) of A+ or A0: f_j or a_j
-%               2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-%               3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-%               4th: the number s such that f_j(i) = s * a_j(h) holds.
-%
-% Tao Zha, May 2000
-
-
-
-Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
-Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
-n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation
-np = zeros(nvar,1); % ith element represents the number of free A+ parameters in ith equation
-
-if (nargin==2)
-   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
-elseif (nargin==3)
-   indxC0Pres = 0;  % default is no cross-A0-and-A+ restrictions.
-end
-
-k = lags*nvar+nexo;  % maximum number of lagged and exogenous variables in each equation
-
-Qi = zeros(nvar,nvar,nvar);   % for nvar contemporaneous equations
-Ri = zeros(k,k,nvar);    % for nvar lagged and exogenous equations
-  % Row corresponds to equation. 0 means no restriction.
-  %                              1 means exclusion restriction such that the corresponding parameter is restricted to 0.
-
-%nfvar = 6;   % number of foreign (Granger causing) variables
-%nhvar = nvar-nfvar;  % number of home (affected) variables.
-
-
-%-------------------------------------------------------------
-%  Beginning the manual input of the restrictions one quation at a time
-%-------------------------------------------------------------
-%The restrictions considered here are in the following form where X means unrestricted:
-%  A0 = [
-%      X  0  X  X
-%		 0  X  X  X
-%		 0  0  X  X
-%		 0  0  0  X
-%			];
-%	Ap = [
-%      X  0  X  X
-%		 0  X  X  X
-%      0  0  X  X
-%      0  0  X  X  (1st lag)
-%      X  0  X  X
-%		 0  X  X  X
-%      0  0  X  X
-%      0  0  X  X  (2nd lag)
-%      X  0  X  X
-%		 0  X  X  X
-%      0  0  X  X
-%      0  0  X  X  (3rd lag)
-%      X  0  X  X
-%		 0  X  X  X
-%      0  0  X  X
-%      0  0  X  X  (4th lag)
-%      0  X  0  0  (constant terms)
-%			];
-
-if (0)
-	%------------------------ Lower triangular A0 ------------------------------
-	%======== The first equation ===========
-
-
-	%======== The second equation ===========
-	Qi(1:1,:,2) = [
-	   1 0 0 0
-	        ];
-
-	%======== The third equation ===========
-	Qi(1:2,:,3) = [
-	   1 0 0 0
-	   0 1 0 0
-	        ];
-
-	%======== The fourth equation ===========
-	Qi(1:3,:,4) = [
-	   1 0 0 0
-	   0 1 0 0
-	   0 0 1 0
-	        ];
-else
-	%------------------------ Upper triangular A0 ------------------------------
-	%======== The first equation ===========
-	Qi(2:4,:,1) = [
-	   0 1 0 0
-	   0 0 1 0
-	   0 0 0 1
-	        ];
-
-	%======== The second equation ===========
-   Qi([1 3:4],:,2) = [
-      1 0 0 0
-      0 0 1 0
-	   0 0 0 1
-	        ];
-
-	%======== The third equation ===========
-	Qi(4:4,:,3) = [
-	   0 0 0 1
-	        ];
-
-	%======== The fourth equation ===========
-end
-
-
-%-------------------------- Lag restrictions. ------------------------------------------
-if (1)
-	%--- Lag restrictions.
-	indxeqn = 1;   %Which equation.
-	nrestrs = (nvar-1)*lags+1;  %Number of restrictions.
-	vars_restr = [2:nvar];  %Variables that are restricted:  id, ik, and y.
-   blags = zeros(nrestrs,k);  %k=nvar*lags+1
-	cnt = 0;
-	for ki = 1:lags
-	   for kj=vars_restr
-	      cnt = cnt+1;
-	      blags(cnt,nvar*(ki-1)+kj) = 1;
-	   end
-	end
-	%--- Keep constant zero.
-	cnt = cnt+1;
-	blags(cnt,end) = 1;  %Constant = 0.
-	if cnt~=nrestrs
-	   error('Check lagged restrictions in 1st equation!')
-	end
-	Ri(1:nrestrs,:,indxeqn) = blags;
-
-	%--- Lag restrictions.
-	indxeqn = 2;   %Which equation.
-   nrestrs = (nvar-1)*lags;  %Number of restrictions.
-   vars_restr = [1 3:nvar];  %Variables that are restricted:  id, ik, and y.
-   blags = zeros(nrestrs,k);  %k=nvar*lags+1
-   cnt = 0;
-   for ki = 1:lags
-      for kj=vars_restr
-         cnt = cnt+1;
-         blags(cnt,nvar*(ki-1)+kj) = 1;
-      end
-   end
-	Ri(1:nrestrs,:,indxeqn) = blags;
-
-	%--- Lag restrictions.
-	indxeqn = 3;   %Which equation.
-	nrestrs = 1;  %Number of restrictions.
-	blags = zeros(nrestrs,k);
-	cnt = 0;
-	%--- Keep constant zero.
-	cnt = cnt+1;
-	blags(cnt,end) = 1;  %Constant = 0.
-	if cnt~=nrestrs
-	   error('Check lagged restrictions in 1st equation!')
-	end
-	Ri(1:nrestrs,:,indxeqn) = blags;
-
-	%--- Lag restrictions.
-	indxeqn = 4;   %Which equation.
-	nrestrs = 1;  %Number of restrictions.
-	blags = zeros(nrestrs,k);
-	cnt = 0;
-	%--- Keep constant zero.
-	cnt = cnt+1;
-	blags(cnt,end) = 1;  %Constant = 0.
-	if cnt~=nrestrs
-	   error('Check lagged restrictions in 1st equation!')
-	end
-	Ri(1:nrestrs,:,indxeqn) = blags;
-end
-
-
-for n=1:nvar   %  initializing loop for each equation
-   Ui{n} = null(Qi(:,:,n));
-   Vi{n} = null(Ri(:,:,n));
-   n0(n) = size(Ui{n},2);
-   np(n) = size(Vi{n},2);
-end
-
-
-
-%(2)-------------------------------------------------------------
-%  Cross-A0-and-A+ rerestrictions one quation at a time
-%    i.e., the first, second, ..., kjth, ..., equation
-%  This type of restriction is used for the New-Keysian model studied by Leeper and Zha
-%    "Assessing Simple Policy Rules: A View from a Complete Macroeconomic Model" published
-%    by St. Louis Fed Review.
-%(2)-------------------------------------------------------------
-%
-if indxC0Pres
-   neq_cres = 3;   % the number of equations in which cross-A0-A+ restrictions occur.
-   ixmC0Pres = cell(neq_cres,1);  % in each cell representing equation, we have 4 columns:
-           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
-           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
-   %** 1st equation
-   ixmC0Pres{1} = [1 2 2 1
-                   1 7 1 1];
-   %** 2nd equation
-   ixmC0Pres{2} = [2 2 2 2];
-   %** 3rd equation
-   ixmC0Pres{3} = [3 7 1 1
-                   3 2 2 1];
-
-
-%         % 4 columns.
-%   ncres = 5;  % manually key in the number of cross-A0-A+ restrictions
-
-%           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
-%           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-%           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-%           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
-else
-   ixmC0Pres = NaN;
-end
-
+function [Ui,Vi,n0,np,ixmC0Pres] = ftd_cholesky(lags,nvar,nexo,indxC0Pres)
+%vlist = [1:4];    % regarding "xdd", % 1: p; 2: id; 3: ik; 4: y.
+%For restricted VARs in the form: y_t'*A0 = x_t'*Ap + e_t', where y_t is a vector of endogenous variables
+%      and x_t is a vector of lagged endogenous variables and the constant term (last term).
+%      Note that the columns of A0 and Ap correspnd to equations.
+%
+%    Exporting orthonormal matrices for the deterministic linear restrictions (equation by equation)
+%    See Waggoner and Zha's Gibbs sampling paper.
+%
+% q_m:  quarter or month
+% lags: the maximum length of lag
+% nvar:  number of endogeous variables
+% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant
+% indxC0Pres: index for cross-A0-A+ restrictions.  if 1: cross-A0-and-A+ restrictions; 0: idfile is all we have
+%                Example for indxOres==1: restrictions of the form P(t) = P(t-1).
+%                These restrictions have to be manually and carefully keyed in.
+%-----------------
+% Ui: nvar-by-1 cell.  In each cell, nvar-by-qi orthonormal basis for the null of the ith
+%           equation contemporaneous restriction matrix where qi is the number of free parameters.
+%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
+%           of total original parameters and bi is a vector of free parameters. When no
+%           restrictions are imposed, we have Ui = I.  There must be at least one free
+%           parameter left for the ith equation.
+% Vi: nvar-by-1 cell.  In each cell, k-by-ri orthonormal basis for the null of the ith
+%           equation lagged restriction matrix where k is a total of exogenous variables and
+%           ri is the number of free parameters. With this transformation, we have fi = Vi*gi
+%           or Vi'*fi = gi where fi is a vector of total original parameters and gi is a
+%           vector of free parameters. There must be at least one free parameter left for
+%           the ith equation.
+% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation
+% np: nvar-by-1, ith element represents the number of free A+ parameters in ith equation
+% ixmC0Pres:  neq_cres-by-1 cell.  Effective only if indxC0Pres=1, otherwise equals NaN.
+%             neq_cres is the number of equations in which cross-A0-A+ restrictions occur.
+%             In the jth cell representing equation, we have 4 columns:
+%               1st: the jth column (equation) of A+ or A0: f_j or a_j
+%               2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+%               3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+%               4th: the number s such that f_j(i) = s * a_j(h) holds.
+%
+% Tao Zha, May 2000
+
+
+
+Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
+Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
+n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation
+np = zeros(nvar,1); % ith element represents the number of free A+ parameters in ith equation
+
+if (nargin==2)
+   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
+elseif (nargin==3)
+   indxC0Pres = 0;  % default is no cross-A0-and-A+ restrictions.
+end
+
+k = lags*nvar+nexo;  % maximum number of lagged and exogenous variables in each equation
+
+Qi = zeros(nvar,nvar,nvar);   % for nvar contemporaneous equations
+Ri = zeros(k,k,nvar);    % for nvar lagged and exogenous equations
+  % Row corresponds to equation. 0 means no restriction.
+  %                              1 means exclusion restriction such that the corresponding parameter is restricted to 0.
+
+%nfvar = 6;   % number of foreign (Granger causing) variables
+%nhvar = nvar-nfvar;  % number of home (affected) variables.
+
+
+%-------------------------------------------------------------
+%  Beginning the manual input of the restrictions one quation at a time
+%-------------------------------------------------------------
+%The restrictions considered here are in the following form where X means unrestricted:
+%  A0 = [
+%      X  0  X  X
+%		 0  X  X  X
+%		 0  0  X  X
+%		 0  0  0  X
+%			];
+%	Ap = [
+%      X  0  X  X
+%		 0  X  X  X
+%      0  0  X  X
+%      0  0  X  X  (1st lag)
+%      X  0  X  X
+%		 0  X  X  X
+%      0  0  X  X
+%      0  0  X  X  (2nd lag)
+%      X  0  X  X
+%		 0  X  X  X
+%      0  0  X  X
+%      0  0  X  X  (3rd lag)
+%      X  0  X  X
+%		 0  X  X  X
+%      0  0  X  X
+%      0  0  X  X  (4th lag)
+%      0  X  0  0  (constant terms)
+%			];
+
+if (0)
+	%------------------------ Lower triangular A0 ------------------------------
+	%======== The first equation ===========
+
+
+	%======== The second equation ===========
+	Qi(1:1,:,2) = [
+	   1 0 0 0
+	        ];
+
+	%======== The third equation ===========
+	Qi(1:2,:,3) = [
+	   1 0 0 0
+	   0 1 0 0
+	        ];
+
+	%======== The fourth equation ===========
+	Qi(1:3,:,4) = [
+	   1 0 0 0
+	   0 1 0 0
+	   0 0 1 0
+	        ];
+else
+	%------------------------ Upper triangular A0 ------------------------------
+	%======== The first equation ===========
+	Qi(2:4,:,1) = [
+	   0 1 0 0
+	   0 0 1 0
+	   0 0 0 1
+	        ];
+
+	%======== The second equation ===========
+   Qi([1 3:4],:,2) = [
+      1 0 0 0
+      0 0 1 0
+	   0 0 0 1
+	        ];
+
+	%======== The third equation ===========
+	Qi(4:4,:,3) = [
+	   0 0 0 1
+	        ];
+
+	%======== The fourth equation ===========
+end
+
+
+%-------------------------- Lag restrictions. ------------------------------------------
+if (1)
+	%--- Lag restrictions.
+	indxeqn = 1;   %Which equation.
+	nrestrs = (nvar-1)*lags+1;  %Number of restrictions.
+	vars_restr = [2:nvar];  %Variables that are restricted:  id, ik, and y.
+   blags = zeros(nrestrs,k);  %k=nvar*lags+1
+	cnt = 0;
+	for ki = 1:lags
+	   for kj=vars_restr
+	      cnt = cnt+1;
+	      blags(cnt,nvar*(ki-1)+kj) = 1;
+	   end
+	end
+	%--- Keep constant zero.
+	cnt = cnt+1;
+	blags(cnt,end) = 1;  %Constant = 0.
+	if cnt~=nrestrs
+	   error('Check lagged restrictions in 1st equation!')
+	end
+	Ri(1:nrestrs,:,indxeqn) = blags;
+
+	%--- Lag restrictions.
+	indxeqn = 2;   %Which equation.
+   nrestrs = (nvar-1)*lags;  %Number of restrictions.
+   vars_restr = [1 3:nvar];  %Variables that are restricted:  id, ik, and y.
+   blags = zeros(nrestrs,k);  %k=nvar*lags+1
+   cnt = 0;
+   for ki = 1:lags
+      for kj=vars_restr
+         cnt = cnt+1;
+         blags(cnt,nvar*(ki-1)+kj) = 1;
+      end
+   end
+	Ri(1:nrestrs,:,indxeqn) = blags;
+
+	%--- Lag restrictions.
+	indxeqn = 3;   %Which equation.
+	nrestrs = 1;  %Number of restrictions.
+	blags = zeros(nrestrs,k);
+	cnt = 0;
+	%--- Keep constant zero.
+	cnt = cnt+1;
+	blags(cnt,end) = 1;  %Constant = 0.
+	if cnt~=nrestrs
+	   error('Check lagged restrictions in 1st equation!')
+	end
+	Ri(1:nrestrs,:,indxeqn) = blags;
+
+	%--- Lag restrictions.
+	indxeqn = 4;   %Which equation.
+	nrestrs = 1;  %Number of restrictions.
+	blags = zeros(nrestrs,k);
+	cnt = 0;
+	%--- Keep constant zero.
+	cnt = cnt+1;
+	blags(cnt,end) = 1;  %Constant = 0.
+	if cnt~=nrestrs
+	   error('Check lagged restrictions in 1st equation!')
+	end
+	Ri(1:nrestrs,:,indxeqn) = blags;
+end
+
+
+for n=1:nvar   %  initializing loop for each equation
+   Ui{n} = null(Qi(:,:,n));
+   Vi{n} = null(Ri(:,:,n));
+   n0(n) = size(Ui{n},2);
+   np(n) = size(Vi{n},2);
+end
+
+
+
+%(2)-------------------------------------------------------------
+%  Cross-A0-and-A+ rerestrictions one quation at a time
+%    i.e., the first, second, ..., kjth, ..., equation
+%  This type of restriction is used for the New-Keysian model studied by Leeper and Zha
+%    "Assessing Simple Policy Rules: A View from a Complete Macroeconomic Model" published
+%    by St. Louis Fed Review.
+%(2)-------------------------------------------------------------
+%
+if indxC0Pres
+   neq_cres = 3;   % the number of equations in which cross-A0-A+ restrictions occur.
+   ixmC0Pres = cell(neq_cres,1);  % in each cell representing equation, we have 4 columns:
+           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
+           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
+   %** 1st equation
+   ixmC0Pres{1} = [1 2 2 1
+                   1 7 1 1];
+   %** 2nd equation
+   ixmC0Pres{2} = [2 2 2 2];
+   %** 3rd equation
+   ixmC0Pres{3} = [3 7 1 1
+                   3 2 2 1];
+
+
+%         % 4 columns.
+%   ncres = 5;  % manually key in the number of cross-A0-A+ restrictions
+
+%           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
+%           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+%           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+%           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
+else
+   ixmC0Pres = NaN;
+end
+
diff --git a/tests/ms-sbvar/archive-files/ftd_non_rec_5v.m b/tests/ms-sbvar/archive-files/ftd_non_rec_5v.m
index e7ae075494c04fe997c50a2f7a418e0fd4e3f78e..e9fbeb4099a5f9e7a43a39e8de43d90b7b4aada6 100644
--- a/tests/ms-sbvar/archive-files/ftd_non_rec_5v.m
+++ b/tests/ms-sbvar/archive-files/ftd_non_rec_5v.m
@@ -1,192 +1,192 @@
-function [Ui,Vi,n0,np,ixmC0Pres] = ftd_upperchol5v(lags,nvar,nexo,indxC0Pres)
-%  vlist = [127 124 93 141 21];    % 1: GDP; 2: GDP deflator 124 (consumption deflator 79); 3: R; 4: M3 141 (M2 140); 5: exchange rate 21.
-%  varlist={'y', 'P', 'R', 'M3', 'Ex'};
-%
-%    Exporting orthonormal matrices for the deterministic linear restrictions (equation by equation)
-%    See Waggoner and Zha's Gibbs sampling paper.
-%
-% q_m:  quarter or month
-% lags: the maximum length of lag
-% nvar:  number of endogeous variables
-% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant
-% indxC0Pres: index for cross-A0-A+ restrictions.  if 1: cross-A0-and-A+ restrictions; 0: idfile is all we have
-%                Example for indxOres==1: restrictions of the form P(t) = P(t-1).
-%                These restrictions have to be manually and carefully keyed in.
-%-----------------
-% Ui: nvar-by-1 cell.  In each cell, nvar-by-qi orthonormal basis for the null of the ith
-%           equation contemporaneous restriction matrix where qi is the number of free parameters.
-%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
-%           of total original parameters and bi is a vector of free parameters. When no
-%           restrictions are imposed, we have Ui = I.  There must be at least one free
-%           parameter left for the ith equation.
-% Vi: nvar-by-1 cell.  In each cell, k-by-ri orthonormal basis for the null of the ith
-%           equation lagged restriction matrix where k is a total of exogenous variables and
-%           ri is the number of free parameters. With this transformation, we have fi = Vi*gi
-%           or Vi'*fi = gi where fi is a vector of total original parameters and gi is a
-%           vector of free parameters. There must be at least one free parameter left for
-%           the ith equation.
-% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation
-% np: nvar-by-1, ith element represents the number of free A+ parameters in ith equation
-% ixmC0Pres:  neq_cres-by-1 cell.  Effective only if indxC0Pres=1, otherwise equals NaN.
-%             neq_cres is the number of equations in which cross-A0-A+ restrictions occur.
-%             In the jth cell representing equation, we have 4 columns:
-%               1st: the jth column (equation) of A+ or A0: f_j or a_j
-%               2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-%               3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-%               4th: the number s such that f_j(i) = s * a_j(h) holds.
-%
-% Tao Zha, May 2000
-
-
-
-Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
-Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
-n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation
-np = zeros(nvar,1); % ith element represents the number of free A+ parameters in ith equation
-
-if (nargin==2)
-   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
-elseif (nargin==3)
-   indxC0Pres = 0;  % default is no cross-A0-and-A+ restrictions.
-end
-
-k = lags*nvar+nexo;  % maximum number of lagged and exogenous variables in each equation
-
-Qi = zeros(nvar,nvar,nvar);   % for nvar contemporaneous equations
-Ri = zeros(k,k,nvar);    % for nvar lagged and exogenous equations
-  % Row corresponds to equation. 0 means no restriction.
-  %                              1 means exclusion restriction such that the corresponding parameter is restricted to 0.
-
-%nfvar = 6;   % number of foreign (Granger causing) variables
-%nhvar = nvar-nfvar;  % number of home (affected) variables.
-
-
-%-------------------------------------------------------------
-%  Beginning the manual input of the restrictions one quation at a time
-%-------------------------------------------------------------
-%
-%======== The first equation ===========
-Qi(1:4,:,1) = [
-    0 1 0 0 0
-    0 0 1 0 0
-    0 0 0 1 0
-    0 0 0 0 1
-        ];
-
-%======== The second equation ===========
-Qi(1:3,:,2) = [
-    0 0 1 0 0
-    0 0 0 1 0
-    0 0 0 0 1
-        ];
-
-%======== The third equation ===========
-Qi(1:2,:,3) = [
-    0 0 0 1 0
-    0 0 0 0 1
-        ];
-
-
-%======== The fourth equation ===========
-%Qi(1:1,:,4) = [
-%    0 0 0 0 1
-%         ];
-
-
-%======== The fifth equation ===========
-
-Qi(1:3,:,5) = [
-    1 0 0 0 0
-    0 1 0 0 0
-    0 0 1 0 0
-         ];
-
-
-
-%===== Lagged restrictions in foreign (Granger causing) block
-%nfbres = lags*(nvar-nfvar);  % number of block restrictions in each foreign equation
-%bfor = zeros(nfbres,k);  % each foreign equation
-%cnt=0;
-%for ki = 1:lags
-%   for kj=1:nvar-nfvar
-%      cnt=cnt+1;
-%      bfor(cnt,nvar*(ki-1)+nfvar+kj) = 1;
-%   end
-%end
-%%
-%if cnt~=nfbres
-%   error('Check lagged restrictions in foreign equations!')
-%end
-%%
-%for kj=1:nfvar
-%   Ri(1:nfbres,:,kj) = bfor;
-%end
-
-
-%===== Lagged restrictions in home (affected) block
-%
-%~~~~~ selected domestic equations
-%dlrindx = nfvar+1; %[nfvar+1 nfvar+2];  % index for relevant home equations
-%rfvindx = []; %[6];  %[1 2 3 5];  % index for restricted foreign variables (e.g., Poil, M2, FFR, P).
-%%nf2hvar = nfvar-length(rfvindx);  % number of free parameters -- foreign variables entering the home sector
-%nhbres = lags*length(rfvindx);  % number of block restrictions in each home equation
-%bhom = zeros(nhbres,k);  % each home equation
-%cnt=0;
-%for ki = 1:lags
-%   for kj=1:length(rfvindx)
-%      cnt=cnt+1;
-%      bhom(cnt,nvar*(ki-1)+rfvindx(kj)) = 1;
-%   end
-%end
-%%
-%if cnt~=nhbres
-%   error('Check lagged restrictions in domestic equations!')
-%end
-%%
-%for kj=dlrindx
-%   Ri(1:nhbres,:,kj) = bhom;
-%end
-
-
-for n=1:nvar   %  initializing loop for each equation
-   Ui{n} = null(Qi(:,:,n));
-   Vi{n} = null(Ri(:,:,n));
-   n0(n) = size(Ui{n},2);
-   np(n) = size(Vi{n},2);
-end
-
-
-
-%(2)-------------------------------------------------------------
-%  Cross-A0-and-A+ rerestrictions one quation at a time
-%    i.e., the first, second, ..., kjth, ..., equation
-%(2)-------------------------------------------------------------
-%
-if indxC0Pres
-   neq_cres = 3;   % the number of equations in which cross-A0-A+ restrictions occur.
-   ixmC0Pres = cell(neq_cres,1);  % in each cell representing equation, we have 4 columns:
-           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
-           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
-   %** 1st equation
-   ixmC0Pres{1} = [1 2 2 1
-                   1 7 1 1];
-   %** 2nd equation
-   ixmC0Pres{2} = [2 2 2 2];
-   %** 3rd equation
-   ixmC0Pres{3} = [3 7 1 1
-                   3 2 2 1];
-
-
-%         % 4 columns.
-%   ncres = 5;  % manually key in the number of cross-A0-A+ restrictions
-
-%           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
-%           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-%           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-%           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
-else
-   ixmC0Pres = NaN;
-end
-
+function [Ui,Vi,n0,np,ixmC0Pres] = ftd_upperchol5v(lags,nvar,nexo,indxC0Pres)
+%  vlist = [127 124 93 141 21];    % 1: GDP; 2: GDP deflator 124 (consumption deflator 79); 3: R; 4: M3 141 (M2 140); 5: exchange rate 21.
+%  varlist={'y', 'P', 'R', 'M3', 'Ex'};
+%
+%    Exporting orthonormal matrices for the deterministic linear restrictions (equation by equation)
+%    See Waggoner and Zha's Gibbs sampling paper.
+%
+% q_m:  quarter or month
+% lags: the maximum length of lag
+% nvar:  number of endogeous variables
+% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant
+% indxC0Pres: index for cross-A0-A+ restrictions.  if 1: cross-A0-and-A+ restrictions; 0: idfile is all we have
+%                Example for indxOres==1: restrictions of the form P(t) = P(t-1).
+%                These restrictions have to be manually and carefully keyed in.
+%-----------------
+% Ui: nvar-by-1 cell.  In each cell, nvar-by-qi orthonormal basis for the null of the ith
+%           equation contemporaneous restriction matrix where qi is the number of free parameters.
+%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
+%           of total original parameters and bi is a vector of free parameters. When no
+%           restrictions are imposed, we have Ui = I.  There must be at least one free
+%           parameter left for the ith equation.
+% Vi: nvar-by-1 cell.  In each cell, k-by-ri orthonormal basis for the null of the ith
+%           equation lagged restriction matrix where k is a total of exogenous variables and
+%           ri is the number of free parameters. With this transformation, we have fi = Vi*gi
+%           or Vi'*fi = gi where fi is a vector of total original parameters and gi is a
+%           vector of free parameters. There must be at least one free parameter left for
+%           the ith equation.
+% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation
+% np: nvar-by-1, ith element represents the number of free A+ parameters in ith equation
+% ixmC0Pres:  neq_cres-by-1 cell.  Effective only if indxC0Pres=1, otherwise equals NaN.
+%             neq_cres is the number of equations in which cross-A0-A+ restrictions occur.
+%             In the jth cell representing equation, we have 4 columns:
+%               1st: the jth column (equation) of A+ or A0: f_j or a_j
+%               2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+%               3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+%               4th: the number s such that f_j(i) = s * a_j(h) holds.
+%
+% Tao Zha, May 2000
+
+
+
+Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
+Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
+n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation
+np = zeros(nvar,1); % ith element represents the number of free A+ parameters in ith equation
+
+if (nargin==2)
+   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
+elseif (nargin==3)
+   indxC0Pres = 0;  % default is no cross-A0-and-A+ restrictions.
+end
+
+k = lags*nvar+nexo;  % maximum number of lagged and exogenous variables in each equation
+
+Qi = zeros(nvar,nvar,nvar);   % for nvar contemporaneous equations
+Ri = zeros(k,k,nvar);    % for nvar lagged and exogenous equations
+  % Row corresponds to equation. 0 means no restriction.
+  %                              1 means exclusion restriction such that the corresponding parameter is restricted to 0.
+
+%nfvar = 6;   % number of foreign (Granger causing) variables
+%nhvar = nvar-nfvar;  % number of home (affected) variables.
+
+
+%-------------------------------------------------------------
+%  Beginning the manual input of the restrictions one quation at a time
+%-------------------------------------------------------------
+%
+%======== The first equation ===========
+Qi(1:4,:,1) = [
+    0 1 0 0 0
+    0 0 1 0 0
+    0 0 0 1 0
+    0 0 0 0 1
+        ];
+
+%======== The second equation ===========
+Qi(1:3,:,2) = [
+    0 0 1 0 0
+    0 0 0 1 0
+    0 0 0 0 1
+        ];
+
+%======== The third equation ===========
+Qi(1:2,:,3) = [
+    0 0 0 1 0
+    0 0 0 0 1
+        ];
+
+
+%======== The fourth equation ===========
+%Qi(1:1,:,4) = [
+%    0 0 0 0 1
+%         ];
+
+
+%======== The fifth equation ===========
+
+Qi(1:3,:,5) = [
+    1 0 0 0 0
+    0 1 0 0 0
+    0 0 1 0 0
+         ];
+
+
+
+%===== Lagged restrictions in foreign (Granger causing) block
+%nfbres = lags*(nvar-nfvar);  % number of block restrictions in each foreign equation
+%bfor = zeros(nfbres,k);  % each foreign equation
+%cnt=0;
+%for ki = 1:lags
+%   for kj=1:nvar-nfvar
+%      cnt=cnt+1;
+%      bfor(cnt,nvar*(ki-1)+nfvar+kj) = 1;
+%   end
+%end
+%%
+%if cnt~=nfbres
+%   error('Check lagged restrictions in foreign equations!')
+%end
+%%
+%for kj=1:nfvar
+%   Ri(1:nfbres,:,kj) = bfor;
+%end
+
+
+%===== Lagged restrictions in home (affected) block
+%
+%~~~~~ selected domestic equations
+%dlrindx = nfvar+1; %[nfvar+1 nfvar+2];  % index for relevant home equations
+%rfvindx = []; %[6];  %[1 2 3 5];  % index for restricted foreign variables (e.g., Poil, M2, FFR, P).
+%%nf2hvar = nfvar-length(rfvindx);  % number of free parameters -- foreign variables entering the home sector
+%nhbres = lags*length(rfvindx);  % number of block restrictions in each home equation
+%bhom = zeros(nhbres,k);  % each home equation
+%cnt=0;
+%for ki = 1:lags
+%   for kj=1:length(rfvindx)
+%      cnt=cnt+1;
+%      bhom(cnt,nvar*(ki-1)+rfvindx(kj)) = 1;
+%   end
+%end
+%%
+%if cnt~=nhbres
+%   error('Check lagged restrictions in domestic equations!')
+%end
+%%
+%for kj=dlrindx
+%   Ri(1:nhbres,:,kj) = bhom;
+%end
+
+
+for n=1:nvar   %  initializing loop for each equation
+   Ui{n} = null(Qi(:,:,n));
+   Vi{n} = null(Ri(:,:,n));
+   n0(n) = size(Ui{n},2);
+   np(n) = size(Vi{n},2);
+end
+
+
+
+%(2)-------------------------------------------------------------
+%  Cross-A0-and-A+ rerestrictions one quation at a time
+%    i.e., the first, second, ..., kjth, ..., equation
+%(2)-------------------------------------------------------------
+%
+if indxC0Pres
+   neq_cres = 3;   % the number of equations in which cross-A0-A+ restrictions occur.
+   ixmC0Pres = cell(neq_cres,1);  % in each cell representing equation, we have 4 columns:
+           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
+           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
+   %** 1st equation
+   ixmC0Pres{1} = [1 2 2 1
+                   1 7 1 1];
+   %** 2nd equation
+   ixmC0Pres{2} = [2 2 2 2];
+   %** 3rd equation
+   ixmC0Pres{3} = [3 7 1 1
+                   3 2 2 1];
+
+
+%         % 4 columns.
+%   ncres = 5;  % manually key in the number of cross-A0-A+ restrictions
+
+%           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
+%           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+%           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+%           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
+else
+   ixmC0Pres = NaN;
+end
+
diff --git a/tests/ms-sbvar/archive-files/ftd_simszha5v.m b/tests/ms-sbvar/archive-files/ftd_simszha5v.m
index a2092fb3e8d374d4b742af6a930022f00c6c79d3..0a0034a9d0298e983674cc113fae1b28a8311c70 100644
--- a/tests/ms-sbvar/archive-files/ftd_simszha5v.m
+++ b/tests/ms-sbvar/archive-files/ftd_simszha5v.m
@@ -1,190 +1,190 @@
-function [Ui,Vi,n0,np,ixmC0Pres] = ftd_simszha5v(lags,nvar,nexo,indxC0Pres)
-%vlist = [21  141  93  127  124];    % 1: Pcom 2 (exchange rate 21); 2: M3 141 (M2 140); 3: R; 4: GDP; 5: GDP deflator 124 (consumption deflator 79).
-%varlist={'Ex', 'M3', 'R', 'y','P'};
-%
-%    Exporting orthonormal matrices for the deterministic linear restrictions (equation by equation)
-%    See Waggoner and Zha's Gibbs sampling paper.
-%
-% q_m:  quarter or month
-% lags: the maximum length of lag
-% nvar:  number of endogeous variables
-% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant
-% indxC0Pres: index for cross-A0-A+ restrictions.  if 1: cross-A0-and-A+ restrictions; 0: idfile is all we have
-%                Example for indxOres==1: restrictions of the form P(t) = P(t-1).
-%                These restrictions have to be manually and carefully keyed in.
-%-----------------
-% Ui: nvar-by-1 cell.  In each cell, nvar-by-qi orthonormal basis for the null of the ith
-%           equation contemporaneous restriction matrix where qi is the number of free parameters.
-%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
-%           of total original parameters and bi is a vector of free parameters. When no
-%           restrictions are imposed, we have Ui = I.  There must be at least one free
-%           parameter left for the ith equation.
-% Vi: nvar-by-1 cell.  In each cell, k-by-ri orthonormal basis for the null of the ith
-%           equation lagged restriction matrix where k is a total of exogenous variables and
-%           ri is the number of free parameters. With this transformation, we have fi = Vi*gi
-%           or Vi'*fi = gi where fi is a vector of total original parameters and gi is a
-%           vector of free parameters. There must be at least one free parameter left for
-%           the ith equation.
-% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation
-% np: nvar-by-1, ith element represents the number of free A+ parameters in ith equation
-% ixmC0Pres:  neq_cres-by-1 cell.  Effective only if indxC0Pres=1, otherwise equals NaN.
-%             neq_cres is the number of equations in which cross-A0-A+ restrictions occur.
-%             In the jth cell representing equation, we have 4 columns:
-%               1st: the jth column (equation) of A+ or A0: f_j or a_j
-%               2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-%               3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-%               4th: the number s such that f_j(i) = s * a_j(h) holds.
-%
-% Tao Zha, May 2000
-
-
-
-Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
-Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
-n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation
-np = zeros(nvar,1); % ith element represents the number of free A+ parameters in ith equation
-
-if (nargin==2)
-   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
-elseif (nargin==3)
-   indxC0Pres = 0;  % default is no cross-A0-and-A+ restrictions.
-end
-
-k = lags*nvar+nexo;  % maximum number of lagged and exogenous variables in each equation
-
-Qi = zeros(nvar,nvar,nvar);   % for nvar contemporaneous equations
-Ri = zeros(k,k,nvar);    % for nvar lagged and exogenous equations
-  % Row corresponds to equation. 0 means no restriction.
-  %                              1 means exclusion restriction such that the corresponding parameter is restricted to 0.
-
-%nfvar = 6;   % number of foreign (Granger causing) variables
-%nhvar = nvar-nfvar;  % number of home (affected) variables.
-
-
-%-------------------------------------------------------------
-%  Beginning the manual input of the restrictions one quation at a time
-%-------------------------------------------------------------
-%
-
-%======== The first equation: information sector ===========
-
-
-%======== The second equation: monetary policy ===========
-%Qi(1:2,:,2) = [
-%   0 0 0 1 0
-%   0 0 0 0 1
-%        ];    % Respond to Pcom.
-Qi(1:3,:,2) = [
-   1 0 0 0 0
-   0 0 0 1 0
-   0 0 0 0 1
-        ];    % Not respond to Pcom.
-
-%======== The third equation: money demand ===========
-Qi(1,:,3) = [
-   1 0 0 0 0
-        ];
-
-%======== The fourth equation: y equation ===========
-Qi(1:4,:,4) = [
-   1 0 0 0 0
-   0 1 0 0 0
-   0 0 1 0 0
-   0 0 0 0 1
-        ];
-
-%======== The fifth equation: p equation ===========
-Qi(1:3,:,5) = [
-   1 0 0 0 0
-   0 1 0 0 0
-   0 0 1 0 0
-        ];
-
-
-%===== Lagged restrictions in foreign (Granger causing) block
-%nfbres = lags*(nvar-nfvar);  % number of block restrictions in each foreign equation
-%bfor = zeros(nfbres,k);  % each foreign equation
-%cnt=0;
-%for ki = 1:lags
-%   for kj=1:nvar-nfvar
-%      cnt=cnt+1;
-%      bfor(cnt,nvar*(ki-1)+nfvar+kj) = 1;
-%   end
-%end
-%%
-%if cnt~=nfbres
-%   error('Check lagged restrictions in foreign equations!')
-%end
-%%
-%for kj=1:nfvar
-%   Ri(1:nfbres,:,kj) = bfor;
-%end
-
-
-%===== Lagged restrictions in home (affected) block
-%
-%~~~~~ selected domestic equations
-%dlrindx = nfvar+1; %[nfvar+1 nfvar+2];  % index for relevant home equations
-%rfvindx = []; %[6];  %[1 2 3 5];  % index for restricted foreign variables (e.g., Poil, M2, FFR, P).
-%%nf2hvar = nfvar-length(rfvindx);  % number of free parameters -- foreign variables entering the home sector
-%nhbres = lags*length(rfvindx);  % number of block restrictions in each home equation
-%bhom = zeros(nhbres,k);  % each home equation
-%cnt=0;
-%for ki = 1:lags
-%   for kj=1:length(rfvindx)
-%      cnt=cnt+1;
-%      bhom(cnt,nvar*(ki-1)+rfvindx(kj)) = 1;
-%   end
-%end
-%%
-%if cnt~=nhbres
-%   error('Check lagged restrictions in domestic equations!')
-%end
-%%
-%for kj=dlrindx
-%   Ri(1:nhbres,:,kj) = bhom;
-%end
-
-
-for n=1:nvar   %  initializing loop for each equation
-   Ui{n} = null(Qi(:,:,n));
-   Vi{n} = null(Ri(:,:,n));
-   n0(n) = size(Ui{n},2);
-   np(n) = size(Vi{n},2);
-end
-
-
-
-%(2)-------------------------------------------------------------
-%  Cross-A0-and-A+ rerestrictions one quation at a time
-%    i.e., the first, second, ..., kjth, ..., equation
-%(2)-------------------------------------------------------------
-%
-if indxC0Pres
-   neq_cres = 3;   % the number of equations in which cross-A0-A+ restrictions occur.
-   ixmC0Pres = cell(neq_cres,1);  % in each cell representing equation, we have 4 columns:
-           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
-           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
-   %** 1st equation
-   ixmC0Pres{1} = [1 2 2 1
-                   1 7 1 1];
-   %** 2nd equation
-   ixmC0Pres{2} = [2 2 2 2];
-   %** 3rd equation
-   ixmC0Pres{3} = [3 7 1 1
-                   3 2 2 1];
-
-
-%         % 4 columns.
-%   ncres = 5;  % manually key in the number of cross-A0-A+ restrictions
-
-%           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
-%           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-%           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-%           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
-else
-   ixmC0Pres = NaN;
-end
-
+function [Ui,Vi,n0,np,ixmC0Pres] = ftd_simszha5v(lags,nvar,nexo,indxC0Pres)
+%vlist = [21  141  93  127  124];    % 1: Pcom 2 (exchange rate 21); 2: M3 141 (M2 140); 3: R; 4: GDP; 5: GDP deflator 124 (consumption deflator 79).
+%varlist={'Ex', 'M3', 'R', 'y','P'};
+%
+%    Exporting orthonormal matrices for the deterministic linear restrictions (equation by equation)
+%    See Waggoner and Zha's Gibbs sampling paper.
+%
+% q_m:  quarter or month
+% lags: the maximum length of lag
+% nvar:  number of endogeous variables
+% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant
+% indxC0Pres: index for cross-A0-A+ restrictions.  if 1: cross-A0-and-A+ restrictions; 0: idfile is all we have
+%                Example for indxOres==1: restrictions of the form P(t) = P(t-1).
+%                These restrictions have to be manually and carefully keyed in.
+%-----------------
+% Ui: nvar-by-1 cell.  In each cell, nvar-by-qi orthonormal basis for the null of the ith
+%           equation contemporaneous restriction matrix where qi is the number of free parameters.
+%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
+%           of total original parameters and bi is a vector of free parameters. When no
+%           restrictions are imposed, we have Ui = I.  There must be at least one free
+%           parameter left for the ith equation.
+% Vi: nvar-by-1 cell.  In each cell, k-by-ri orthonormal basis for the null of the ith
+%           equation lagged restriction matrix where k is a total of exogenous variables and
+%           ri is the number of free parameters. With this transformation, we have fi = Vi*gi
+%           or Vi'*fi = gi where fi is a vector of total original parameters and gi is a
+%           vector of free parameters. There must be at least one free parameter left for
+%           the ith equation.
+% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation
+% np: nvar-by-1, ith element represents the number of free A+ parameters in ith equation
+% ixmC0Pres:  neq_cres-by-1 cell.  Effective only if indxC0Pres=1, otherwise equals NaN.
+%             neq_cres is the number of equations in which cross-A0-A+ restrictions occur.
+%             In the jth cell representing equation, we have 4 columns:
+%               1st: the jth column (equation) of A+ or A0: f_j or a_j
+%               2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+%               3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+%               4th: the number s such that f_j(i) = s * a_j(h) holds.
+%
+% Tao Zha, May 2000
+
+
+
+Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
+Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
+n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation
+np = zeros(nvar,1); % ith element represents the number of free A+ parameters in ith equation
+
+if (nargin==2)
+   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
+elseif (nargin==3)
+   indxC0Pres = 0;  % default is no cross-A0-and-A+ restrictions.
+end
+
+k = lags*nvar+nexo;  % maximum number of lagged and exogenous variables in each equation
+
+Qi = zeros(nvar,nvar,nvar);   % for nvar contemporaneous equations
+Ri = zeros(k,k,nvar);    % for nvar lagged and exogenous equations
+  % Row corresponds to equation. 0 means no restriction.
+  %                              1 means exclusion restriction such that the corresponding parameter is restricted to 0.
+
+%nfvar = 6;   % number of foreign (Granger causing) variables
+%nhvar = nvar-nfvar;  % number of home (affected) variables.
+
+
+%-------------------------------------------------------------
+%  Beginning the manual input of the restrictions one quation at a time
+%-------------------------------------------------------------
+%
+
+%======== The first equation: information sector ===========
+
+
+%======== The second equation: monetary policy ===========
+%Qi(1:2,:,2) = [
+%   0 0 0 1 0
+%   0 0 0 0 1
+%        ];    % Respond to Pcom.
+Qi(1:3,:,2) = [
+   1 0 0 0 0
+   0 0 0 1 0
+   0 0 0 0 1
+        ];    % Not respond to Pcom.
+
+%======== The third equation: money demand ===========
+Qi(1,:,3) = [
+   1 0 0 0 0
+        ];
+
+%======== The fourth equation: y equation ===========
+Qi(1:4,:,4) = [
+   1 0 0 0 0
+   0 1 0 0 0
+   0 0 1 0 0
+   0 0 0 0 1
+        ];
+
+%======== The fifth equation: p equation ===========
+Qi(1:3,:,5) = [
+   1 0 0 0 0
+   0 1 0 0 0
+   0 0 1 0 0
+        ];
+
+
+%===== Lagged restrictions in foreign (Granger causing) block
+%nfbres = lags*(nvar-nfvar);  % number of block restrictions in each foreign equation
+%bfor = zeros(nfbres,k);  % each foreign equation
+%cnt=0;
+%for ki = 1:lags
+%   for kj=1:nvar-nfvar
+%      cnt=cnt+1;
+%      bfor(cnt,nvar*(ki-1)+nfvar+kj) = 1;
+%   end
+%end
+%%
+%if cnt~=nfbres
+%   error('Check lagged restrictions in foreign equations!')
+%end
+%%
+%for kj=1:nfvar
+%   Ri(1:nfbres,:,kj) = bfor;
+%end
+
+
+%===== Lagged restrictions in home (affected) block
+%
+%~~~~~ selected domestic equations
+%dlrindx = nfvar+1; %[nfvar+1 nfvar+2];  % index for relevant home equations
+%rfvindx = []; %[6];  %[1 2 3 5];  % index for restricted foreign variables (e.g., Poil, M2, FFR, P).
+%%nf2hvar = nfvar-length(rfvindx);  % number of free parameters -- foreign variables entering the home sector
+%nhbres = lags*length(rfvindx);  % number of block restrictions in each home equation
+%bhom = zeros(nhbres,k);  % each home equation
+%cnt=0;
+%for ki = 1:lags
+%   for kj=1:length(rfvindx)
+%      cnt=cnt+1;
+%      bhom(cnt,nvar*(ki-1)+rfvindx(kj)) = 1;
+%   end
+%end
+%%
+%if cnt~=nhbres
+%   error('Check lagged restrictions in domestic equations!')
+%end
+%%
+%for kj=dlrindx
+%   Ri(1:nhbres,:,kj) = bhom;
+%end
+
+
+for n=1:nvar   %  initializing loop for each equation
+   Ui{n} = null(Qi(:,:,n));
+   Vi{n} = null(Ri(:,:,n));
+   n0(n) = size(Ui{n},2);
+   np(n) = size(Vi{n},2);
+end
+
+
+
+%(2)-------------------------------------------------------------
+%  Cross-A0-and-A+ rerestrictions one quation at a time
+%    i.e., the first, second, ..., kjth, ..., equation
+%(2)-------------------------------------------------------------
+%
+if indxC0Pres
+   neq_cres = 3;   % the number of equations in which cross-A0-A+ restrictions occur.
+   ixmC0Pres = cell(neq_cres,1);  % in each cell representing equation, we have 4 columns:
+           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
+           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
+   %** 1st equation
+   ixmC0Pres{1} = [1 2 2 1
+                   1 7 1 1];
+   %** 2nd equation
+   ixmC0Pres{2} = [2 2 2 2];
+   %** 3rd equation
+   ixmC0Pres{3} = [3 7 1 1
+                   3 2 2 1];
+
+
+%         % 4 columns.
+%   ncres = 5;  % manually key in the number of cross-A0-A+ restrictions
+
+%           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
+%           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+%           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+%           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
+else
+   ixmC0Pres = NaN;
+end
+
diff --git a/tests/ms-sbvar/archive-files/ftd_upperchol3v.m b/tests/ms-sbvar/archive-files/ftd_upperchol3v.m
index 4376b3c5d5a56b0d6c15c56912aef46142b77d61..a5c19f79e8ef575e6e0ff1480593e73b84ebf19e 100644
--- a/tests/ms-sbvar/archive-files/ftd_upperchol3v.m
+++ b/tests/ms-sbvar/archive-files/ftd_upperchol3v.m
@@ -1,170 +1,170 @@
-function [Ui,Vi,n0,np,ixmC0Pres] = ftd_upperchol3v(lags,nvar,nexo,indxC0Pres)
-%vlist = [20 6 3 44 1 10];    % regarding "xdd", Pcom (Poil or imfcom), M2, FFR, GDP, CPI (or PCE), and U.
-%
-%    Exporting orthonormal matrices for the deterministic linear restrictions (equation by equation)
-%    See Waggoner and Zha's Gibbs sampling paper.
-%
-% q_m:  quarter or month
-% lags: the maximum length of lag
-% nvar:  number of endogeous variables
-% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant
-% indxC0Pres: index for cross-A0-A+ restrictions.  if 1: cross-A0-and-A+ restrictions; 0: idfile is all we have
-%                Example for indxOres==1: restrictions of the form P(t) = P(t-1).
-%                These restrictions have to be manually and carefully keyed in.
-%-----------------
-% Ui: nvar-by-1 cell.  In each cell, nvar-by-qi orthonormal basis for the null of the ith
-%           equation contemporaneous restriction matrix where qi is the number of free parameters.
-%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
-%           of total original parameters and bi is a vector of free parameters. When no
-%           restrictions are imposed, we have Ui = I.  There must be at least one free
-%           parameter left for the ith equation.
-% Vi: nvar-by-1 cell.  In each cell, k-by-ri orthonormal basis for the null of the ith
-%           equation lagged restriction matrix where k is a total of exogenous variables and
-%           ri is the number of free parameters. With this transformation, we have fi = Vi*gi
-%           or Vi'*fi = gi where fi is a vector of total original parameters and gi is a
-%           vector of free parameters. There must be at least one free parameter left for
-%           the ith equation.
-% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation
-% np: nvar-by-1, ith element represents the number of free A+ parameters in ith equation
-% ixmC0Pres:  neq_cres-by-1 cell.  Effective only if indxC0Pres=1, otherwise equals NaN.
-%             neq_cres is the number of equations in which cross-A0-A+ restrictions occur.
-%             In the jth cell representing equation, we have 4 columns:
-%               1st: the jth column (equation) of A+ or A0: f_j or a_j
-%               2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-%               3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-%               4th: the number s such that f_j(i) = s * a_j(h) holds.
-%
-% Tao Zha, May 2000
-
-
-
-Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
-Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
-n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation
-np = zeros(nvar,1); % ith element represents the number of free A+ parameters in ith equation
-
-if (nargin==2)
-   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
-elseif (nargin==3)
-   indxC0Pres = 0;  % default is no cross-A0-and-A+ restrictions.
-end
-
-k = lags*nvar+nexo;  % maximum number of lagged and exogenous variables in each equation
-
-Qi = zeros(nvar,nvar,nvar);   % for nvar contemporaneous equations
-Ri = zeros(k,k,nvar);    % for nvar lagged and exogenous equations
-  % Row corresponds to equation. 0 means no restriction.
-  %                              1 means exclusion restriction such that the corresponding parameter is restricted to 0.
-
-%nfvar = 6;   % number of foreign (Granger causing) variables
-%nhvar = nvar-nfvar;  % number of home (affected) variables.
-
-
-%-------------------------------------------------------------
-%  Beginning the manual input of the restrictions one quation at a time
-%-------------------------------------------------------------
-%
-
-%======== The first equation ===========
-Qi(1:2,:,1) = [
-    0 1 0
-    0 0 1
-        ];
-
-%======== The second equation ===========
-Qi(1:1,:,2) = [
-    0 0 1
-        ];
-
-
-%======== The third equation ===========
-
-
-
-%===== Lagged restrictions in foreign (Granger causing) block
-%nfbres = lags*(nvar-nfvar);  % number of block restrictions in each foreign equation
-%bfor = zeros(nfbres,k);  % each foreign equation
-%cnt=0;
-%for ki = 1:lags
-%   for kj=1:nvar-nfvar
-%      cnt=cnt+1;
-%      bfor(cnt,nvar*(ki-1)+nfvar+kj) = 1;
-%   end
-%end
-%%
-%if cnt~=nfbres
-%   error('Check lagged restrictions in foreign equations!')
-%end
-%%
-%for kj=1:nfvar
-%   Ri(1:nfbres,:,kj) = bfor;
-%end
-
-
-%===== Lagged restrictions in home (affected) block
-%
-%~~~~~ selected domestic equations
-%dlrindx = nfvar+1; %[nfvar+1 nfvar+2];  % index for relevant home equations
-%rfvindx = []; %[6];  %[1 2 3 5];  % index for restricted foreign variables (e.g., Poil, M2, FFR, P).
-%%nf2hvar = nfvar-length(rfvindx);  % number of free parameters -- foreign variables entering the home sector
-%nhbres = lags*length(rfvindx);  % number of block restrictions in each home equation
-%bhom = zeros(nhbres,k);  % each home equation
-%cnt=0;
-%for ki = 1:lags
-%   for kj=1:length(rfvindx)
-%      cnt=cnt+1;
-%      bhom(cnt,nvar*(ki-1)+rfvindx(kj)) = 1;
-%   end
-%end
-%%
-%if cnt~=nhbres
-%   error('Check lagged restrictions in domestic equations!')
-%end
-%%
-%for kj=dlrindx
-%   Ri(1:nhbres,:,kj) = bhom;
-%end
-
-
-for n=1:nvar   %  initializing loop for each equation
-   Ui{n} = null(Qi(:,:,n));
-   Vi{n} = null(Ri(:,:,n));
-   n0(n) = size(Ui{n},2);
-   np(n) = size(Vi{n},2);
-end
-
-
-
-%(2)-------------------------------------------------------------
-%  Cross-A0-and-A+ rerestrictions one quation at a time
-%    i.e., the first, second, ..., kjth, ..., equation
-%(2)-------------------------------------------------------------
-%
-if indxC0Pres
-   neq_cres = 3;   % the number of equations in which cross-A0-A+ restrictions occur.
-   ixmC0Pres = cell(neq_cres,1);  % in each cell representing equation, we have 4 columns:
-           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
-           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
-   %** 1st equation
-   ixmC0Pres{1} = [1 2 2 1
-                   1 7 1 1];
-   %** 2nd equation
-   ixmC0Pres{2} = [2 2 2 2];
-   %** 3rd equation
-   ixmC0Pres{3} = [3 7 1 1
-                   3 2 2 1];
-
-
-%         % 4 columns.
-%   ncres = 5;  % manually key in the number of cross-A0-A+ restrictions
-
-%           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
-%           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-%           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-%           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
-else
-   ixmC0Pres = NaN;
-end
-
+function [Ui,Vi,n0,np,ixmC0Pres] = ftd_upperchol3v(lags,nvar,nexo,indxC0Pres)
+%vlist = [20 6 3 44 1 10];    % regarding "xdd", Pcom (Poil or imfcom), M2, FFR, GDP, CPI (or PCE), and U.
+%
+%    Exporting orthonormal matrices for the deterministic linear restrictions (equation by equation)
+%    See Waggoner and Zha's Gibbs sampling paper.
+%
+% q_m:  quarter or month
+% lags: the maximum length of lag
+% nvar:  number of endogeous variables
+% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant
+% indxC0Pres: index for cross-A0-A+ restrictions.  if 1: cross-A0-and-A+ restrictions; 0: idfile is all we have
+%                Example for indxOres==1: restrictions of the form P(t) = P(t-1).
+%                These restrictions have to be manually and carefully keyed in.
+%-----------------
+% Ui: nvar-by-1 cell.  In each cell, nvar-by-qi orthonormal basis for the null of the ith
+%           equation contemporaneous restriction matrix where qi is the number of free parameters.
+%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
+%           of total original parameters and bi is a vector of free parameters. When no
+%           restrictions are imposed, we have Ui = I.  There must be at least one free
+%           parameter left for the ith equation.
+% Vi: nvar-by-1 cell.  In each cell, k-by-ri orthonormal basis for the null of the ith
+%           equation lagged restriction matrix where k is a total of exogenous variables and
+%           ri is the number of free parameters. With this transformation, we have fi = Vi*gi
+%           or Vi'*fi = gi where fi is a vector of total original parameters and gi is a
+%           vector of free parameters. There must be at least one free parameter left for
+%           the ith equation.
+% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation
+% np: nvar-by-1, ith element represents the number of free A+ parameters in ith equation
+% ixmC0Pres:  neq_cres-by-1 cell.  Effective only if indxC0Pres=1, otherwise equals NaN.
+%             neq_cres is the number of equations in which cross-A0-A+ restrictions occur.
+%             In the jth cell representing equation, we have 4 columns:
+%               1st: the jth column (equation) of A+ or A0: f_j or a_j
+%               2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+%               3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+%               4th: the number s such that f_j(i) = s * a_j(h) holds.
+%
+% Tao Zha, May 2000
+
+
+
+Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
+Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
+n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation
+np = zeros(nvar,1); % ith element represents the number of free A+ parameters in ith equation
+
+if (nargin==2)
+   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
+elseif (nargin==3)
+   indxC0Pres = 0;  % default is no cross-A0-and-A+ restrictions.
+end
+
+k = lags*nvar+nexo;  % maximum number of lagged and exogenous variables in each equation
+
+Qi = zeros(nvar,nvar,nvar);   % for nvar contemporaneous equations
+Ri = zeros(k,k,nvar);    % for nvar lagged and exogenous equations
+  % Row corresponds to equation. 0 means no restriction.
+  %                              1 means exclusion restriction such that the corresponding parameter is restricted to 0.
+
+%nfvar = 6;   % number of foreign (Granger causing) variables
+%nhvar = nvar-nfvar;  % number of home (affected) variables.
+
+
+%-------------------------------------------------------------
+%  Beginning the manual input of the restrictions one quation at a time
+%-------------------------------------------------------------
+%
+
+%======== The first equation ===========
+Qi(1:2,:,1) = [
+    0 1 0
+    0 0 1
+        ];
+
+%======== The second equation ===========
+Qi(1:1,:,2) = [
+    0 0 1
+        ];
+
+
+%======== The third equation ===========
+
+
+
+%===== Lagged restrictions in foreign (Granger causing) block
+%nfbres = lags*(nvar-nfvar);  % number of block restrictions in each foreign equation
+%bfor = zeros(nfbres,k);  % each foreign equation
+%cnt=0;
+%for ki = 1:lags
+%   for kj=1:nvar-nfvar
+%      cnt=cnt+1;
+%      bfor(cnt,nvar*(ki-1)+nfvar+kj) = 1;
+%   end
+%end
+%%
+%if cnt~=nfbres
+%   error('Check lagged restrictions in foreign equations!')
+%end
+%%
+%for kj=1:nfvar
+%   Ri(1:nfbres,:,kj) = bfor;
+%end
+
+
+%===== Lagged restrictions in home (affected) block
+%
+%~~~~~ selected domestic equations
+%dlrindx = nfvar+1; %[nfvar+1 nfvar+2];  % index for relevant home equations
+%rfvindx = []; %[6];  %[1 2 3 5];  % index for restricted foreign variables (e.g., Poil, M2, FFR, P).
+%%nf2hvar = nfvar-length(rfvindx);  % number of free parameters -- foreign variables entering the home sector
+%nhbres = lags*length(rfvindx);  % number of block restrictions in each home equation
+%bhom = zeros(nhbres,k);  % each home equation
+%cnt=0;
+%for ki = 1:lags
+%   for kj=1:length(rfvindx)
+%      cnt=cnt+1;
+%      bhom(cnt,nvar*(ki-1)+rfvindx(kj)) = 1;
+%   end
+%end
+%%
+%if cnt~=nhbres
+%   error('Check lagged restrictions in domestic equations!')
+%end
+%%
+%for kj=dlrindx
+%   Ri(1:nhbres,:,kj) = bhom;
+%end
+
+
+for n=1:nvar   %  initializing loop for each equation
+   Ui{n} = null(Qi(:,:,n));
+   Vi{n} = null(Ri(:,:,n));
+   n0(n) = size(Ui{n},2);
+   np(n) = size(Vi{n},2);
+end
+
+
+
+%(2)-------------------------------------------------------------
+%  Cross-A0-and-A+ rerestrictions one quation at a time
+%    i.e., the first, second, ..., kjth, ..., equation
+%(2)-------------------------------------------------------------
+%
+if indxC0Pres
+   neq_cres = 3;   % the number of equations in which cross-A0-A+ restrictions occur.
+   ixmC0Pres = cell(neq_cres,1);  % in each cell representing equation, we have 4 columns:
+           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
+           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
+   %** 1st equation
+   ixmC0Pres{1} = [1 2 2 1
+                   1 7 1 1];
+   %** 2nd equation
+   ixmC0Pres{2} = [2 2 2 2];
+   %** 3rd equation
+   ixmC0Pres{3} = [3 7 1 1
+                   3 2 2 1];
+
+
+%         % 4 columns.
+%   ncres = 5;  % manually key in the number of cross-A0-A+ restrictions
+
+%           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
+%           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+%           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+%           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
+else
+   ixmC0Pres = NaN;
+end
+
diff --git a/tests/ms-sbvar/archive-files/ftd_upperchol4v.m b/tests/ms-sbvar/archive-files/ftd_upperchol4v.m
index 78c9a7c5142192a3ae03a623eb1b9baa266b34c8..aadac9512f31724b77225a07edc5ede987795aa4 100644
--- a/tests/ms-sbvar/archive-files/ftd_upperchol4v.m
+++ b/tests/ms-sbvar/archive-files/ftd_upperchol4v.m
@@ -1,178 +1,178 @@
-function [Ui,Vi,n0,np,ixmC0Pres] = ftd_upperchol4v(lags,nvar,nexo,indxC0Pres)
-%  vlist = [127 124 93 141 21];    % 1: GDP; 2: GDP deflator 124 (consumption deflator 79); 3: R; 4: M3 141 (M2 140); 5: exchange rate 21.
-%  varlist={'y', 'P', 'R', 'M3', 'Ex'};
-%
-%    Exporting orthonormal matrices for the deterministic linear restrictions (equation by equation)
-%    See Waggoner and Zha's Gibbs sampling paper.
-%
-% q_m:  quarter or month
-% lags: the maximum length of lag
-% nvar:  number of endogeous variables
-% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant
-% indxC0Pres: index for cross-A0-A+ restrictions.  if 1: cross-A0-and-A+ restrictions; 0: idfile is all we have
-%                Example for indxOres==1: restrictions of the form P(t) = P(t-1).
-%                These restrictions have to be manually and carefully keyed in.
-%-----------------
-% Ui: nvar-by-1 cell.  In each cell, nvar-by-qi orthonormal basis for the null of the ith
-%           equation contemporaneous restriction matrix where qi is the number of free parameters.
-%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
-%           of total original parameters and bi is a vector of free parameters. When no
-%           restrictions are imposed, we have Ui = I.  There must be at least one free
-%           parameter left for the ith equation.
-% Vi: nvar-by-1 cell.  In each cell, k-by-ri orthonormal basis for the null of the ith
-%           equation lagged restriction matrix where k is a total of exogenous variables and
-%           ri is the number of free parameters. With this transformation, we have fi = Vi*gi
-%           or Vi'*fi = gi where fi is a vector of total original parameters and gi is a
-%           vector of free parameters. There must be at least one free parameter left for
-%           the ith equation.
-% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation
-% np: nvar-by-1, ith element represents the number of free A+ parameters in ith equation
-% ixmC0Pres:  neq_cres-by-1 cell.  Effective only if indxC0Pres=1, otherwise equals NaN.
-%             neq_cres is the number of equations in which cross-A0-A+ restrictions occur.
-%             In the jth cell representing equation, we have 4 columns:
-%               1st: the jth column (equation) of A+ or A0: f_j or a_j
-%               2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-%               3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-%               4th: the number s such that f_j(i) = s * a_j(h) holds.
-%
-% Tao Zha, May 2000
-
-
-
-Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
-Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
-n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation
-np = zeros(nvar,1); % ith element represents the number of free A+ parameters in ith equation
-
-if (nargin==2)
-   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
-elseif (nargin==3)
-   indxC0Pres = 0;  % default is no cross-A0-and-A+ restrictions.
-end
-
-k = lags*nvar+nexo;  % maximum number of lagged and exogenous variables in each equation
-
-Qi = zeros(nvar,nvar,nvar);   % for nvar contemporaneous equations
-Ri = zeros(k,k,nvar);    % for nvar lagged and exogenous equations
-  % Row corresponds to equation. 0 means no restriction.
-  %                              1 means exclusion restriction such that the corresponding parameter is restricted to 0.
-
-%nfvar = 6;   % number of foreign (Granger causing) variables
-%nhvar = nvar-nfvar;  % number of home (affected) variables.
-
-
-%-------------------------------------------------------------
-%  Beginning the manual input of the restrictions one quation at a time
-%-------------------------------------------------------------
-%
-%======== The first equation ===========
-Qi(1:3,:,1) = [
-    0 1 0 0
-    0 0 1 0
-    0 0 0 1
-        ];
-
-%======== The second equation ===========
-Qi(1:2,:,2) = [
-    0 0 1 0
-    0 0 0 1
-        ];
-
-%======== The third equation ===========
-Qi(1:1,:,3) = [
-    0 0 0 1
-        ];
-
-
-%======== The fourth equation ===========
-
-
-
-
-%===== Lagged restrictions in foreign (Granger causing) block
-%nfbres = lags*(nvar-nfvar);  % number of block restrictions in each foreign equation
-%bfor = zeros(nfbres,k);  % each foreign equation
-%cnt=0;
-%for ki = 1:lags
-%   for kj=1:nvar-nfvar
-%      cnt=cnt+1;
-%      bfor(cnt,nvar*(ki-1)+nfvar+kj) = 1;
-%   end
-%end
-%%
-%if cnt~=nfbres
-%   error('Check lagged restrictions in foreign equations!')
-%end
-%%
-%for kj=1:nfvar
-%   Ri(1:nfbres,:,kj) = bfor;
-%end
-
-
-%===== Lagged restrictions in home (affected) block
-%
-%~~~~~ selected domestic equations
-%dlrindx = nfvar+1; %[nfvar+1 nfvar+2];  % index for relevant home equations
-%rfvindx = []; %[6];  %[1 2 3 5];  % index for restricted foreign variables (e.g., Poil, M2, FFR, P).
-%%nf2hvar = nfvar-length(rfvindx);  % number of free parameters -- foreign variables entering the home sector
-%nhbres = lags*length(rfvindx);  % number of block restrictions in each home equation
-%bhom = zeros(nhbres,k);  % each home equation
-%cnt=0;
-%for ki = 1:lags
-%   for kj=1:length(rfvindx)
-%      cnt=cnt+1;
-%      bhom(cnt,nvar*(ki-1)+rfvindx(kj)) = 1;
-%   end
-%end
-%%
-%if cnt~=nhbres
-%   error('Check lagged restrictions in domestic equations!')
-%end
-%%
-%for kj=dlrindx
-%   Ri(1:nhbres,:,kj) = bhom;
-%end
-
-
-for n=1:nvar   %  initializing loop for each equation
-   Ui{n} = null(Qi(:,:,n));
-   Vi{n} = null(Ri(:,:,n));
-   n0(n) = size(Ui{n},2);
-   np(n) = size(Vi{n},2);
-end
-
-
-
-%(2)-------------------------------------------------------------
-%  Cross-A0-and-A+ rerestrictions one quation at a time
-%    i.e., the first, second, ..., kjth, ..., equation
-%(2)-------------------------------------------------------------
-%
-if indxC0Pres
-   neq_cres = 3;   % the number of equations in which cross-A0-A+ restrictions occur.
-   ixmC0Pres = cell(neq_cres,1);  % in each cell representing equation, we have 4 columns:
-           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
-           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
-   %** 1st equation
-   ixmC0Pres{1} = [1 2 2 1
-                   1 7 1 1];
-   %** 2nd equation
-   ixmC0Pres{2} = [2 2 2 2];
-   %** 3rd equation
-   ixmC0Pres{3} = [3 7 1 1
-                   3 2 2 1];
-
-
-%         % 4 columns.
-%   ncres = 5;  % manually key in the number of cross-A0-A+ restrictions
-
-%           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
-%           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-%           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-%           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
-else
-   ixmC0Pres = NaN;
-end
-
+function [Ui,Vi,n0,np,ixmC0Pres] = ftd_upperchol4v(lags,nvar,nexo,indxC0Pres)
+%  vlist = [127 124 93 141 21];    % 1: GDP; 2: GDP deflator 124 (consumption deflator 79); 3: R; 4: M3 141 (M2 140); 5: exchange rate 21.
+%  varlist={'y', 'P', 'R', 'M3', 'Ex'};
+%
+%    Exporting orthonormal matrices for the deterministic linear restrictions (equation by equation)
+%    See Waggoner and Zha's Gibbs sampling paper.
+%
+% q_m:  quarter or month
+% lags: the maximum length of lag
+% nvar:  number of endogeous variables
+% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant
+% indxC0Pres: index for cross-A0-A+ restrictions.  if 1: cross-A0-and-A+ restrictions; 0: idfile is all we have
+%                Example for indxOres==1: restrictions of the form P(t) = P(t-1).
+%                These restrictions have to be manually and carefully keyed in.
+%-----------------
+% Ui: nvar-by-1 cell.  In each cell, nvar-by-qi orthonormal basis for the null of the ith
+%           equation contemporaneous restriction matrix where qi is the number of free parameters.
+%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
+%           of total original parameters and bi is a vector of free parameters. When no
+%           restrictions are imposed, we have Ui = I.  There must be at least one free
+%           parameter left for the ith equation.
+% Vi: nvar-by-1 cell.  In each cell, k-by-ri orthonormal basis for the null of the ith
+%           equation lagged restriction matrix where k is a total of exogenous variables and
+%           ri is the number of free parameters. With this transformation, we have fi = Vi*gi
+%           or Vi'*fi = gi where fi is a vector of total original parameters and gi is a
+%           vector of free parameters. There must be at least one free parameter left for
+%           the ith equation.
+% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation
+% np: nvar-by-1, ith element represents the number of free A+ parameters in ith equation
+% ixmC0Pres:  neq_cres-by-1 cell.  Effective only if indxC0Pres=1, otherwise equals NaN.
+%             neq_cres is the number of equations in which cross-A0-A+ restrictions occur.
+%             In the jth cell representing equation, we have 4 columns:
+%               1st: the jth column (equation) of A+ or A0: f_j or a_j
+%               2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+%               3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+%               4th: the number s such that f_j(i) = s * a_j(h) holds.
+%
+% Tao Zha, May 2000
+
+
+
+Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
+Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
+n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation
+np = zeros(nvar,1); % ith element represents the number of free A+ parameters in ith equation
+
+if (nargin==2)
+   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
+elseif (nargin==3)
+   indxC0Pres = 0;  % default is no cross-A0-and-A+ restrictions.
+end
+
+k = lags*nvar+nexo;  % maximum number of lagged and exogenous variables in each equation
+
+Qi = zeros(nvar,nvar,nvar);   % for nvar contemporaneous equations
+Ri = zeros(k,k,nvar);    % for nvar lagged and exogenous equations
+  % Row corresponds to equation. 0 means no restriction.
+  %                              1 means exclusion restriction such that the corresponding parameter is restricted to 0.
+
+%nfvar = 6;   % number of foreign (Granger causing) variables
+%nhvar = nvar-nfvar;  % number of home (affected) variables.
+
+
+%-------------------------------------------------------------
+%  Beginning the manual input of the restrictions one quation at a time
+%-------------------------------------------------------------
+%
+%======== The first equation ===========
+Qi(1:3,:,1) = [
+    0 1 0 0
+    0 0 1 0
+    0 0 0 1
+        ];
+
+%======== The second equation ===========
+Qi(1:2,:,2) = [
+    0 0 1 0
+    0 0 0 1
+        ];
+
+%======== The third equation ===========
+Qi(1:1,:,3) = [
+    0 0 0 1
+        ];
+
+
+%======== The fourth equation ===========
+
+
+
+
+%===== Lagged restrictions in foreign (Granger causing) block
+%nfbres = lags*(nvar-nfvar);  % number of block restrictions in each foreign equation
+%bfor = zeros(nfbres,k);  % each foreign equation
+%cnt=0;
+%for ki = 1:lags
+%   for kj=1:nvar-nfvar
+%      cnt=cnt+1;
+%      bfor(cnt,nvar*(ki-1)+nfvar+kj) = 1;
+%   end
+%end
+%%
+%if cnt~=nfbres
+%   error('Check lagged restrictions in foreign equations!')
+%end
+%%
+%for kj=1:nfvar
+%   Ri(1:nfbres,:,kj) = bfor;
+%end
+
+
+%===== Lagged restrictions in home (affected) block
+%
+%~~~~~ selected domestic equations
+%dlrindx = nfvar+1; %[nfvar+1 nfvar+2];  % index for relevant home equations
+%rfvindx = []; %[6];  %[1 2 3 5];  % index for restricted foreign variables (e.g., Poil, M2, FFR, P).
+%%nf2hvar = nfvar-length(rfvindx);  % number of free parameters -- foreign variables entering the home sector
+%nhbres = lags*length(rfvindx);  % number of block restrictions in each home equation
+%bhom = zeros(nhbres,k);  % each home equation
+%cnt=0;
+%for ki = 1:lags
+%   for kj=1:length(rfvindx)
+%      cnt=cnt+1;
+%      bhom(cnt,nvar*(ki-1)+rfvindx(kj)) = 1;
+%   end
+%end
+%%
+%if cnt~=nhbres
+%   error('Check lagged restrictions in domestic equations!')
+%end
+%%
+%for kj=dlrindx
+%   Ri(1:nhbres,:,kj) = bhom;
+%end
+
+
+for n=1:nvar   %  initializing loop for each equation
+   Ui{n} = null(Qi(:,:,n));
+   Vi{n} = null(Ri(:,:,n));
+   n0(n) = size(Ui{n},2);
+   np(n) = size(Vi{n},2);
+end
+
+
+
+%(2)-------------------------------------------------------------
+%  Cross-A0-and-A+ rerestrictions one quation at a time
+%    i.e., the first, second, ..., kjth, ..., equation
+%(2)-------------------------------------------------------------
+%
+if indxC0Pres
+   neq_cres = 3;   % the number of equations in which cross-A0-A+ restrictions occur.
+   ixmC0Pres = cell(neq_cres,1);  % in each cell representing equation, we have 4 columns:
+           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
+           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
+   %** 1st equation
+   ixmC0Pres{1} = [1 2 2 1
+                   1 7 1 1];
+   %** 2nd equation
+   ixmC0Pres{2} = [2 2 2 2];
+   %** 3rd equation
+   ixmC0Pres{3} = [3 7 1 1
+                   3 2 2 1];
+
+
+%         % 4 columns.
+%   ncres = 5;  % manually key in the number of cross-A0-A+ restrictions
+
+%           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
+%           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+%           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+%           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
+else
+   ixmC0Pres = NaN;
+end
+
diff --git a/tests/ms-sbvar/archive-files/ftd_upperchol5v.m b/tests/ms-sbvar/archive-files/ftd_upperchol5v.m
index e1dfaa18d54e64f0e2073fee6cc65cc5bfd362b4..b41a60c1747dde3075a4d4ae7cac3cc1e3a8cdab 100644
--- a/tests/ms-sbvar/archive-files/ftd_upperchol5v.m
+++ b/tests/ms-sbvar/archive-files/ftd_upperchol5v.m
@@ -1,187 +1,187 @@
-function [Ui,Vi,n0,np,ixmC0Pres] = ftd_upperchol5v(lags,nvar,nexo,indxC0Pres)
-%  vlist = [127 124 93 141 21];    % 1: GDP; 2: GDP deflator 124 (consumption deflator 79); 3: R; 4: M3 141 (M2 140); 5: exchange rate 21.
-%  varlist={'y', 'P', 'R', 'M3', 'Ex'};
-%
-%    Exporting orthonormal matrices for the deterministic linear restrictions (equation by equation)
-%    See Waggoner and Zha's Gibbs sampling paper.
-%
-% q_m:  quarter or month
-% lags: the maximum length of lag
-% nvar:  number of endogeous variables
-% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant
-% indxC0Pres: index for cross-A0-A+ restrictions.  if 1: cross-A0-and-A+ restrictions; 0: idfile is all we have
-%                Example for indxOres==1: restrictions of the form P(t) = P(t-1).
-%                These restrictions have to be manually and carefully keyed in.
-%-----------------
-% Ui: nvar-by-1 cell.  In each cell, nvar-by-qi orthonormal basis for the null of the ith
-%           equation contemporaneous restriction matrix where qi is the number of free parameters.
-%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
-%           of total original parameters and bi is a vector of free parameters. When no
-%           restrictions are imposed, we have Ui = I.  There must be at least one free
-%           parameter left for the ith equation.
-% Vi: nvar-by-1 cell.  In each cell, k-by-ri orthonormal basis for the null of the ith
-%           equation lagged restriction matrix where k is a total of exogenous variables and
-%           ri is the number of free parameters. With this transformation, we have fi = Vi*gi
-%           or Vi'*fi = gi where fi is a vector of total original parameters and gi is a
-%           vector of free parameters. There must be at least one free parameter left for
-%           the ith equation.
-% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation
-% np: nvar-by-1, ith element represents the number of free A+ parameters in ith equation
-% ixmC0Pres:  neq_cres-by-1 cell.  Effective only if indxC0Pres=1, otherwise equals NaN.
-%             neq_cres is the number of equations in which cross-A0-A+ restrictions occur.
-%             In the jth cell representing equation, we have 4 columns:
-%               1st: the jth column (equation) of A+ or A0: f_j or a_j
-%               2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-%               3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-%               4th: the number s such that f_j(i) = s * a_j(h) holds.
-%
-% Tao Zha, May 2000
-
-
-
-Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
-Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
-n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation
-np = zeros(nvar,1); % ith element represents the number of free A+ parameters in ith equation
-
-if (nargin==2)
-   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
-elseif (nargin==3)
-   indxC0Pres = 0;  % default is no cross-A0-and-A+ restrictions.
-end
-
-k = lags*nvar+nexo;  % maximum number of lagged and exogenous variables in each equation
-
-Qi = zeros(nvar,nvar,nvar);   % for nvar contemporaneous equations
-Ri = zeros(k,k,nvar);    % for nvar lagged and exogenous equations
-  % Row corresponds to equation. 0 means no restriction.
-  %                              1 means exclusion restriction such that the corresponding parameter is restricted to 0.
-
-%nfvar = 6;   % number of foreign (Granger causing) variables
-%nhvar = nvar-nfvar;  % number of home (affected) variables.
-
-
-%-------------------------------------------------------------
-%  Beginning the manual input of the restrictions one quation at a time
-%-------------------------------------------------------------
-%
-%======== The first equation ===========
-Qi(1:4,:,1) = [
-    0 1 0 0 0
-    0 0 1 0 0
-    0 0 0 1 0
-    0 0 0 0 1
-        ];
-
-%======== The second equation ===========
-Qi(1:3,:,2) = [
-    0 0 1 0 0
-    0 0 0 1 0
-    0 0 0 0 1
-        ];
-
-%======== The third equation ===========
-Qi(1:2,:,3) = [
-    0 0 0 1 0
-    0 0 0 0 1
-        ];
-
-
-%======== The fourth equation ===========
-Qi(1:1,:,4) = [
-    0 0 0 0 1
-         ];
-
-
-%======== The fifth equation ===========
-
-
-
-
-%===== Lagged restrictions in foreign (Granger causing) block
-%nfbres = lags*(nvar-nfvar);  % number of block restrictions in each foreign equation
-%bfor = zeros(nfbres,k);  % each foreign equation
-%cnt=0;
-%for ki = 1:lags
-%   for kj=1:nvar-nfvar
-%      cnt=cnt+1;
-%      bfor(cnt,nvar*(ki-1)+nfvar+kj) = 1;
-%   end
-%end
-%%
-%if cnt~=nfbres
-%   error('Check lagged restrictions in foreign equations!')
-%end
-%%
-%for kj=1:nfvar
-%   Ri(1:nfbres,:,kj) = bfor;
-%end
-
-
-%===== Lagged restrictions in home (affected) block
-%
-%~~~~~ selected domestic equations
-%dlrindx = nfvar+1; %[nfvar+1 nfvar+2];  % index for relevant home equations
-%rfvindx = []; %[6];  %[1 2 3 5];  % index for restricted foreign variables (e.g., Poil, M2, FFR, P).
-%%nf2hvar = nfvar-length(rfvindx);  % number of free parameters -- foreign variables entering the home sector
-%nhbres = lags*length(rfvindx);  % number of block restrictions in each home equation
-%bhom = zeros(nhbres,k);  % each home equation
-%cnt=0;
-%for ki = 1:lags
-%   for kj=1:length(rfvindx)
-%      cnt=cnt+1;
-%      bhom(cnt,nvar*(ki-1)+rfvindx(kj)) = 1;
-%   end
-%end
-%%
-%if cnt~=nhbres
-%   error('Check lagged restrictions in domestic equations!')
-%end
-%%
-%for kj=dlrindx
-%   Ri(1:nhbres,:,kj) = bhom;
-%end
-
-
-for n=1:nvar   %  initializing loop for each equation
-   Ui{n} = null(Qi(:,:,n));
-   Vi{n} = null(Ri(:,:,n));
-   n0(n) = size(Ui{n},2);
-   np(n) = size(Vi{n},2);
-end
-
-
-
-%(2)-------------------------------------------------------------
-%  Cross-A0-and-A+ rerestrictions one quation at a time
-%    i.e., the first, second, ..., kjth, ..., equation
-%(2)-------------------------------------------------------------
-%
-if indxC0Pres
-   neq_cres = 3;   % the number of equations in which cross-A0-A+ restrictions occur.
-   ixmC0Pres = cell(neq_cres,1);  % in each cell representing equation, we have 4 columns:
-           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
-           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
-   %** 1st equation
-   ixmC0Pres{1} = [1 2 2 1
-                   1 7 1 1];
-   %** 2nd equation
-   ixmC0Pres{2} = [2 2 2 2];
-   %** 3rd equation
-   ixmC0Pres{3} = [3 7 1 1
-                   3 2 2 1];
-
-
-%         % 4 columns.
-%   ncres = 5;  % manually key in the number of cross-A0-A+ restrictions
-
-%           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
-%           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-%           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-%           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
-else
-   ixmC0Pres = NaN;
-end
-
+function [Ui,Vi,n0,np,ixmC0Pres] = ftd_upperchol5v(lags,nvar,nexo,indxC0Pres)
+%  vlist = [127 124 93 141 21];    % 1: GDP; 2: GDP deflator 124 (consumption deflator 79); 3: R; 4: M3 141 (M2 140); 5: exchange rate 21.
+%  varlist={'y', 'P', 'R', 'M3', 'Ex'};
+%
+%    Exporting orthonormal matrices for the deterministic linear restrictions (equation by equation)
+%    See Waggoner and Zha's Gibbs sampling paper.
+%
+% q_m:  quarter or month
+% lags: the maximum length of lag
+% nvar:  number of endogeous variables
+% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant
+% indxC0Pres: index for cross-A0-A+ restrictions.  if 1: cross-A0-and-A+ restrictions; 0: idfile is all we have
+%                Example for indxOres==1: restrictions of the form P(t) = P(t-1).
+%                These restrictions have to be manually and carefully keyed in.
+%-----------------
+% Ui: nvar-by-1 cell.  In each cell, nvar-by-qi orthonormal basis for the null of the ith
+%           equation contemporaneous restriction matrix where qi is the number of free parameters.
+%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
+%           of total original parameters and bi is a vector of free parameters. When no
+%           restrictions are imposed, we have Ui = I.  There must be at least one free
+%           parameter left for the ith equation.
+% Vi: nvar-by-1 cell.  In each cell, k-by-ri orthonormal basis for the null of the ith
+%           equation lagged restriction matrix where k is a total of exogenous variables and
+%           ri is the number of free parameters. With this transformation, we have fi = Vi*gi
+%           or Vi'*fi = gi where fi is a vector of total original parameters and gi is a
+%           vector of free parameters. There must be at least one free parameter left for
+%           the ith equation.
+% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation
+% np: nvar-by-1, ith element represents the number of free A+ parameters in ith equation
+% ixmC0Pres:  neq_cres-by-1 cell.  Effective only if indxC0Pres=1, otherwise equals NaN.
+%             neq_cres is the number of equations in which cross-A0-A+ restrictions occur.
+%             In the jth cell representing equation, we have 4 columns:
+%               1st: the jth column (equation) of A+ or A0: f_j or a_j
+%               2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+%               3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+%               4th: the number s such that f_j(i) = s * a_j(h) holds.
+%
+% Tao Zha, May 2000
+
+
+
+Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
+Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
+n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation
+np = zeros(nvar,1); % ith element represents the number of free A+ parameters in ith equation
+
+if (nargin==2)
+   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
+elseif (nargin==3)
+   indxC0Pres = 0;  % default is no cross-A0-and-A+ restrictions.
+end
+
+k = lags*nvar+nexo;  % maximum number of lagged and exogenous variables in each equation
+
+Qi = zeros(nvar,nvar,nvar);   % for nvar contemporaneous equations
+Ri = zeros(k,k,nvar);    % for nvar lagged and exogenous equations
+  % Row corresponds to equation. 0 means no restriction.
+  %                              1 means exclusion restriction such that the corresponding parameter is restricted to 0.
+
+%nfvar = 6;   % number of foreign (Granger causing) variables
+%nhvar = nvar-nfvar;  % number of home (affected) variables.
+
+
+%-------------------------------------------------------------
+%  Beginning the manual input of the restrictions one quation at a time
+%-------------------------------------------------------------
+%
+%======== The first equation ===========
+Qi(1:4,:,1) = [
+    0 1 0 0 0
+    0 0 1 0 0
+    0 0 0 1 0
+    0 0 0 0 1
+        ];
+
+%======== The second equation ===========
+Qi(1:3,:,2) = [
+    0 0 1 0 0
+    0 0 0 1 0
+    0 0 0 0 1
+        ];
+
+%======== The third equation ===========
+Qi(1:2,:,3) = [
+    0 0 0 1 0
+    0 0 0 0 1
+        ];
+
+
+%======== The fourth equation ===========
+Qi(1:1,:,4) = [
+    0 0 0 0 1
+         ];
+
+
+%======== The fifth equation ===========
+
+
+
+
+%===== Lagged restrictions in foreign (Granger causing) block
+%nfbres = lags*(nvar-nfvar);  % number of block restrictions in each foreign equation
+%bfor = zeros(nfbres,k);  % each foreign equation
+%cnt=0;
+%for ki = 1:lags
+%   for kj=1:nvar-nfvar
+%      cnt=cnt+1;
+%      bfor(cnt,nvar*(ki-1)+nfvar+kj) = 1;
+%   end
+%end
+%%
+%if cnt~=nfbres
+%   error('Check lagged restrictions in foreign equations!')
+%end
+%%
+%for kj=1:nfvar
+%   Ri(1:nfbres,:,kj) = bfor;
+%end
+
+
+%===== Lagged restrictions in home (affected) block
+%
+%~~~~~ selected domestic equations
+%dlrindx = nfvar+1; %[nfvar+1 nfvar+2];  % index for relevant home equations
+%rfvindx = []; %[6];  %[1 2 3 5];  % index for restricted foreign variables (e.g., Poil, M2, FFR, P).
+%%nf2hvar = nfvar-length(rfvindx);  % number of free parameters -- foreign variables entering the home sector
+%nhbres = lags*length(rfvindx);  % number of block restrictions in each home equation
+%bhom = zeros(nhbres,k);  % each home equation
+%cnt=0;
+%for ki = 1:lags
+%   for kj=1:length(rfvindx)
+%      cnt=cnt+1;
+%      bhom(cnt,nvar*(ki-1)+rfvindx(kj)) = 1;
+%   end
+%end
+%%
+%if cnt~=nhbres
+%   error('Check lagged restrictions in domestic equations!')
+%end
+%%
+%for kj=dlrindx
+%   Ri(1:nhbres,:,kj) = bhom;
+%end
+
+
+for n=1:nvar   %  initializing loop for each equation
+   Ui{n} = null(Qi(:,:,n));
+   Vi{n} = null(Ri(:,:,n));
+   n0(n) = size(Ui{n},2);
+   np(n) = size(Vi{n},2);
+end
+
+
+
+%(2)-------------------------------------------------------------
+%  Cross-A0-and-A+ rerestrictions one quation at a time
+%    i.e., the first, second, ..., kjth, ..., equation
+%(2)-------------------------------------------------------------
+%
+if indxC0Pres
+   neq_cres = 3;   % the number of equations in which cross-A0-A+ restrictions occur.
+   ixmC0Pres = cell(neq_cres,1);  % in each cell representing equation, we have 4 columns:
+           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
+           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
+   %** 1st equation
+   ixmC0Pres{1} = [1 2 2 1
+                   1 7 1 1];
+   %** 2nd equation
+   ixmC0Pres{2} = [2 2 2 2];
+   %** 3rd equation
+   ixmC0Pres{3} = [3 7 1 1
+                   3 2 2 1];
+
+
+%         % 4 columns.
+%   ncres = 5;  % manually key in the number of cross-A0-A+ restrictions
+
+%           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
+%           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+%           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+%           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
+else
+   ixmC0Pres = NaN;
+end
+
diff --git a/tests/ms-sbvar/archive-files/ftd_upperchol6v.m b/tests/ms-sbvar/archive-files/ftd_upperchol6v.m
index fb09e9298fc941716655b156f2ce718d488a48d7..c6560ffd986fccb13b4e8e499f434512d612b16e 100644
--- a/tests/ms-sbvar/archive-files/ftd_upperchol6v.m
+++ b/tests/ms-sbvar/archive-files/ftd_upperchol6v.m
@@ -1,194 +1,194 @@
-function [Ui,Vi,n0,np,ixmC0Pres] = ftd_upperchol6v(lags,nvar,nexo,indxC0Pres)
-%  vlist = [127 124 2 93 141 21];    % 1: Pcom 2 (exchange rate 21); 2: M3 141 (M2 140); 3: R; 4: GDP; 5: GDP deflator 124 (consumption deflator 79).
-%  varlist={'y', 'P', 'Pcom', 'R', 'M3', 'Ex'};
-%
-%    Exporting orthonormal matrices for the deterministic linear restrictions (equation by equation)
-%    See Waggoner and Zha's Gibbs sampling paper.
-%
-% q_m:  quarter or month
-% lags: the maximum length of lag
-% nvar:  number of endogeous variables
-% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant
-% indxC0Pres: index for cross-A0-A+ restrictions.  if 1: cross-A0-and-A+ restrictions; 0: idfile is all we have
-%                Example for indxOres==1: restrictions of the form P(t) = P(t-1).
-%                These restrictions have to be manually and carefully keyed in.
-%-----------------
-% Ui: nvar-by-1 cell.  In each cell, nvar-by-qi orthonormal basis for the null of the ith
-%           equation contemporaneous restriction matrix where qi is the number of free parameters.
-%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
-%           of total original parameters and bi is a vector of free parameters. When no
-%           restrictions are imposed, we have Ui = I.  There must be at least one free
-%           parameter left for the ith equation.
-% Vi: nvar-by-1 cell.  In each cell, k-by-ri orthonormal basis for the null of the ith
-%           equation lagged restriction matrix where k is a total of exogenous variables and
-%           ri is the number of free parameters. With this transformation, we have fi = Vi*gi
-%           or Vi'*fi = gi where fi is a vector of total original parameters and gi is a
-%           vector of free parameters. There must be at least one free parameter left for
-%           the ith equation.
-% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation
-% np: nvar-by-1, ith element represents the number of free A+ parameters in ith equation
-% ixmC0Pres:  neq_cres-by-1 cell.  Effective only if indxC0Pres=1, otherwise equals NaN.
-%             neq_cres is the number of equations in which cross-A0-A+ restrictions occur.
-%             In the jth cell representing equation, we have 4 columns:
-%               1st: the jth column (equation) of A+ or A0: f_j or a_j
-%               2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-%               3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-%               4th: the number s such that f_j(i) = s * a_j(h) holds.
-%
-% Tao Zha, May 2000
-
-
-
-Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
-Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
-n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation
-np = zeros(nvar,1); % ith element represents the number of free A+ parameters in ith equation
-
-if (nargin==2)
-   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
-elseif (nargin==3)
-   indxC0Pres = 0;  % default is no cross-A0-and-A+ restrictions.
-end
-
-k = lags*nvar+nexo;  % maximum number of lagged and exogenous variables in each equation
-
-Qi = zeros(nvar,nvar,nvar);   % for nvar contemporaneous equations
-Ri = zeros(k,k,nvar);    % for nvar lagged and exogenous equations
-  % Row corresponds to equation. 0 means no restriction.
-  %                              1 means exclusion restriction such that the corresponding parameter is restricted to 0.
-
-%nfvar = 6;   % number of foreign (Granger causing) variables
-%nhvar = nvar-nfvar;  % number of home (affected) variables.
-
-
-%-------------------------------------------------------------
-%  Beginning the manual input of the restrictions one quation at a time
-%-------------------------------------------------------------
-%
-%======== The first equation ===========
-Qi(1:5,:,1) = [
-    0 1 0 0 0 0
-    0 0 1 0 0 0
-    0 0 0 1 0 0
-    0 0 0 0 1 0
-    0 0 0 0 0 1
-        ];
-
-%======== The second equation ===========
-Qi(1:4,:,2) = [
-    0 0 1 0 0 0
-    0 0 0 1 0 0
-    0 0 0 0 1 0
-    0 0 0 0 0 1
-        ];
-
-%======== The third equation ===========
-Qi(1:3,:,3) = [
-    0 0 0 1 0 0
-    0 0 0 0 1 0
-    0 0 0 0 0 1
-        ];
-
-
-%======== The fourth equation ===========
-Qi(1:2,:,4) = [
-    0 0 0 0 1 0
-    0 0 0 0 0 1
-         ];
-
-
-%======== The fifth equation ===========
-Qi(1:1,:,5) = [
-    0 0 0 0 0 1
-         ];
-
-
-%======== The sixth equation ===========
-
-%===== Lagged restrictions in foreign (Granger causing) block
-%nfbres = lags*(nvar-nfvar);  % number of block restrictions in each foreign equation
-%bfor = zeros(nfbres,k);  % each foreign equation
-%cnt=0;
-%for ki = 1:lags
-%   for kj=1:nvar-nfvar
-%      cnt=cnt+1;
-%      bfor(cnt,nvar*(ki-1)+nfvar+kj) = 1;
-%   end
-%end
-%%
-%if cnt~=nfbres
-%   error('Check lagged restrictions in foreign equations!')
-%end
-%%
-%for kj=1:nfvar
-%   Ri(1:nfbres,:,kj) = bfor;
-%end
-
-
-%===== Lagged restrictions in home (affected) block
-%
-%~~~~~ selected domestic equations
-%dlrindx = nfvar+1; %[nfvar+1 nfvar+2];  % index for relevant home equations
-%rfvindx = []; %[6];  %[1 2 3 5];  % index for restricted foreign variables (e.g., Poil, M2, FFR, P).
-%%nf2hvar = nfvar-length(rfvindx);  % number of free parameters -- foreign variables entering the home sector
-%nhbres = lags*length(rfvindx);  % number of block restrictions in each home equation
-%bhom = zeros(nhbres,k);  % each home equation
-%cnt=0;
-%for ki = 1:lags
-%   for kj=1:length(rfvindx)
-%      cnt=cnt+1;
-%      bhom(cnt,nvar*(ki-1)+rfvindx(kj)) = 1;
-%   end
-%end
-%%
-%if cnt~=nhbres
-%   error('Check lagged restrictions in domestic equations!')
-%end
-%%
-%for kj=dlrindx
-%   Ri(1:nhbres,:,kj) = bhom;
-%end
-
-
-for n=1:nvar   %  initializing loop for each equation
-   Ui{n} = null(Qi(:,:,n));
-   Vi{n} = null(Ri(:,:,n));
-   n0(n) = size(Ui{n},2);
-   np(n) = size(Vi{n},2);
-end
-
-
-
-%(2)-------------------------------------------------------------
-%  Cross-A0-and-A+ rerestrictions one quation at a time
-%    i.e., the first, second, ..., kjth, ..., equation
-%(2)-------------------------------------------------------------
-%
-if indxC0Pres
-   neq_cres = 3;   % the number of equations in which cross-A0-A+ restrictions occur.
-   ixmC0Pres = cell(neq_cres,1);  % in each cell representing equation, we have 4 columns:
-           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
-           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
-   %** 1st equation
-   ixmC0Pres{1} = [1 2 2 1
-                   1 7 1 1];
-   %** 2nd equation
-   ixmC0Pres{2} = [2 2 2 2];
-   %** 3rd equation
-   ixmC0Pres{3} = [3 7 1 1
-                   3 2 2 1];
-
-
-%         % 4 columns.
-%   ncres = 5;  % manually key in the number of cross-A0-A+ restrictions
-
-%           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
-%           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-%           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-%           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
-else
-   ixmC0Pres = NaN;
-end
-
+function [Ui,Vi,n0,np,ixmC0Pres] = ftd_upperchol6v(lags,nvar,nexo,indxC0Pres)
+%  vlist = [127 124 2 93 141 21];    % 1: Pcom 2 (exchange rate 21); 2: M3 141 (M2 140); 3: R; 4: GDP; 5: GDP deflator 124 (consumption deflator 79).
+%  varlist={'y', 'P', 'Pcom', 'R', 'M3', 'Ex'};
+%
+%    Exporting orthonormal matrices for the deterministic linear restrictions (equation by equation)
+%    See Waggoner and Zha's Gibbs sampling paper.
+%
+% q_m:  quarter or month
+% lags: the maximum length of lag
+% nvar:  number of endogeous variables
+% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant
+% indxC0Pres: index for cross-A0-A+ restrictions.  if 1: cross-A0-and-A+ restrictions; 0: idfile is all we have
+%                Example for indxOres==1: restrictions of the form P(t) = P(t-1).
+%                These restrictions have to be manually and carefully keyed in.
+%-----------------
+% Ui: nvar-by-1 cell.  In each cell, nvar-by-qi orthonormal basis for the null of the ith
+%           equation contemporaneous restriction matrix where qi is the number of free parameters.
+%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
+%           of total original parameters and bi is a vector of free parameters. When no
+%           restrictions are imposed, we have Ui = I.  There must be at least one free
+%           parameter left for the ith equation.
+% Vi: nvar-by-1 cell.  In each cell, k-by-ri orthonormal basis for the null of the ith
+%           equation lagged restriction matrix where k is a total of exogenous variables and
+%           ri is the number of free parameters. With this transformation, we have fi = Vi*gi
+%           or Vi'*fi = gi where fi is a vector of total original parameters and gi is a
+%           vector of free parameters. There must be at least one free parameter left for
+%           the ith equation.
+% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation
+% np: nvar-by-1, ith element represents the number of free A+ parameters in ith equation
+% ixmC0Pres:  neq_cres-by-1 cell.  Effective only if indxC0Pres=1, otherwise equals NaN.
+%             neq_cres is the number of equations in which cross-A0-A+ restrictions occur.
+%             In the jth cell representing equation, we have 4 columns:
+%               1st: the jth column (equation) of A+ or A0: f_j or a_j
+%               2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+%               3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+%               4th: the number s such that f_j(i) = s * a_j(h) holds.
+%
+% Tao Zha, May 2000
+
+
+
+Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
+Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
+n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation
+np = zeros(nvar,1); % ith element represents the number of free A+ parameters in ith equation
+
+if (nargin==2)
+   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
+elseif (nargin==3)
+   indxC0Pres = 0;  % default is no cross-A0-and-A+ restrictions.
+end
+
+k = lags*nvar+nexo;  % maximum number of lagged and exogenous variables in each equation
+
+Qi = zeros(nvar,nvar,nvar);   % for nvar contemporaneous equations
+Ri = zeros(k,k,nvar);    % for nvar lagged and exogenous equations
+  % Row corresponds to equation. 0 means no restriction.
+  %                              1 means exclusion restriction such that the corresponding parameter is restricted to 0.
+
+%nfvar = 6;   % number of foreign (Granger causing) variables
+%nhvar = nvar-nfvar;  % number of home (affected) variables.
+
+
+%-------------------------------------------------------------
+%  Beginning the manual input of the restrictions one quation at a time
+%-------------------------------------------------------------
+%
+%======== The first equation ===========
+Qi(1:5,:,1) = [
+    0 1 0 0 0 0
+    0 0 1 0 0 0
+    0 0 0 1 0 0
+    0 0 0 0 1 0
+    0 0 0 0 0 1
+        ];
+
+%======== The second equation ===========
+Qi(1:4,:,2) = [
+    0 0 1 0 0 0
+    0 0 0 1 0 0
+    0 0 0 0 1 0
+    0 0 0 0 0 1
+        ];
+
+%======== The third equation ===========
+Qi(1:3,:,3) = [
+    0 0 0 1 0 0
+    0 0 0 0 1 0
+    0 0 0 0 0 1
+        ];
+
+
+%======== The fourth equation ===========
+Qi(1:2,:,4) = [
+    0 0 0 0 1 0
+    0 0 0 0 0 1
+         ];
+
+
+%======== The fifth equation ===========
+Qi(1:1,:,5) = [
+    0 0 0 0 0 1
+         ];
+
+
+%======== The sixth equation ===========
+
+%===== Lagged restrictions in foreign (Granger causing) block
+%nfbres = lags*(nvar-nfvar);  % number of block restrictions in each foreign equation
+%bfor = zeros(nfbres,k);  % each foreign equation
+%cnt=0;
+%for ki = 1:lags
+%   for kj=1:nvar-nfvar
+%      cnt=cnt+1;
+%      bfor(cnt,nvar*(ki-1)+nfvar+kj) = 1;
+%   end
+%end
+%%
+%if cnt~=nfbres
+%   error('Check lagged restrictions in foreign equations!')
+%end
+%%
+%for kj=1:nfvar
+%   Ri(1:nfbres,:,kj) = bfor;
+%end
+
+
+%===== Lagged restrictions in home (affected) block
+%
+%~~~~~ selected domestic equations
+%dlrindx = nfvar+1; %[nfvar+1 nfvar+2];  % index for relevant home equations
+%rfvindx = []; %[6];  %[1 2 3 5];  % index for restricted foreign variables (e.g., Poil, M2, FFR, P).
+%%nf2hvar = nfvar-length(rfvindx);  % number of free parameters -- foreign variables entering the home sector
+%nhbres = lags*length(rfvindx);  % number of block restrictions in each home equation
+%bhom = zeros(nhbres,k);  % each home equation
+%cnt=0;
+%for ki = 1:lags
+%   for kj=1:length(rfvindx)
+%      cnt=cnt+1;
+%      bhom(cnt,nvar*(ki-1)+rfvindx(kj)) = 1;
+%   end
+%end
+%%
+%if cnt~=nhbres
+%   error('Check lagged restrictions in domestic equations!')
+%end
+%%
+%for kj=dlrindx
+%   Ri(1:nhbres,:,kj) = bhom;
+%end
+
+
+for n=1:nvar   %  initializing loop for each equation
+   Ui{n} = null(Qi(:,:,n));
+   Vi{n} = null(Ri(:,:,n));
+   n0(n) = size(Ui{n},2);
+   np(n) = size(Vi{n},2);
+end
+
+
+
+%(2)-------------------------------------------------------------
+%  Cross-A0-and-A+ rerestrictions one quation at a time
+%    i.e., the first, second, ..., kjth, ..., equation
+%(2)-------------------------------------------------------------
+%
+if indxC0Pres
+   neq_cres = 3;   % the number of equations in which cross-A0-A+ restrictions occur.
+   ixmC0Pres = cell(neq_cres,1);  % in each cell representing equation, we have 4 columns:
+           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
+           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
+   %** 1st equation
+   ixmC0Pres{1} = [1 2 2 1
+                   1 7 1 1];
+   %** 2nd equation
+   ixmC0Pres{2} = [2 2 2 2];
+   %** 3rd equation
+   ixmC0Pres{3} = [3 7 1 1
+                   3 2 2 1];
+
+
+%         % 4 columns.
+%   ncres = 5;  % manually key in the number of cross-A0-A+ restrictions
+
+%           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
+%           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+%           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+%           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
+else
+   ixmC0Pres = NaN;
+end
+
diff --git a/tests/ms-sbvar/archive-files/ftd_upperchol7v.m b/tests/ms-sbvar/archive-files/ftd_upperchol7v.m
index 31ce836cf09fce94fac0f42e615fa629fac65717..d0dc7969c4bc3d435bc427a6c62300a24584a9c9 100644
--- a/tests/ms-sbvar/archive-files/ftd_upperchol7v.m
+++ b/tests/ms-sbvar/archive-files/ftd_upperchol7v.m
@@ -1,204 +1,204 @@
-function [Ui,Vi,n0,np,ixmC0Pres] = ftd_upperchol7v(lags,nvar,nexo,indxC0Pres)
-%  vlist = [127 124 2 93 141 21];    % 1: Pcom 2 (exchange rate 21); 2: M3 141 (M2 140); 3: R; 4: GDP; 5: GDP deflator 124 (consumption deflator 79).
-%  varlist={'y', 'P', 'Pcom', 'R', 'M3', 'Ex'};
-%
-%    Exporting orthonormal matrices for the deterministic linear restrictions (equation by equation)
-%    See Waggoner and Zha's Gibbs sampling paper.
-%
-% q_m:  quarter or month
-% lags: the maximum length of lag
-% nvar:  number of endogeous variables
-% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant
-% indxC0Pres: index for cross-A0-A+ restrictions.  if 1: cross-A0-and-A+ restrictions; 0: idfile is all we have
-%                Example for indxOres==1: restrictions of the form P(t) = P(t-1).
-%                These restrictions have to be manually and carefully keyed in.
-%-----------------
-% Ui: nvar-by-1 cell.  In each cell, nvar-by-qi orthonormal basis for the null of the ith
-%           equation contemporaneous restriction matrix where qi is the number of free parameters.
-%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
-%           of total original parameters and bi is a vector of free parameters. When no
-%           restrictions are imposed, we have Ui = I.  There must be at least one free
-%           parameter left for the ith equation.
-% Vi: nvar-by-1 cell.  In each cell, k-by-ri orthonormal basis for the null of the ith
-%           equation lagged restriction matrix where k is a total of exogenous variables and
-%           ri is the number of free parameters. With this transformation, we have fi = Vi*gi
-%           or Vi'*fi = gi where fi is a vector of total original parameters and gi is a
-%           vector of free parameters. There must be at least one free parameter left for
-%           the ith equation.
-% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation
-% np: nvar-by-1, ith element represents the number of free A+ parameters in ith equation
-% ixmC0Pres:  neq_cres-by-1 cell.  Effective only if indxC0Pres=1, otherwise equals NaN.
-%             neq_cres is the number of equations in which cross-A0-A+ restrictions occur.
-%             In the jth cell representing equation, we have 4 columns:
-%               1st: the jth column (equation) of A+ or A0: f_j or a_j
-%               2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-%               3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-%               4th: the number s such that f_j(i) = s * a_j(h) holds.
-%
-% Tao Zha, May 2000
-
-
-
-Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
-Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
-n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation
-np = zeros(nvar,1); % ith element represents the number of free A+ parameters in ith equation
-
-if (nargin==2)
-   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
-elseif (nargin==3)
-   indxC0Pres = 0;  % default is no cross-A0-and-A+ restrictions.
-end
-
-k = lags*nvar+nexo;  % maximum number of lagged and exogenous variables in each equation
-
-Qi = zeros(nvar,nvar,nvar);   % for nvar contemporaneous equations
-Ri = zeros(k,k,nvar);    % for nvar lagged and exogenous equations
-  % Row corresponds to equation. 0 means no restriction.
-  %                              1 means exclusion restriction such that the corresponding parameter is restricted to 0.
-
-%nfvar = 6;   % number of foreign (Granger causing) variables
-%nhvar = nvar-nfvar;  % number of home (affected) variables.
-
-
-%-------------------------------------------------------------
-%  Beginning the manual input of the restrictions one quation at a time
-%-------------------------------------------------------------
-%
-%======== The first equation ===========
-Qi(1:6,:,1) = [
-    0 1 0 0 0 0 0
-    0 0 1 0 0 0 0
-    0 0 0 1 0 0 0
-    0 0 0 0 1 0 0
-    0 0 0 0 0 1 0
-    0 0 0 0 0 0 1
-        ];
-
-%======== The second equation ===========
-Qi(1:5,:,2) = [
-    0 0 1 0 0 0 0
-    0 0 0 1 0 0 0
-    0 0 0 0 1 0 0
-    0 0 0 0 0 1 0
-    0 0 0 0 0 0 1
-        ];
-
-%======== The third equation ===========
-Qi(1:4,:,3) = [
-    0 0 0 1 0 0 0
-    0 0 0 0 1 0 0
-    0 0 0 0 0 1 0
-    0 0 0 0 0 0 1
-        ];
-
-%======== The fourth equation ===========
-Qi(1:3,:,4) = [
-    0 0 0 0 1 0 0
-    0 0 0 0 0 1 0
-    0 0 0 0 0 0 1
-        ];
-
-
-%======== The fifth equation ===========
-Qi(1:2,:,5) = [
-    0 0 0 0 0 1 0
-    0 0 0 0 0 0 1
-         ];
-
-
-%======== The sixth equation ===========
-Qi(1:1,:,6) = [
-    0 0 0 0 0 0 1
-         ];
-
-
-%======== The seventh equation ===========
-
-%===== Lagged restrictions in foreign (Granger causing) block
-%nfbres = lags*(nvar-nfvar);  % number of block restrictions in each foreign equation
-%bfor = zeros(nfbres,k);  % each foreign equation
-%cnt=0;
-%for ki = 1:lags
-%   for kj=1:nvar-nfvar
-%      cnt=cnt+1;
-%      bfor(cnt,nvar*(ki-1)+nfvar+kj) = 1;
-%   end
-%end
-%%
-%if cnt~=nfbres
-%   error('Check lagged restrictions in foreign equations!')
-%end
-%%
-%for kj=1:nfvar
-%   Ri(1:nfbres,:,kj) = bfor;
-%end
-
-
-%===== Lagged restrictions in home (affected) block
-%
-%~~~~~ selected domestic equations
-%dlrindx = nfvar+1; %[nfvar+1 nfvar+2];  % index for relevant home equations
-%rfvindx = []; %[6];  %[1 2 3 5];  % index for restricted foreign variables (e.g., Poil, M2, FFR, P).
-%%nf2hvar = nfvar-length(rfvindx);  % number of free parameters -- foreign variables entering the home sector
-%nhbres = lags*length(rfvindx);  % number of block restrictions in each home equation
-%bhom = zeros(nhbres,k);  % each home equation
-%cnt=0;
-%for ki = 1:lags
-%   for kj=1:length(rfvindx)
-%      cnt=cnt+1;
-%      bhom(cnt,nvar*(ki-1)+rfvindx(kj)) = 1;
-%   end
-%end
-%%
-%if cnt~=nhbres
-%   error('Check lagged restrictions in domestic equations!')
-%end
-%%
-%for kj=dlrindx
-%   Ri(1:nhbres,:,kj) = bhom;
-%end
-
-
-for n=1:nvar   %  initializing loop for each equation
-   Ui{n} = null(Qi(:,:,n));
-   Vi{n} = null(Ri(:,:,n));
-   n0(n) = size(Ui{n},2);
-   np(n) = size(Vi{n},2);
-end
-
-
-
-%(2)-------------------------------------------------------------
-%  Cross-A0-and-A+ rerestrictions one quation at a time
-%    i.e., the first, second, ..., kjth, ..., equation
-%(2)-------------------------------------------------------------
-%
-if indxC0Pres
-   neq_cres = 3;   % the number of equations in which cross-A0-A+ restrictions occur.
-   ixmC0Pres = cell(neq_cres,1);  % in each cell representing equation, we have 4 columns:
-           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
-           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
-   %** 1st equation
-   ixmC0Pres{1} = [1 2 2 1
-                   1 7 1 1];
-   %** 2nd equation
-   ixmC0Pres{2} = [2 2 2 2];
-   %** 3rd equation
-   ixmC0Pres{3} = [3 7 1 1
-                   3 2 2 1];
-
-
-%         % 4 columns.
-%   ncres = 5;  % manually key in the number of cross-A0-A+ restrictions
-
-%           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
-%           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
-%           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
-%           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
-else
-   ixmC0Pres = NaN;
-end
-
+function [Ui,Vi,n0,np,ixmC0Pres] = ftd_upperchol7v(lags,nvar,nexo,indxC0Pres)
+%  vlist = [127 124 2 93 141 21];    % 1: Pcom 2 (exchange rate 21); 2: M3 141 (M2 140); 3: R; 4: GDP; 5: GDP deflator 124 (consumption deflator 79).
+%  varlist={'y', 'P', 'Pcom', 'R', 'M3', 'Ex'};
+%
+%    Exporting orthonormal matrices for the deterministic linear restrictions (equation by equation)
+%    See Waggoner and Zha's Gibbs sampling paper.
+%
+% q_m:  quarter or month
+% lags: the maximum length of lag
+% nvar:  number of endogeous variables
+% nexo:  number of exogenous variables.  If nexo is not supplied, nexo=1 as default for a constant
+% indxC0Pres: index for cross-A0-A+ restrictions.  if 1: cross-A0-and-A+ restrictions; 0: idfile is all we have
+%                Example for indxOres==1: restrictions of the form P(t) = P(t-1).
+%                These restrictions have to be manually and carefully keyed in.
+%-----------------
+% Ui: nvar-by-1 cell.  In each cell, nvar-by-qi orthonormal basis for the null of the ith
+%           equation contemporaneous restriction matrix where qi is the number of free parameters.
+%           With this transformation, we have ai = Ui*bi or Ui'*ai = bi where ai is a vector
+%           of total original parameters and bi is a vector of free parameters. When no
+%           restrictions are imposed, we have Ui = I.  There must be at least one free
+%           parameter left for the ith equation.
+% Vi: nvar-by-1 cell.  In each cell, k-by-ri orthonormal basis for the null of the ith
+%           equation lagged restriction matrix where k is a total of exogenous variables and
+%           ri is the number of free parameters. With this transformation, we have fi = Vi*gi
+%           or Vi'*fi = gi where fi is a vector of total original parameters and gi is a
+%           vector of free parameters. There must be at least one free parameter left for
+%           the ith equation.
+% n0: nvar-by-1, ith element represents the number of free A0 parameters in ith equation
+% np: nvar-by-1, ith element represents the number of free A+ parameters in ith equation
+% ixmC0Pres:  neq_cres-by-1 cell.  Effective only if indxC0Pres=1, otherwise equals NaN.
+%             neq_cres is the number of equations in which cross-A0-A+ restrictions occur.
+%             In the jth cell representing equation, we have 4 columns:
+%               1st: the jth column (equation) of A+ or A0: f_j or a_j
+%               2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+%               3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+%               4th: the number s such that f_j(i) = s * a_j(h) holds.
+%
+% Tao Zha, May 2000
+
+
+
+Ui = cell(nvar,1);  % initializing for contemporaneous endogenous variables
+Vi = cell(nvar,1);  % initializing for lagged and exogenous variables
+n0 = zeros(nvar,1); % ith element represents the number of free A0 parameters in ith equation
+np = zeros(nvar,1); % ith element represents the number of free A+ parameters in ith equation
+
+if (nargin==2)
+   nexo = 1;  % 1: constant as default where nexo must be a nonnegative integer
+elseif (nargin==3)
+   indxC0Pres = 0;  % default is no cross-A0-and-A+ restrictions.
+end
+
+k = lags*nvar+nexo;  % maximum number of lagged and exogenous variables in each equation
+
+Qi = zeros(nvar,nvar,nvar);   % for nvar contemporaneous equations
+Ri = zeros(k,k,nvar);    % for nvar lagged and exogenous equations
+  % Row corresponds to equation. 0 means no restriction.
+  %                              1 means exclusion restriction such that the corresponding parameter is restricted to 0.
+
+%nfvar = 6;   % number of foreign (Granger causing) variables
+%nhvar = nvar-nfvar;  % number of home (affected) variables.
+
+
+%-------------------------------------------------------------
+%  Beginning the manual input of the restrictions one quation at a time
+%-------------------------------------------------------------
+%
+%======== The first equation ===========
+Qi(1:6,:,1) = [
+    0 1 0 0 0 0 0
+    0 0 1 0 0 0 0
+    0 0 0 1 0 0 0
+    0 0 0 0 1 0 0
+    0 0 0 0 0 1 0
+    0 0 0 0 0 0 1
+        ];
+
+%======== The second equation ===========
+Qi(1:5,:,2) = [
+    0 0 1 0 0 0 0
+    0 0 0 1 0 0 0
+    0 0 0 0 1 0 0
+    0 0 0 0 0 1 0
+    0 0 0 0 0 0 1
+        ];
+
+%======== The third equation ===========
+Qi(1:4,:,3) = [
+    0 0 0 1 0 0 0
+    0 0 0 0 1 0 0
+    0 0 0 0 0 1 0
+    0 0 0 0 0 0 1
+        ];
+
+%======== The fourth equation ===========
+Qi(1:3,:,4) = [
+    0 0 0 0 1 0 0
+    0 0 0 0 0 1 0
+    0 0 0 0 0 0 1
+        ];
+
+
+%======== The fifth equation ===========
+Qi(1:2,:,5) = [
+    0 0 0 0 0 1 0
+    0 0 0 0 0 0 1
+         ];
+
+
+%======== The sixth equation ===========
+Qi(1:1,:,6) = [
+    0 0 0 0 0 0 1
+         ];
+
+
+%======== The seventh equation ===========
+
+%===== Lagged restrictions in foreign (Granger causing) block
+%nfbres = lags*(nvar-nfvar);  % number of block restrictions in each foreign equation
+%bfor = zeros(nfbres,k);  % each foreign equation
+%cnt=0;
+%for ki = 1:lags
+%   for kj=1:nvar-nfvar
+%      cnt=cnt+1;
+%      bfor(cnt,nvar*(ki-1)+nfvar+kj) = 1;
+%   end
+%end
+%%
+%if cnt~=nfbres
+%   error('Check lagged restrictions in foreign equations!')
+%end
+%%
+%for kj=1:nfvar
+%   Ri(1:nfbres,:,kj) = bfor;
+%end
+
+
+%===== Lagged restrictions in home (affected) block
+%
+%~~~~~ selected domestic equations
+%dlrindx = nfvar+1; %[nfvar+1 nfvar+2];  % index for relevant home equations
+%rfvindx = []; %[6];  %[1 2 3 5];  % index for restricted foreign variables (e.g., Poil, M2, FFR, P).
+%%nf2hvar = nfvar-length(rfvindx);  % number of free parameters -- foreign variables entering the home sector
+%nhbres = lags*length(rfvindx);  % number of block restrictions in each home equation
+%bhom = zeros(nhbres,k);  % each home equation
+%cnt=0;
+%for ki = 1:lags
+%   for kj=1:length(rfvindx)
+%      cnt=cnt+1;
+%      bhom(cnt,nvar*(ki-1)+rfvindx(kj)) = 1;
+%   end
+%end
+%%
+%if cnt~=nhbres
+%   error('Check lagged restrictions in domestic equations!')
+%end
+%%
+%for kj=dlrindx
+%   Ri(1:nhbres,:,kj) = bhom;
+%end
+
+
+for n=1:nvar   %  initializing loop for each equation
+   Ui{n} = null(Qi(:,:,n));
+   Vi{n} = null(Ri(:,:,n));
+   n0(n) = size(Ui{n},2);
+   np(n) = size(Vi{n},2);
+end
+
+
+
+%(2)-------------------------------------------------------------
+%  Cross-A0-and-A+ rerestrictions one quation at a time
+%    i.e., the first, second, ..., kjth, ..., equation
+%(2)-------------------------------------------------------------
+%
+if indxC0Pres
+   neq_cres = 3;   % the number of equations in which cross-A0-A+ restrictions occur.
+   ixmC0Pres = cell(neq_cres,1);  % in each cell representing equation, we have 4 columns:
+           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
+           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
+   %** 1st equation
+   ixmC0Pres{1} = [1 2 2 1
+                   1 7 1 1];
+   %** 2nd equation
+   ixmC0Pres{2} = [2 2 2 2];
+   %** 3rd equation
+   ixmC0Pres{3} = [3 7 1 1
+                   3 2 2 1];
+
+
+%         % 4 columns.
+%   ncres = 5;  % manually key in the number of cross-A0-A+ restrictions
+
+%           % 1st: the jth column (equation) of A+ or A0: f_j or a_j
+%           % 2nd: the ith element f_j(i) -- the ith element in the jth column of A+
+%           % 3rd: the hth element a_j(h) -- the hth element in the jth column of A0
+%           % 4th: the number s such that f_j(i) = s * a_j(h) holds.
+else
+   ixmC0Pres = NaN;
+end
+
diff --git a/tests/optimal_policy/nk_ramsey.mod b/tests/optimal_policy/nk_ramsey.mod
index c83cccc5e412a1fa4600e47cf1978708e61c361f..3b35cf51c87c6be1f6f264f9694a34e94f76c15f 100644
--- a/tests/optimal_policy/nk_ramsey.mod
+++ b/tests/optimal_policy/nk_ramsey.mod
@@ -1,90 +1,90 @@
-//MODEL:
-//test on Dynare to find the lagrangean multipliers.
-//We consider a standard NK model. We use the FOCS of the competitive economy and we aim at calculating the Ramsey optimal problem.
-
-//------------------------------------------------------------------------------------------------------------------------
-//1. Variable declaration
-//------------------------------------------------------------------------------------------------------------------------
-
-var pai, c, n, r, a;
-
-//4 variables + 1 shock
-
-varexo u;
-
-
-
-
-//------------------------------------------------------------------------------------------------------------------------
-// 2. Parameter declaration and calibration
-//-------------------------------------------------------------------------------------------------------------------------
-
-parameters beta, rho, epsilon, omega, phi, gamma;
-
-beta=0.99;
-gamma=3;       //Frish elasticity
-omega=17;        //price stickyness
-epsilon=8;      //elasticity for each variety of consumption
-phi=1;           //coefficient associated to labor effort disutility
-
-rho=0.95;  //coefficient associated to productivity shock
-
-
-//-----------------------------------------------------------------------------------------------------------------------
-// 3. The model
-//-----------------------------------------------------------------------------------------------------------------------
-
-
-model;
-
-
-a=rho*(a(-1))+u;
-
-1/c=beta*(1/(c(+1)))*(r/(pai(+1)));               //euler
-
-
-omega*pai*(pai-1)=beta*omega*(c/(c(+1)))*(pai(+1))*(pai(+1)-1)+epsilon*exp(a)*n*(c/exp(a)*phi*n^gamma-(epsilon-1)/epsilon);  //NK pc
-//pai*(pai-1)/c = beta*pai(+1)*(pai(+1)-1)/c(+1)+epsilon*phi*n^(gamma+1)/omega-exp(a)*n*(epsilon-1)/(omega*c);  //NK pc
-
-(exp(a))*n=c+(omega/2)*((pai-1)^2);
-
-end;
-
-//--------------------------------------------------------------------------------------------------------------------------
-// 4. Steady state
-//---------------------------------------------------------------------------------------------------------------------------
-
-initval;
-
-pai=1;
-r=1/beta;
-c=0.9671684882;
-n=0.9671684882;
-a=0;
-
-
-end;
-
-
-
-//---------------------------------------------------------------------------------------------------------------------------
-// 5. shocks
-//---------------------------------------------------------------------------------------------------------------------------
-
-shocks;
-var u; stderr 0.008;
-
-end;
-
-//--------------------------------------------------------------------------------------------------------------------------
-// 6. Ramsey problem
-//--------------------------------------------------------------------------------------------------------------------------
-
-planner_objective(ln(c)-phi*((n^(1+gamma))/(1+gamma)));
-
-write_latex_static_model;
-
-ramsey_policy(planner_discount=0.99);
-
-
-
+//MODEL:
+//test on Dynare to find the lagrangean multipliers.
+//We consider a standard NK model. We use the FOCS of the competitive economy and we aim at calculating the Ramsey optimal problem.
+
+//------------------------------------------------------------------------------------------------------------------------
+//1. Variable declaration
+//------------------------------------------------------------------------------------------------------------------------
+
+var pai, c, n, r, a;
+
+//4 variables + 1 shock
+
+varexo u;
+
+
+
+
+//------------------------------------------------------------------------------------------------------------------------
+// 2. Parameter declaration and calibration
+//-------------------------------------------------------------------------------------------------------------------------
+
+parameters beta, rho, epsilon, omega, phi, gamma;
+
+beta=0.99;
+gamma=3;       //Frish elasticity
+omega=17;        //price stickyness
+epsilon=8;      //elasticity for each variety of consumption
+phi=1;           //coefficient associated to labor effort disutility
+
+rho=0.95;  //coefficient associated to productivity shock
+
+
+//-----------------------------------------------------------------------------------------------------------------------
+// 3. The model
+//-----------------------------------------------------------------------------------------------------------------------
+
+
+model;
+
+
+a=rho*(a(-1))+u;
+
+1/c=beta*(1/(c(+1)))*(r/(pai(+1)));               //euler
+
+
+omega*pai*(pai-1)=beta*omega*(c/(c(+1)))*(pai(+1))*(pai(+1)-1)+epsilon*exp(a)*n*(c/exp(a)*phi*n^gamma-(epsilon-1)/epsilon);  //NK pc
+//pai*(pai-1)/c = beta*pai(+1)*(pai(+1)-1)/c(+1)+epsilon*phi*n^(gamma+1)/omega-exp(a)*n*(epsilon-1)/(omega*c);  //NK pc
+
+(exp(a))*n=c+(omega/2)*((pai-1)^2);
+
+end;
+
+//--------------------------------------------------------------------------------------------------------------------------
+// 4. Steady state
+//---------------------------------------------------------------------------------------------------------------------------
+
+initval;
+
+pai=1;
+r=1/beta;
+c=0.9671684882;
+n=0.9671684882;
+a=0;
+
+
+end;
+
+
+
+//---------------------------------------------------------------------------------------------------------------------------
+// 5. shocks
+//---------------------------------------------------------------------------------------------------------------------------
+
+shocks;
+var u; stderr 0.008;
+
+end;
+
+//--------------------------------------------------------------------------------------------------------------------------
+// 6. Ramsey problem
+//--------------------------------------------------------------------------------------------------------------------------
+
+planner_objective(ln(c)-phi*((n^(1+gamma))/(1+gamma)));
+
+write_latex_static_model;
+
+ramsey_policy(planner_discount=0.99);
+
+
+
diff --git a/tests/optimal_policy/nk_ramsey_expectation.mod b/tests/optimal_policy/nk_ramsey_expectation.mod
index 6ef787945ecee24f7ca9cf5e0186ec450e5eb752..00212c000cc20a5a4fd3b12a0584bd63070614c7 100644
--- a/tests/optimal_policy/nk_ramsey_expectation.mod
+++ b/tests/optimal_policy/nk_ramsey_expectation.mod
@@ -1,96 +1,96 @@
-//MODEL:
-// test for using expectation operator with Ramsey policy
-// The results is validated by comparing with replacing manually the expectation with an
-// auxiliary variable in nk_ramsey_expectation_a.mod
-// Note that the example doesn't make any sense from an economic point of view.
-
-
-//------------------------------------------------------------------------------------------------------------------------
-//1. Variable declaration
-//------------------------------------------------------------------------------------------------------------------------
-
-var pai, c, n, r, a;
-
-//4 variables + 1 shock
-
-varexo u;
-
-
-
-
-//------------------------------------------------------------------------------------------------------------------------
-// 2. Parameter declaration and calibration
-//-------------------------------------------------------------------------------------------------------------------------
-
-parameters beta, rho, epsilon, omega, phi, gamma;
-
-beta=0.99;
-gamma=3;       //Frish elasticity
-omega=17;        //price stickyness
-epsilon=8;      //elasticity for each variety of consumption
-phi=1;           //coefficient associated to labor effort disutility
-
-rho=0.95;  //coefficient associated to productivity shock
-
-
-//-----------------------------------------------------------------------------------------------------------------------
-// 3. The model
-//-----------------------------------------------------------------------------------------------------------------------
-
-
-model;
-
-
-a=rho*(a(-1))+u;
-
-1/c=beta*(1/(c(+1)))*(r/expectation(0)(pai(+1)));               //euler
-
-
-omega*pai*(pai-1)=beta*omega*(c/(c(+1)))*(pai(+1))*(pai(+1)-1)+epsilon*exp(a)*n*(c/exp(a)*phi*n^gamma-(epsilon-1)/epsilon);  //NK pc
-//pai*(pai-1)/c = beta*pai(+1)*(pai(+1)-1)/c(+1)+epsilon*phi*n^(gamma+1)/omega-exp(a)*n*(epsilon-1)/(omega*c);  //NK pc
-
-(exp(a))*n=c+(omega/2)*((pai-1)^2);
-
-end;
-
-//--------------------------------------------------------------------------------------------------------------------------
-// 4. Steady state
-//---------------------------------------------------------------------------------------------------------------------------
-
-initval;
-% this is the exact steady state under optimal policy
-%important for the comparison
-
-pai=1;
-r=1/beta;
-c=((epsilon-1)/(epsilon*phi))^(1/(1+gamma));
-n=c;
-a=0;
-
-end;
-
-
-
-//---------------------------------------------------------------------------------------------------------------------------
-// 5. shocks
-//---------------------------------------------------------------------------------------------------------------------------
-
-shocks;
-var u; stderr 0.008;
-
-end;
-
-//--------------------------------------------------------------------------------------------------------------------------
-// 6. Ramsey problem
-//--------------------------------------------------------------------------------------------------------------------------
-
-planner_objective(ln(c)-phi*((n^(1+gamma))/(1+gamma)));
-
-write_latex_static_model;
-write_latex_dynamic_model;
-
-options_.solve_tolf=1e-12;
-ramsey_policy(planner_discount=0.99);
-
-
-
+//MODEL:
+// test for using expectation operator with Ramsey policy
+// The results is validated by comparing with replacing manually the expectation with an
+// auxiliary variable in nk_ramsey_expectation_a.mod
+// Note that the example doesn't make any sense from an economic point of view.
+
+
+//------------------------------------------------------------------------------------------------------------------------
+//1. Variable declaration
+//------------------------------------------------------------------------------------------------------------------------
+
+var pai, c, n, r, a;
+
+//4 variables + 1 shock
+
+varexo u;
+
+
+
+
+//------------------------------------------------------------------------------------------------------------------------
+// 2. Parameter declaration and calibration
+//-------------------------------------------------------------------------------------------------------------------------
+
+parameters beta, rho, epsilon, omega, phi, gamma;
+
+beta=0.99;
+gamma=3;       //Frish elasticity
+omega=17;        //price stickyness
+epsilon=8;      //elasticity for each variety of consumption
+phi=1;           //coefficient associated to labor effort disutility
+
+rho=0.95;  //coefficient associated to productivity shock
+
+
+//-----------------------------------------------------------------------------------------------------------------------
+// 3. The model
+//-----------------------------------------------------------------------------------------------------------------------
+
+
+model;
+
+
+a=rho*(a(-1))+u;
+
+1/c=beta*(1/(c(+1)))*(r/expectation(0)(pai(+1)));               //euler
+
+
+omega*pai*(pai-1)=beta*omega*(c/(c(+1)))*(pai(+1))*(pai(+1)-1)+epsilon*exp(a)*n*(c/exp(a)*phi*n^gamma-(epsilon-1)/epsilon);  //NK pc
+//pai*(pai-1)/c = beta*pai(+1)*(pai(+1)-1)/c(+1)+epsilon*phi*n^(gamma+1)/omega-exp(a)*n*(epsilon-1)/(omega*c);  //NK pc
+
+(exp(a))*n=c+(omega/2)*((pai-1)^2);
+
+end;
+
+//--------------------------------------------------------------------------------------------------------------------------
+// 4. Steady state
+//---------------------------------------------------------------------------------------------------------------------------
+
+initval;
+% this is the exact steady state under optimal policy
+%important for the comparison
+
+pai=1;
+r=1/beta;
+c=((epsilon-1)/(epsilon*phi))^(1/(1+gamma));
+n=c;
+a=0;
+
+end;
+
+
+
+//---------------------------------------------------------------------------------------------------------------------------
+// 5. shocks
+//---------------------------------------------------------------------------------------------------------------------------
+
+shocks;
+var u; stderr 0.008;
+
+end;
+
+//--------------------------------------------------------------------------------------------------------------------------
+// 6. Ramsey problem
+//--------------------------------------------------------------------------------------------------------------------------
+
+planner_objective(ln(c)-phi*((n^(1+gamma))/(1+gamma)));
+
+write_latex_static_model;
+write_latex_dynamic_model;
+
+options_.solve_tolf=1e-12;
+ramsey_policy(planner_discount=0.99);
+
+
+
diff --git a/tests/optimal_policy/nk_ramsey_expectation_a.mod b/tests/optimal_policy/nk_ramsey_expectation_a.mod
index cbd7a5f341270fbb807f40c1d9b9c802648e02d7..8755e7f36726c855fb6b1cec140a914c5e311674 100644
--- a/tests/optimal_policy/nk_ramsey_expectation_a.mod
+++ b/tests/optimal_policy/nk_ramsey_expectation_a.mod
@@ -1,104 +1,104 @@
-//MODEL:
-// test for using expectation operator with Ramsey policy
-// Here, the expected variable is replaced manually with an auxiliary variable (epai)
-// We check that the result is the same as with an explicit expectation operator in nk_ramsey_expectation.mod
-// Note that the example doesn't make any sense from an economic point of view.
-
-//------------------------------------------------------------------------------------------------------------------------
-//1. Variable declaration
-//------------------------------------------------------------------------------------------------------------------------
-
-var pai, c, n, r, a, epai;
-
-//4 variables + 1 shock
-
-varexo u;
-
-
-
-
-//------------------------------------------------------------------------------------------------------------------------
-// 2. Parameter declaration and calibration
-//-------------------------------------------------------------------------------------------------------------------------
-
-parameters beta, rho, epsilon, omega, phi, gamma;
-
-beta=0.99;
-gamma=3;       //Frish elasticity
-omega=17;        //price stickyness
-epsilon=8;      //elasticity for each variety of consumption
-phi=1;           //coefficient associated to labor effort disutility
-
-rho=0.95;  //coefficient associated to productivity shock
-
-
-//-----------------------------------------------------------------------------------------------------------------------
-// 3. The model
-//-----------------------------------------------------------------------------------------------------------------------
-
-
-model;
-
-
-a=rho*(a(-1))+u;
-
-1/c=beta*(1/(c(+1)))*(r/epai);               //euler
-
-
-omega*pai*(pai-1)=beta*omega*(c/(c(+1)))*(pai(+1))*(pai(+1)-1)+epsilon*exp(a)*n*(c/exp(a)*phi*n^gamma-(epsilon-1)/epsilon);  //NK pc
-//pai*(pai-1)/c = beta*pai(+1)*(pai(+1)-1)/c(+1)+epsilon*phi*n^(gamma+1)/omega-exp(a)*n*(epsilon-1)/(omega*c);  //NK pc
-
-(exp(a))*n=c+(omega/2)*((pai-1)^2);
-
-epai = pai(+1);
-end;
-
-//--------------------------------------------------------------------------------------------------------------------------
-// 4. Steady state
-//---------------------------------------------------------------------------------------------------------------------------
-
-initval;
-% this is the exact steady state under optimal policy
-%important for the comparison
-
-pai=1;
-epai=1;
-r=1/beta;
-c=((epsilon-1)/(epsilon*phi))^(1/(1+gamma));
-n=c;
-a=0;
-
-
-end;
-
-
-
-//---------------------------------------------------------------------------------------------------------------------------
-// 5. shocks
-//---------------------------------------------------------------------------------------------------------------------------
-
-shocks;
-var u; stderr 0.008;
-
-end;
-
-//--------------------------------------------------------------------------------------------------------------------------
-// 6. Ramsey problem
-//--------------------------------------------------------------------------------------------------------------------------
-
-planner_objective(ln(c)-phi*((n^(1+gamma))/(1+gamma)));
-
-options_.solve_tolf=1e-12;
-ramsey_policy(planner_discount=0.99);
-
-o1=load('nk_ramsey_expectation_results');
-if (norm(o1.oo_.dr.ghx-oo_.dr.ghx,inf) > 1e-12)
-   error('ghx doesn''t match')
-end
-if (norm(o1.oo_.dr.ghu-oo_.dr.ghu,inf) > 1e-12)
-   error('ghu doesn''t match')
-end
-if (abs(o1.oo_.planner_objective_value(1)-oo_.planner_objective_value(1)) > 1e-12)
-   error('planner objective value doesn''t match')
-end
-
+//MODEL:
+// test for using expectation operator with Ramsey policy
+// Here, the expected variable is replaced manually with an auxiliary variable (epai)
+// We check that the result is the same as with an explicit expectation operator in nk_ramsey_expectation.mod
+// Note that the example doesn't make any sense from an economic point of view.
+
+//------------------------------------------------------------------------------------------------------------------------
+//1. Variable declaration
+//------------------------------------------------------------------------------------------------------------------------
+
+var pai, c, n, r, a, epai;
+
+//4 variables + 1 shock
+
+varexo u;
+
+
+
+
+//------------------------------------------------------------------------------------------------------------------------
+// 2. Parameter declaration and calibration
+//-------------------------------------------------------------------------------------------------------------------------
+
+parameters beta, rho, epsilon, omega, phi, gamma;
+
+beta=0.99;
+gamma=3;       //Frish elasticity
+omega=17;        //price stickyness
+epsilon=8;      //elasticity for each variety of consumption
+phi=1;           //coefficient associated to labor effort disutility
+
+rho=0.95;  //coefficient associated to productivity shock
+
+
+//-----------------------------------------------------------------------------------------------------------------------
+// 3. The model
+//-----------------------------------------------------------------------------------------------------------------------
+
+
+model;
+
+
+a=rho*(a(-1))+u;
+
+1/c=beta*(1/(c(+1)))*(r/epai);               //euler
+
+
+omega*pai*(pai-1)=beta*omega*(c/(c(+1)))*(pai(+1))*(pai(+1)-1)+epsilon*exp(a)*n*(c/exp(a)*phi*n^gamma-(epsilon-1)/epsilon);  //NK pc
+//pai*(pai-1)/c = beta*pai(+1)*(pai(+1)-1)/c(+1)+epsilon*phi*n^(gamma+1)/omega-exp(a)*n*(epsilon-1)/(omega*c);  //NK pc
+
+(exp(a))*n=c+(omega/2)*((pai-1)^2);
+
+epai = pai(+1);
+end;
+
+//--------------------------------------------------------------------------------------------------------------------------
+// 4. Steady state
+//---------------------------------------------------------------------------------------------------------------------------
+
+initval;
+% this is the exact steady state under optimal policy
+%important for the comparison
+
+pai=1;
+epai=1;
+r=1/beta;
+c=((epsilon-1)/(epsilon*phi))^(1/(1+gamma));
+n=c;
+a=0;
+
+
+end;
+
+
+
+//---------------------------------------------------------------------------------------------------------------------------
+// 5. shocks
+//---------------------------------------------------------------------------------------------------------------------------
+
+shocks;
+var u; stderr 0.008;
+
+end;
+
+//--------------------------------------------------------------------------------------------------------------------------
+// 6. Ramsey problem
+//--------------------------------------------------------------------------------------------------------------------------
+
+planner_objective(ln(c)-phi*((n^(1+gamma))/(1+gamma)));
+
+options_.solve_tolf=1e-12;
+ramsey_policy(planner_discount=0.99);
+
+o1=load('nk_ramsey_expectation_results');
+if (norm(o1.oo_.dr.ghx-oo_.dr.ghx,inf) > 1e-12)
+   error('ghx doesn''t match')
+end
+if (norm(o1.oo_.dr.ghu-oo_.dr.ghu,inf) > 1e-12)
+   error('ghu doesn''t match')
+end
+if (abs(o1.oo_.planner_objective_value(1)-oo_.planner_objective_value(1)) > 1e-12)
+   error('planner objective value doesn''t match')
+end
+
diff --git a/tests/parallel/data_ca1.m b/tests/parallel/data_ca1.m
index b0b4f054613b41ebd91b9492f4edca5d38f6cb26..c28fae1a2800e83eda0e6343196e8aeafad2935f 100644
--- a/tests/parallel/data_ca1.m
+++ b/tests/parallel/data_ca1.m
@@ -1,100 +1,100 @@
-data = [0.928467646476  11.8716889412   20  0.418037507392  0.227382377518 ...
--0.705994063083 11.7522582094   21.25   1.09254424511   -1.29488274994 ...
--0.511895351926 9.68144025625   17.25   -1.66150408407  0.331508393098 ...
--0.990955971267 10.0890781236   17  1.43016275252   -2.43589670141 ...
--0.981233061806 12.1094840679   18.25   2.91293288733   -0.790246576864 ...
--0.882182844512 8.54559460406   15  0.419579139481  0.358729719566 ...
--0.930893002836 6.19238374422   12.5    -1.48847457959  0.739779938797 ...
-1.53158206947   2.76544271886   11.5    -0.336216769682 0.455559918769 ...
-2.2659052834    5.47418162513   11  0.306436789767  -0.0707985731221 ...
-1.05419803797   6.35698426189   11  0.140700250477  0.620401487202 ...
-1.20161076793   3.4253301593    11  0.461296492351  0.14354323987 ...
-1.73934077971   4.70926070322   11.5    1.35798282982   0.38564694435 ...
-1.71735262584   3.54232079749   12.5    2.9097529155    -0.804308583301 ...
-0.426343657844  3.32719108897   13  1.64214862652   -1.18214664701 ...
-1.67751812324   2.93444727338   11.25   0.344434910651  -1.6529373719 ...
-1.37013301099   4.72303361923   11.75   2.61511526582   0.327684243041 ...
-0.281231073781  4.4893853071    10.5    1.17043449257   1.12855106649 ...
-1.53638992834   3.7325309699    10.25   -0.683947046728 0.11943538737 ...
-1.68081431462   3.34729969129   10  1.41159342106   -1.59065680853 ...
--0.343321601133 5.05563513564   12  1.75117366498   -2.40127764642 ...
-0.873415608666  3.2779996255    10.25   -1.39895866711  0.0971444398216 ...
-0.26399696544   4.78229419828   9.75    0.0914692438124 0.299310457612 ...
--0.562233624818 3.88598638237   9.75    -0.0505384765105    0.332826708151 ...
-2.15161914936   3.84859710132   8.75    -3.44811080489  0.789138678784 ...
-1.2345093726    5.62225030942   9.5 -0.366945407434 2.32974981198 ...
-1.62554967459   4.24667132831   10  -0.800958371402 0.0293183770935 ...
-1.33035402527   2.75248979249   9.75    -0.855723113225 0.852493939813 ...
-1.52078814077   3.53415985826   9.75    -3.37963469203  -1.05133958119 ...
-1.16704983697   4.92754079464   10.75   -3.0142303324   0.459907431978 ...
-0.277213572101  4.55532133037   11.75   -0.851995599415 2.03242034852 ...
-0.842215068977  3.11164509647   12.25   -1.08290421696  0.014323281961 ...
-1.05325028606   4.92882647578   13.5    -1.1953883867   0.706764750654 ...
-0.453051253568  6.82998950103   13.5    0.111803656462  0.088462593153 ...
-0.199885995525  5.82643354662   13.5    -0.920501518421 -0.26504958666 ...
-0.137907999624  2.66076369132   13.5    -1.17122929812  -0.995642430514 ...
-0.721949686709  5.70497876823   14.25   1.19378169018   -1.10644839651 ...
--0.418465249225 3.75861110232   14.75   -1.03131674824  0.188507675831 ...
--0.644028342116 4.15104788154   13.75   -1.48911756546  0.204560913792 ...
--0.848213852668 5.65580324027   12.75   0.677011703877  -0.849628054542 ...
--1.51954076928  11.4866911266   11.25   -0.446024680774 -0.456342350765 ...
-0.265275055215  2.85472749592   9.75    -0.598778202436 -0.907311640831 ...
-0.356162529063  2.29614015658   9.5 -0.46820788432  -1.22130883441 ...
-0.368308864363  -0.539083504685 8   -0.781333991956 0.374007246518 ...
--0.145751412732 1.61507621789   8.25    3.68291932628   1.32438399845 ...
-0.285457283664  2.14334055993   7   1.42819405379   -0.00818660844123 ...
-0.372390129412  1.60000213334   6.25    0.626106424052  -0.10136772765 ...
-0.382720203063  1.72614243263   7.25    4.89631941021   -1.10060711916 ...
-0.737957515573  2.90430582851   6   -0.0422721010314    0.4178952497 ...
-0.649532581668  0.657135682543  6   0.692066153971  0.422299120276 ...
-0.627159201987  1.70352689913   5.75    2.62066711305   -1.29237304034 ...
-0.905441299817  1.95663197267   5.5 1.5949697565    -0.27115830703 ...
-1.49322577898   -2.08741765309  6.25    1.23027694802   0.418336889527 ...
-1.48750731567   -1.57274121871  8   3.01660550994   -0.893958254365 ...
-1.39783858087   2.22623066426   7   -0.80842319214  1.47625453886 ...
-0.89274836317   1.30378081742   8   -0.249485058661 0.159871204185 ...
-0.920652246088  4.1437741965    9.75    2.8204453623    0.178149239655 ...
--0.00264276644799   3.07989972052   8.75    -2.56342461535  2.105998353 ...
-0.0198190461681 0.766283759256  8   -1.15838865989  1.56888883418 ...
-0.440050515311  0.127570085801  7.5 0.0400753569995 0.028914333532 ...
-0.129536637901  1.78174141526   6.75    0.959943962785  0.307781224401 ...
-0.398549827172  3.03606770667   6.5 -0.340209794742 0.100979469478 ...
-1.17174775425   0.629625188037  5.75    0.403003686814  0.902394579377 ...
-0.991163981251  2.50862910684   4.75    -1.44963996982  1.16150986945 ...
-0.967603566096  2.12003739013   4.75    0.610846030775  -0.889994896068 ...
-1.14689383604   1.24185011459   4.75    2.01098091308   -1.73846431001 ...
-1.32593824054   0.990713820685  4.75    -0.0955142989332    -0.0369257308362 ...
-0.861135002644  -0.24744943605  6   1.72793107135   -0.691506789639 ...
-1.26870850151   2.09844764887   6.5 1.50720217572   -1.31399187077 ...
-0.260364987715  1.10650139716   6.5 1.13659047496   0.0720441664643 ...
-1.09731242214   0.490796381346  7.25    4.59123894147   -2.14073070763 ...
-1.63792841781   0.612652594286  6.75    1.79604605035   -0.644363995357 ...
-1.48465576034   0.978295808687  6.75    -2.00753620902  1.39437534964 ...
-1.0987608663    4.25212569087   6.25    -2.58901196498  2.56054320803 ...
-1.42592178132   2.76984518311   6.25    0.888195752358  1.03114549274 ...
-1.52958239462   1.31795955491   6.5 -0.902907564082 -0.0952198893776 ...
-1.0170168994    2.14733589918   7   -1.3054866978   2.68803738466 ...
-0.723253652257  3.43552889347   7.5 1.8213700853    0.592593586195 ...
-1.24720806008   3.87383806577   7.5 0.0522300654168 0.988871238698 ...
-0.482531471239  2.67793287032   7.5 2.9693944293    -0.108591166081 ...
-0.154056100439  0.927269031704  6.75    0.119222057561  3.30489209451 ...
-0.0694865769274 6.65916526788   6.25    0.889014476084  -2.83976849035 ...
--0.121267434867 0.341442615696  5.25    0.323053239216  -3.49289229012 ...
-0.726473690375  -3.5423730964   4   2.19149290449   -3.20855054004 ...
-1.39271709108   2.63121085718   3.75    0.88406577736   0.75622580197 ...
-1.07502077727   5.88578836799   4.25    -2.55088273352  2.89018116374 ...
-0.759049251607  4.24703604223   4.5 0.575687665685  -0.388292506167 ...
-]; 
- 
-data = reshape(data,5,86)'; 
-y_obs = data(:,1); 
-pie_obs = data(:,2); 
-R_obs = data(:,3); 
-de = data(:,4); 
-dq = data(:,5); 
- 
-%Country: Canada 
-%Sample Range: 1981:2 to 2002:3 
-%Observations: 86 
-%Variables: Real GDP Growth [%], Inflation [annualized %], Nom Rate [%], 
-%           Exchange Rate Change [%], Terms of Trade Change [%] 
+data = [0.928467646476  11.8716889412   20  0.418037507392  0.227382377518 ...
+-0.705994063083 11.7522582094   21.25   1.09254424511   -1.29488274994 ...
+-0.511895351926 9.68144025625   17.25   -1.66150408407  0.331508393098 ...
+-0.990955971267 10.0890781236   17  1.43016275252   -2.43589670141 ...
+-0.981233061806 12.1094840679   18.25   2.91293288733   -0.790246576864 ...
+-0.882182844512 8.54559460406   15  0.419579139481  0.358729719566 ...
+-0.930893002836 6.19238374422   12.5    -1.48847457959  0.739779938797 ...
+1.53158206947   2.76544271886   11.5    -0.336216769682 0.455559918769 ...
+2.2659052834    5.47418162513   11  0.306436789767  -0.0707985731221 ...
+1.05419803797   6.35698426189   11  0.140700250477  0.620401487202 ...
+1.20161076793   3.4253301593    11  0.461296492351  0.14354323987 ...
+1.73934077971   4.70926070322   11.5    1.35798282982   0.38564694435 ...
+1.71735262584   3.54232079749   12.5    2.9097529155    -0.804308583301 ...
+0.426343657844  3.32719108897   13  1.64214862652   -1.18214664701 ...
+1.67751812324   2.93444727338   11.25   0.344434910651  -1.6529373719 ...
+1.37013301099   4.72303361923   11.75   2.61511526582   0.327684243041 ...
+0.281231073781  4.4893853071    10.5    1.17043449257   1.12855106649 ...
+1.53638992834   3.7325309699    10.25   -0.683947046728 0.11943538737 ...
+1.68081431462   3.34729969129   10  1.41159342106   -1.59065680853 ...
+-0.343321601133 5.05563513564   12  1.75117366498   -2.40127764642 ...
+0.873415608666  3.2779996255    10.25   -1.39895866711  0.0971444398216 ...
+0.26399696544   4.78229419828   9.75    0.0914692438124 0.299310457612 ...
+-0.562233624818 3.88598638237   9.75    -0.0505384765105    0.332826708151 ...
+2.15161914936   3.84859710132   8.75    -3.44811080489  0.789138678784 ...
+1.2345093726    5.62225030942   9.5 -0.366945407434 2.32974981198 ...
+1.62554967459   4.24667132831   10  -0.800958371402 0.0293183770935 ...
+1.33035402527   2.75248979249   9.75    -0.855723113225 0.852493939813 ...
+1.52078814077   3.53415985826   9.75    -3.37963469203  -1.05133958119 ...
+1.16704983697   4.92754079464   10.75   -3.0142303324   0.459907431978 ...
+0.277213572101  4.55532133037   11.75   -0.851995599415 2.03242034852 ...
+0.842215068977  3.11164509647   12.25   -1.08290421696  0.014323281961 ...
+1.05325028606   4.92882647578   13.5    -1.1953883867   0.706764750654 ...
+0.453051253568  6.82998950103   13.5    0.111803656462  0.088462593153 ...
+0.199885995525  5.82643354662   13.5    -0.920501518421 -0.26504958666 ...
+0.137907999624  2.66076369132   13.5    -1.17122929812  -0.995642430514 ...
+0.721949686709  5.70497876823   14.25   1.19378169018   -1.10644839651 ...
+-0.418465249225 3.75861110232   14.75   -1.03131674824  0.188507675831 ...
+-0.644028342116 4.15104788154   13.75   -1.48911756546  0.204560913792 ...
+-0.848213852668 5.65580324027   12.75   0.677011703877  -0.849628054542 ...
+-1.51954076928  11.4866911266   11.25   -0.446024680774 -0.456342350765 ...
+0.265275055215  2.85472749592   9.75    -0.598778202436 -0.907311640831 ...
+0.356162529063  2.29614015658   9.5 -0.46820788432  -1.22130883441 ...
+0.368308864363  -0.539083504685 8   -0.781333991956 0.374007246518 ...
+-0.145751412732 1.61507621789   8.25    3.68291932628   1.32438399845 ...
+0.285457283664  2.14334055993   7   1.42819405379   -0.00818660844123 ...
+0.372390129412  1.60000213334   6.25    0.626106424052  -0.10136772765 ...
+0.382720203063  1.72614243263   7.25    4.89631941021   -1.10060711916 ...
+0.737957515573  2.90430582851   6   -0.0422721010314    0.4178952497 ...
+0.649532581668  0.657135682543  6   0.692066153971  0.422299120276 ...
+0.627159201987  1.70352689913   5.75    2.62066711305   -1.29237304034 ...
+0.905441299817  1.95663197267   5.5 1.5949697565    -0.27115830703 ...
+1.49322577898   -2.08741765309  6.25    1.23027694802   0.418336889527 ...
+1.48750731567   -1.57274121871  8   3.01660550994   -0.893958254365 ...
+1.39783858087   2.22623066426   7   -0.80842319214  1.47625453886 ...
+0.89274836317   1.30378081742   8   -0.249485058661 0.159871204185 ...
+0.920652246088  4.1437741965    9.75    2.8204453623    0.178149239655 ...
+-0.00264276644799   3.07989972052   8.75    -2.56342461535  2.105998353 ...
+0.0198190461681 0.766283759256  8   -1.15838865989  1.56888883418 ...
+0.440050515311  0.127570085801  7.5 0.0400753569995 0.028914333532 ...
+0.129536637901  1.78174141526   6.75    0.959943962785  0.307781224401 ...
+0.398549827172  3.03606770667   6.5 -0.340209794742 0.100979469478 ...
+1.17174775425   0.629625188037  5.75    0.403003686814  0.902394579377 ...
+0.991163981251  2.50862910684   4.75    -1.44963996982  1.16150986945 ...
+0.967603566096  2.12003739013   4.75    0.610846030775  -0.889994896068 ...
+1.14689383604   1.24185011459   4.75    2.01098091308   -1.73846431001 ...
+1.32593824054   0.990713820685  4.75    -0.0955142989332    -0.0369257308362 ...
+0.861135002644  -0.24744943605  6   1.72793107135   -0.691506789639 ...
+1.26870850151   2.09844764887   6.5 1.50720217572   -1.31399187077 ...
+0.260364987715  1.10650139716   6.5 1.13659047496   0.0720441664643 ...
+1.09731242214   0.490796381346  7.25    4.59123894147   -2.14073070763 ...
+1.63792841781   0.612652594286  6.75    1.79604605035   -0.644363995357 ...
+1.48465576034   0.978295808687  6.75    -2.00753620902  1.39437534964 ...
+1.0987608663    4.25212569087   6.25    -2.58901196498  2.56054320803 ...
+1.42592178132   2.76984518311   6.25    0.888195752358  1.03114549274 ...
+1.52958239462   1.31795955491   6.5 -0.902907564082 -0.0952198893776 ...
+1.0170168994    2.14733589918   7   -1.3054866978   2.68803738466 ...
+0.723253652257  3.43552889347   7.5 1.8213700853    0.592593586195 ...
+1.24720806008   3.87383806577   7.5 0.0522300654168 0.988871238698 ...
+0.482531471239  2.67793287032   7.5 2.9693944293    -0.108591166081 ...
+0.154056100439  0.927269031704  6.75    0.119222057561  3.30489209451 ...
+0.0694865769274 6.65916526788   6.25    0.889014476084  -2.83976849035 ...
+-0.121267434867 0.341442615696  5.25    0.323053239216  -3.49289229012 ...
+0.726473690375  -3.5423730964   4   2.19149290449   -3.20855054004 ...
+1.39271709108   2.63121085718   3.75    0.88406577736   0.75622580197 ...
+1.07502077727   5.88578836799   4.25    -2.55088273352  2.89018116374 ...
+0.759049251607  4.24703604223   4.5 0.575687665685  -0.388292506167 ...
+]; 
+ 
+data = reshape(data,5,86)'; 
+y_obs = data(:,1); 
+pie_obs = data(:,2); 
+R_obs = data(:,3); 
+de = data(:,4); 
+dq = data(:,5); 
+ 
+%Country: Canada 
+%Sample Range: 1981:2 to 2002:3 
+%Observations: 86 
+%Variables: Real GDP Growth [%], Inflation [annualized %], Nom Rate [%], 
+%           Exchange Rate Change [%], Terms of Trade Change [%] 
diff --git a/tests/parallel/dynare.ini b/tests/parallel/dynare.ini
index e2daa437e84d4f957401f62a408df0b22c83e00a..2132a28cbe16cf8bea42077daf3a4c4032aeeb56 100644
--- a/tests/parallel/dynare.ini
+++ b/tests/parallel/dynare.ini
@@ -1,8 +1,11 @@
-[cluster]
-Name = Local
-Members = n1
-
-[node]
-Name = n1
-ComputerName = localhost
-CPUnbr = [1:8]
+[cluster]
+Name = Local
+Members = n1
+
+[hooks]
+GlobalInitFile = ./init.m
+
+[node]
+Name = n1
+ComputerName = localhost
+CPUnbr = [1:8]
diff --git a/tests/parallel/init.m b/tests/parallel/init.m
new file mode 100644
index 0000000000000000000000000000000000000000..f30afcb55bced99a02523ce58766c26385752b8e
--- /dev/null
+++ b/tests/parallel/init.m
@@ -0,0 +1 @@
+myvar = 1;
\ No newline at end of file
diff --git a/tests/pi2004/idata.m b/tests/pi2004/idata.m
index 9ce34b9eb76be9241efcb6ad422f93be370f4fec..e7a5a2c509bd2dee4a002feb4ab0dbfb866734be 100644
--- a/tests/pi2004/idata.m
+++ b/tests/pi2004/idata.m
@@ -1,5 +1,5 @@
-load ych.dat;
-data = log(ych);
-oy = data(:,1);
-oc = data(:,2);
+load ych.dat;
+data = log(ych);
+oy = data(:,1);
+oc = data(:,2);
 oh = data(:,3);
\ No newline at end of file
diff --git a/tests/practicing/datasaver.m b/tests/practicing/datasaver.m
index 2c72e20e160d54e7013cc132dc20623e3743fd27..0ac532a4aea7bf5c042c21fe43001a563784be48 100644
--- a/tests/practicing/datasaver.m
+++ b/tests/practicing/datasaver.m
@@ -1,58 +1,58 @@
-function datasaver (s,var_list)
-% datasaver saves variables simulated by Dynare
-% INPUT
-%    s: a string containing the name of the destination *.m file
-%    var_list: a character matrix containting the name of the variables
-%              to be saved (optional, default: all endogenous variables)
-% OUTPUT
-%    none
-% This is part of the examples included in F. Barillas, R. Colacito,
-% S. Kitao, C. Matthes, T. Sargent and Y. Shin (2007) "Practicing
-% Dynare".
-  
-% Modified by M. Juillard to make it also compatible with Dynare 
-% version 4 (12/4/07)   
-  
-
-global lgy_ lgx_ y_ endo_nbr M_ oo_
-
-% test and adapt for Dynare version 4
-if isempty(lgy_)
-  lgy_ = M_.endo_names;
-  lgx_ + M_.exo_names;
-  y_ = oo_.endo_simul;
-  endo_nbr = M_.endo_nbr;
-end
-
-sm=[s,'.m'];
-fid=fopen(sm,'w') ;
-
-n = size(var_list,1);
-if n == 0
-  n = endo_nbr;
-  ivar = [1:n]';
-  var_list = lgy_;
-else
-  ivar=zeros(n,1);
-  for i=1:n
-    i_tmp = strmatch(var_list(i,:),lgy_,'exact');
-    if isempty(i_tmp)
-      error (['One of the specified variables does not exist']) ;
-    else
-      ivar(i) = i_tmp;
-    end
-  end
-end
-
-
-for i = 1:n
-	fprintf(fid,[lgy_(ivar(i),:), '=['],'\n') ;
-	fprintf(fid,'\n') ;
-	fprintf(fid,'%15.8g\n',y_(ivar(i),:)') ;
-   	fprintf(fid,'\n') ;
-   	fprintf(fid,'];\n') ;
-  	fprintf(fid,'\n') ;
-end
-fclose(fid) ;
-
-return ;
+function datasaver (s,var_list)
+% datasaver saves variables simulated by Dynare
+% INPUT
+%    s: a string containing the name of the destination *.m file
+%    var_list: a character matrix containting the name of the variables
+%              to be saved (optional, default: all endogenous variables)
+% OUTPUT
+%    none
+% This is part of the examples included in F. Barillas, R. Colacito,
+% S. Kitao, C. Matthes, T. Sargent and Y. Shin (2007) "Practicing
+% Dynare".
+  
+% Modified by M. Juillard to make it also compatible with Dynare 
+% version 4 (12/4/07)   
+  
+
+global lgy_ lgx_ y_ endo_nbr M_ oo_
+
+% test and adapt for Dynare version 4
+if isempty(lgy_)
+  lgy_ = M_.endo_names;
+  lgx_ + M_.exo_names;
+  y_ = oo_.endo_simul;
+  endo_nbr = M_.endo_nbr;
+end
+
+sm=[s,'.m'];
+fid=fopen(sm,'w') ;
+
+n = size(var_list,1);
+if n == 0
+  n = endo_nbr;
+  ivar = [1:n]';
+  var_list = lgy_;
+else
+  ivar=zeros(n,1);
+  for i=1:n
+    i_tmp = strmatch(var_list(i,:),lgy_,'exact');
+    if isempty(i_tmp)
+      error (['One of the specified variables does not exist']) ;
+    else
+      ivar(i) = i_tmp;
+    end
+  end
+end
+
+
+for i = 1:n
+	fprintf(fid,[lgy_(ivar(i),:), '=['],'\n') ;
+	fprintf(fid,'\n') ;
+	fprintf(fid,'%15.8g\n',y_(ivar(i),:)') ;
+   	fprintf(fid,'\n') ;
+   	fprintf(fid,'];\n') ;
+  	fprintf(fid,'\n') ;
+end
+fclose(fid) ;
+
+return ;
diff --git a/tests/recursive/data_ca1.m b/tests/recursive/data_ca1.m
index b0b4f054613b41ebd91b9492f4edca5d38f6cb26..c28fae1a2800e83eda0e6343196e8aeafad2935f 100644
--- a/tests/recursive/data_ca1.m
+++ b/tests/recursive/data_ca1.m
@@ -1,100 +1,100 @@
-data = [0.928467646476  11.8716889412   20  0.418037507392  0.227382377518 ...
--0.705994063083 11.7522582094   21.25   1.09254424511   -1.29488274994 ...
--0.511895351926 9.68144025625   17.25   -1.66150408407  0.331508393098 ...
--0.990955971267 10.0890781236   17  1.43016275252   -2.43589670141 ...
--0.981233061806 12.1094840679   18.25   2.91293288733   -0.790246576864 ...
--0.882182844512 8.54559460406   15  0.419579139481  0.358729719566 ...
--0.930893002836 6.19238374422   12.5    -1.48847457959  0.739779938797 ...
-1.53158206947   2.76544271886   11.5    -0.336216769682 0.455559918769 ...
-2.2659052834    5.47418162513   11  0.306436789767  -0.0707985731221 ...
-1.05419803797   6.35698426189   11  0.140700250477  0.620401487202 ...
-1.20161076793   3.4253301593    11  0.461296492351  0.14354323987 ...
-1.73934077971   4.70926070322   11.5    1.35798282982   0.38564694435 ...
-1.71735262584   3.54232079749   12.5    2.9097529155    -0.804308583301 ...
-0.426343657844  3.32719108897   13  1.64214862652   -1.18214664701 ...
-1.67751812324   2.93444727338   11.25   0.344434910651  -1.6529373719 ...
-1.37013301099   4.72303361923   11.75   2.61511526582   0.327684243041 ...
-0.281231073781  4.4893853071    10.5    1.17043449257   1.12855106649 ...
-1.53638992834   3.7325309699    10.25   -0.683947046728 0.11943538737 ...
-1.68081431462   3.34729969129   10  1.41159342106   -1.59065680853 ...
--0.343321601133 5.05563513564   12  1.75117366498   -2.40127764642 ...
-0.873415608666  3.2779996255    10.25   -1.39895866711  0.0971444398216 ...
-0.26399696544   4.78229419828   9.75    0.0914692438124 0.299310457612 ...
--0.562233624818 3.88598638237   9.75    -0.0505384765105    0.332826708151 ...
-2.15161914936   3.84859710132   8.75    -3.44811080489  0.789138678784 ...
-1.2345093726    5.62225030942   9.5 -0.366945407434 2.32974981198 ...
-1.62554967459   4.24667132831   10  -0.800958371402 0.0293183770935 ...
-1.33035402527   2.75248979249   9.75    -0.855723113225 0.852493939813 ...
-1.52078814077   3.53415985826   9.75    -3.37963469203  -1.05133958119 ...
-1.16704983697   4.92754079464   10.75   -3.0142303324   0.459907431978 ...
-0.277213572101  4.55532133037   11.75   -0.851995599415 2.03242034852 ...
-0.842215068977  3.11164509647   12.25   -1.08290421696  0.014323281961 ...
-1.05325028606   4.92882647578   13.5    -1.1953883867   0.706764750654 ...
-0.453051253568  6.82998950103   13.5    0.111803656462  0.088462593153 ...
-0.199885995525  5.82643354662   13.5    -0.920501518421 -0.26504958666 ...
-0.137907999624  2.66076369132   13.5    -1.17122929812  -0.995642430514 ...
-0.721949686709  5.70497876823   14.25   1.19378169018   -1.10644839651 ...
--0.418465249225 3.75861110232   14.75   -1.03131674824  0.188507675831 ...
--0.644028342116 4.15104788154   13.75   -1.48911756546  0.204560913792 ...
--0.848213852668 5.65580324027   12.75   0.677011703877  -0.849628054542 ...
--1.51954076928  11.4866911266   11.25   -0.446024680774 -0.456342350765 ...
-0.265275055215  2.85472749592   9.75    -0.598778202436 -0.907311640831 ...
-0.356162529063  2.29614015658   9.5 -0.46820788432  -1.22130883441 ...
-0.368308864363  -0.539083504685 8   -0.781333991956 0.374007246518 ...
--0.145751412732 1.61507621789   8.25    3.68291932628   1.32438399845 ...
-0.285457283664  2.14334055993   7   1.42819405379   -0.00818660844123 ...
-0.372390129412  1.60000213334   6.25    0.626106424052  -0.10136772765 ...
-0.382720203063  1.72614243263   7.25    4.89631941021   -1.10060711916 ...
-0.737957515573  2.90430582851   6   -0.0422721010314    0.4178952497 ...
-0.649532581668  0.657135682543  6   0.692066153971  0.422299120276 ...
-0.627159201987  1.70352689913   5.75    2.62066711305   -1.29237304034 ...
-0.905441299817  1.95663197267   5.5 1.5949697565    -0.27115830703 ...
-1.49322577898   -2.08741765309  6.25    1.23027694802   0.418336889527 ...
-1.48750731567   -1.57274121871  8   3.01660550994   -0.893958254365 ...
-1.39783858087   2.22623066426   7   -0.80842319214  1.47625453886 ...
-0.89274836317   1.30378081742   8   -0.249485058661 0.159871204185 ...
-0.920652246088  4.1437741965    9.75    2.8204453623    0.178149239655 ...
--0.00264276644799   3.07989972052   8.75    -2.56342461535  2.105998353 ...
-0.0198190461681 0.766283759256  8   -1.15838865989  1.56888883418 ...
-0.440050515311  0.127570085801  7.5 0.0400753569995 0.028914333532 ...
-0.129536637901  1.78174141526   6.75    0.959943962785  0.307781224401 ...
-0.398549827172  3.03606770667   6.5 -0.340209794742 0.100979469478 ...
-1.17174775425   0.629625188037  5.75    0.403003686814  0.902394579377 ...
-0.991163981251  2.50862910684   4.75    -1.44963996982  1.16150986945 ...
-0.967603566096  2.12003739013   4.75    0.610846030775  -0.889994896068 ...
-1.14689383604   1.24185011459   4.75    2.01098091308   -1.73846431001 ...
-1.32593824054   0.990713820685  4.75    -0.0955142989332    -0.0369257308362 ...
-0.861135002644  -0.24744943605  6   1.72793107135   -0.691506789639 ...
-1.26870850151   2.09844764887   6.5 1.50720217572   -1.31399187077 ...
-0.260364987715  1.10650139716   6.5 1.13659047496   0.0720441664643 ...
-1.09731242214   0.490796381346  7.25    4.59123894147   -2.14073070763 ...
-1.63792841781   0.612652594286  6.75    1.79604605035   -0.644363995357 ...
-1.48465576034   0.978295808687  6.75    -2.00753620902  1.39437534964 ...
-1.0987608663    4.25212569087   6.25    -2.58901196498  2.56054320803 ...
-1.42592178132   2.76984518311   6.25    0.888195752358  1.03114549274 ...
-1.52958239462   1.31795955491   6.5 -0.902907564082 -0.0952198893776 ...
-1.0170168994    2.14733589918   7   -1.3054866978   2.68803738466 ...
-0.723253652257  3.43552889347   7.5 1.8213700853    0.592593586195 ...
-1.24720806008   3.87383806577   7.5 0.0522300654168 0.988871238698 ...
-0.482531471239  2.67793287032   7.5 2.9693944293    -0.108591166081 ...
-0.154056100439  0.927269031704  6.75    0.119222057561  3.30489209451 ...
-0.0694865769274 6.65916526788   6.25    0.889014476084  -2.83976849035 ...
--0.121267434867 0.341442615696  5.25    0.323053239216  -3.49289229012 ...
-0.726473690375  -3.5423730964   4   2.19149290449   -3.20855054004 ...
-1.39271709108   2.63121085718   3.75    0.88406577736   0.75622580197 ...
-1.07502077727   5.88578836799   4.25    -2.55088273352  2.89018116374 ...
-0.759049251607  4.24703604223   4.5 0.575687665685  -0.388292506167 ...
-]; 
- 
-data = reshape(data,5,86)'; 
-y_obs = data(:,1); 
-pie_obs = data(:,2); 
-R_obs = data(:,3); 
-de = data(:,4); 
-dq = data(:,5); 
- 
-%Country: Canada 
-%Sample Range: 1981:2 to 2002:3 
-%Observations: 86 
-%Variables: Real GDP Growth [%], Inflation [annualized %], Nom Rate [%], 
-%           Exchange Rate Change [%], Terms of Trade Change [%] 
+data = [0.928467646476  11.8716889412   20  0.418037507392  0.227382377518 ...
+-0.705994063083 11.7522582094   21.25   1.09254424511   -1.29488274994 ...
+-0.511895351926 9.68144025625   17.25   -1.66150408407  0.331508393098 ...
+-0.990955971267 10.0890781236   17  1.43016275252   -2.43589670141 ...
+-0.981233061806 12.1094840679   18.25   2.91293288733   -0.790246576864 ...
+-0.882182844512 8.54559460406   15  0.419579139481  0.358729719566 ...
+-0.930893002836 6.19238374422   12.5    -1.48847457959  0.739779938797 ...
+1.53158206947   2.76544271886   11.5    -0.336216769682 0.455559918769 ...
+2.2659052834    5.47418162513   11  0.306436789767  -0.0707985731221 ...
+1.05419803797   6.35698426189   11  0.140700250477  0.620401487202 ...
+1.20161076793   3.4253301593    11  0.461296492351  0.14354323987 ...
+1.73934077971   4.70926070322   11.5    1.35798282982   0.38564694435 ...
+1.71735262584   3.54232079749   12.5    2.9097529155    -0.804308583301 ...
+0.426343657844  3.32719108897   13  1.64214862652   -1.18214664701 ...
+1.67751812324   2.93444727338   11.25   0.344434910651  -1.6529373719 ...
+1.37013301099   4.72303361923   11.75   2.61511526582   0.327684243041 ...
+0.281231073781  4.4893853071    10.5    1.17043449257   1.12855106649 ...
+1.53638992834   3.7325309699    10.25   -0.683947046728 0.11943538737 ...
+1.68081431462   3.34729969129   10  1.41159342106   -1.59065680853 ...
+-0.343321601133 5.05563513564   12  1.75117366498   -2.40127764642 ...
+0.873415608666  3.2779996255    10.25   -1.39895866711  0.0971444398216 ...
+0.26399696544   4.78229419828   9.75    0.0914692438124 0.299310457612 ...
+-0.562233624818 3.88598638237   9.75    -0.0505384765105    0.332826708151 ...
+2.15161914936   3.84859710132   8.75    -3.44811080489  0.789138678784 ...
+1.2345093726    5.62225030942   9.5 -0.366945407434 2.32974981198 ...
+1.62554967459   4.24667132831   10  -0.800958371402 0.0293183770935 ...
+1.33035402527   2.75248979249   9.75    -0.855723113225 0.852493939813 ...
+1.52078814077   3.53415985826   9.75    -3.37963469203  -1.05133958119 ...
+1.16704983697   4.92754079464   10.75   -3.0142303324   0.459907431978 ...
+0.277213572101  4.55532133037   11.75   -0.851995599415 2.03242034852 ...
+0.842215068977  3.11164509647   12.25   -1.08290421696  0.014323281961 ...
+1.05325028606   4.92882647578   13.5    -1.1953883867   0.706764750654 ...
+0.453051253568  6.82998950103   13.5    0.111803656462  0.088462593153 ...
+0.199885995525  5.82643354662   13.5    -0.920501518421 -0.26504958666 ...
+0.137907999624  2.66076369132   13.5    -1.17122929812  -0.995642430514 ...
+0.721949686709  5.70497876823   14.25   1.19378169018   -1.10644839651 ...
+-0.418465249225 3.75861110232   14.75   -1.03131674824  0.188507675831 ...
+-0.644028342116 4.15104788154   13.75   -1.48911756546  0.204560913792 ...
+-0.848213852668 5.65580324027   12.75   0.677011703877  -0.849628054542 ...
+-1.51954076928  11.4866911266   11.25   -0.446024680774 -0.456342350765 ...
+0.265275055215  2.85472749592   9.75    -0.598778202436 -0.907311640831 ...
+0.356162529063  2.29614015658   9.5 -0.46820788432  -1.22130883441 ...
+0.368308864363  -0.539083504685 8   -0.781333991956 0.374007246518 ...
+-0.145751412732 1.61507621789   8.25    3.68291932628   1.32438399845 ...
+0.285457283664  2.14334055993   7   1.42819405379   -0.00818660844123 ...
+0.372390129412  1.60000213334   6.25    0.626106424052  -0.10136772765 ...
+0.382720203063  1.72614243263   7.25    4.89631941021   -1.10060711916 ...
+0.737957515573  2.90430582851   6   -0.0422721010314    0.4178952497 ...
+0.649532581668  0.657135682543  6   0.692066153971  0.422299120276 ...
+0.627159201987  1.70352689913   5.75    2.62066711305   -1.29237304034 ...
+0.905441299817  1.95663197267   5.5 1.5949697565    -0.27115830703 ...
+1.49322577898   -2.08741765309  6.25    1.23027694802   0.418336889527 ...
+1.48750731567   -1.57274121871  8   3.01660550994   -0.893958254365 ...
+1.39783858087   2.22623066426   7   -0.80842319214  1.47625453886 ...
+0.89274836317   1.30378081742   8   -0.249485058661 0.159871204185 ...
+0.920652246088  4.1437741965    9.75    2.8204453623    0.178149239655 ...
+-0.00264276644799   3.07989972052   8.75    -2.56342461535  2.105998353 ...
+0.0198190461681 0.766283759256  8   -1.15838865989  1.56888883418 ...
+0.440050515311  0.127570085801  7.5 0.0400753569995 0.028914333532 ...
+0.129536637901  1.78174141526   6.75    0.959943962785  0.307781224401 ...
+0.398549827172  3.03606770667   6.5 -0.340209794742 0.100979469478 ...
+1.17174775425   0.629625188037  5.75    0.403003686814  0.902394579377 ...
+0.991163981251  2.50862910684   4.75    -1.44963996982  1.16150986945 ...
+0.967603566096  2.12003739013   4.75    0.610846030775  -0.889994896068 ...
+1.14689383604   1.24185011459   4.75    2.01098091308   -1.73846431001 ...
+1.32593824054   0.990713820685  4.75    -0.0955142989332    -0.0369257308362 ...
+0.861135002644  -0.24744943605  6   1.72793107135   -0.691506789639 ...
+1.26870850151   2.09844764887   6.5 1.50720217572   -1.31399187077 ...
+0.260364987715  1.10650139716   6.5 1.13659047496   0.0720441664643 ...
+1.09731242214   0.490796381346  7.25    4.59123894147   -2.14073070763 ...
+1.63792841781   0.612652594286  6.75    1.79604605035   -0.644363995357 ...
+1.48465576034   0.978295808687  6.75    -2.00753620902  1.39437534964 ...
+1.0987608663    4.25212569087   6.25    -2.58901196498  2.56054320803 ...
+1.42592178132   2.76984518311   6.25    0.888195752358  1.03114549274 ...
+1.52958239462   1.31795955491   6.5 -0.902907564082 -0.0952198893776 ...
+1.0170168994    2.14733589918   7   -1.3054866978   2.68803738466 ...
+0.723253652257  3.43552889347   7.5 1.8213700853    0.592593586195 ...
+1.24720806008   3.87383806577   7.5 0.0522300654168 0.988871238698 ...
+0.482531471239  2.67793287032   7.5 2.9693944293    -0.108591166081 ...
+0.154056100439  0.927269031704  6.75    0.119222057561  3.30489209451 ...
+0.0694865769274 6.65916526788   6.25    0.889014476084  -2.83976849035 ...
+-0.121267434867 0.341442615696  5.25    0.323053239216  -3.49289229012 ...
+0.726473690375  -3.5423730964   4   2.19149290449   -3.20855054004 ...
+1.39271709108   2.63121085718   3.75    0.88406577736   0.75622580197 ...
+1.07502077727   5.88578836799   4.25    -2.55088273352  2.89018116374 ...
+0.759049251607  4.24703604223   4.5 0.575687665685  -0.388292506167 ...
+]; 
+ 
+data = reshape(data,5,86)'; 
+y_obs = data(:,1); 
+pie_obs = data(:,2); 
+R_obs = data(:,3); 
+de = data(:,4); 
+dq = data(:,5); 
+ 
+%Country: Canada 
+%Sample Range: 1981:2 to 2002:3 
+%Observations: 86 
+%Variables: Real GDP Growth [%], Inflation [annualized %], Nom Rate [%], 
+%           Exchange Rate Change [%], Terms of Trade Change [%] 
diff --git a/tests/run_test_matlab.m b/tests/run_test_matlab.m
index c5a8c0755abc6cd710c7213a0424fcfc204a4b77..c861d7fdc954cfd2c90b5cf66820599e1872c2e0 100644
--- a/tests/run_test_matlab.m
+++ b/tests/run_test_matlab.m
@@ -78,7 +78,7 @@ for blockFlag = 0:1
         default_stack_solve_algo = 0;
         if ~blockFlag && ~bytecodeFlag
             solve_algos = 1:4;
-            stack_solve_algos = 0;
+            stack_solve_algos = [0 6];
         elseif blockFlag && ~bytecodeFlag
             solve_algos = [1:4 6:8];
             stack_solve_algos = 0:4;
diff --git a/tests/run_test_octave.m b/tests/run_test_octave.m
index 66f0c0cbd0895bbacd08dcd67d1cfa4c69421e50..26742a6a2277b93cc3d93a6e5507be92ca124f1f 100644
--- a/tests/run_test_octave.m
+++ b/tests/run_test_octave.m
@@ -75,7 +75,7 @@ for blockFlag = 0:1
         default_stack_solve_algo = 0;
         if !blockFlag && !bytecodeFlag
             solve_algos = 0:4;
-            stack_solve_algos = 0;
+            stack_solve_algos = [0 6];
         elseif blockFlag && !bytecodeFlag
             solve_algos = [0:4 6 8];
             stack_solve_algos = [0 1 3 4];
diff --git a/tests/steady_state/multi_leads.mod b/tests/steady_state/multi_leads.mod
index 8d6d3c8774635298e1cbad5df89c56c040753a19..85573c3f8ac4912081942447265800cafb022289 100644
--- a/tests/steady_state/multi_leads.mod
+++ b/tests/steady_state/multi_leads.mod
@@ -1,27 +1,27 @@
-    @#define N = 4
-    var A B;
-    varexo eB;
-    parameters Bss rho;
-
-    Bss=1;
-    rho=0.9;
-
-    model;
-    A = B(@{N});
-    B = (1-rho)*Bss +rho*B(-1) +eB;
-    end;
-
-    steady_state_model;
-    A = Bss;
-    B = Bss;
-    end;
-
-    resid;
-    steady;
-    check;
-
-    shocks;
-    var eB ; stderr 1 ;
-    end;
-
-    stoch_simul(order=1,irf=0) ;
+    @#define N = 4
+    var A B;
+    varexo eB;
+    parameters Bss rho;
+
+    Bss=1;
+    rho=0.9;
+
+    model;
+    A = B(@{N});
+    B = (1-rho)*Bss +rho*B(-1) +eB;
+    end;
+
+    steady_state_model;
+    A = Bss;
+    B = Bss;
+    end;
+
+    resid;
+    steady;
+    check;
+
+    shocks;
+    var eB ; stderr 1 ;
+    end;
+
+    stoch_simul(order=1,irf=0) ;
diff --git a/tests/steady_state/walsh1_initval.mod b/tests/steady_state/walsh1_initval.mod
index b99016724fbe995a02525f7e2adabdc94a180f6d..bcbebc43faef89ffbd51c53ddc36cecba9195dde 100644
--- a/tests/steady_state/walsh1_initval.mod
+++ b/tests/steady_state/walsh1_initval.mod
@@ -1,68 +1,68 @@
-var y c k m n R pi z u;
-varexo	e sigma;	 
-// sigma stands for phi in the eq 2.37 p.69
-
-parameters alpha beta delta gamm phi1 eta a b rho  phi2 Psi thetass;  
-//phi1 stands for capital phi in eq.2.68 and 2.69
-//phi2 stands for lowercase phi in eq. 2.66
-
-change_type(var) Psi;
-change_type(parameters) n;
-
-alpha = 0.36;
-beta = 0.989; 
-gamm = 0.5;
-delta = 0.019;
-phi1 = 2;
-phi2 = 0;
-eta = 1;
-a = 0.95;
-b = 2.56;
-rho = 0.95;
-//Psi = 1.47630583;
-thetass = 1.0125;
-
-model;
-
-(a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*a*exp(c)^(-b) = (a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*(1-a)*exp(m)^(-b)+beta*(a*exp(c(+1))^(1-b)+(1-a)*exp(m(+1))^(1-b))^((b-phi1)/(1-b))*a*exp(c(+1))^(-b)/(1+pi(+1));
-
-Psi*(1-exp(n))^(-eta)/(a*exp(c)^(-b)*(a*exp(c)^(1-b) + (1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))) = (1-alpha)*exp(y)/exp(n);
-
-(a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*a*exp(c)^(-b) = beta*exp(R(+1))*(a*exp(c(+1))^(1-b)+(1-a)*exp(m(+1))^(1-b))^((b-phi1)/(1-b))*a*exp(c(+1))^(-b);
-
-exp(R) = alpha*exp(y)/exp(k(-1)) + 1-delta;
-
-exp(k) = (1-delta)*exp(k(-1))+exp(y)-exp(c);
-
-exp(y) = exp(z)*exp(k(-1))^alpha*exp(n)^(1-alpha);
-
-exp(m) = exp(m(-1))*(u+thetass)/(1+pi);
-
-z = rho*z(-1) + e;
-
-u = gamm*u(-1) + phi2*z(-1) + sigma;
-
-end;
-
-shocks;
-var e; stderr 0.007;
-var sigma;stderr 0.0089;
-end;
-
-n=log(1/3);
-
-initval;
-y =  0.2;
-c =  0.03;
-k =  2.7;
-m =  0.3;
-Psi = 1.5;
-R =  0.01;
-pi = 0.01;
-z = 0;
-u = 0;
-end;
-
-
-steady;
-
+var y c k m n R pi z u;
+varexo	e sigma;	 
+// sigma stands for phi in the eq 2.37 p.69
+
+parameters alpha beta delta gamm phi1 eta a b rho  phi2 Psi thetass;  
+//phi1 stands for capital phi in eq.2.68 and 2.69
+//phi2 stands for lowercase phi in eq. 2.66
+
+change_type(var) Psi;
+change_type(parameters) n;
+
+alpha = 0.36;
+beta = 0.989; 
+gamm = 0.5;
+delta = 0.019;
+phi1 = 2;
+phi2 = 0;
+eta = 1;
+a = 0.95;
+b = 2.56;
+rho = 0.95;
+//Psi = 1.47630583;
+thetass = 1.0125;
+
+model;
+
+(a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*a*exp(c)^(-b) = (a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*(1-a)*exp(m)^(-b)+beta*(a*exp(c(+1))^(1-b)+(1-a)*exp(m(+1))^(1-b))^((b-phi1)/(1-b))*a*exp(c(+1))^(-b)/(1+pi(+1));
+
+Psi*(1-exp(n))^(-eta)/(a*exp(c)^(-b)*(a*exp(c)^(1-b) + (1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))) = (1-alpha)*exp(y)/exp(n);
+
+(a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*a*exp(c)^(-b) = beta*exp(R(+1))*(a*exp(c(+1))^(1-b)+(1-a)*exp(m(+1))^(1-b))^((b-phi1)/(1-b))*a*exp(c(+1))^(-b);
+
+exp(R) = alpha*exp(y)/exp(k(-1)) + 1-delta;
+
+exp(k) = (1-delta)*exp(k(-1))+exp(y)-exp(c);
+
+exp(y) = exp(z)*exp(k(-1))^alpha*exp(n)^(1-alpha);
+
+exp(m) = exp(m(-1))*(u+thetass)/(1+pi);
+
+z = rho*z(-1) + e;
+
+u = gamm*u(-1) + phi2*z(-1) + sigma;
+
+end;
+
+shocks;
+var e; stderr 0.007;
+var sigma;stderr 0.0089;
+end;
+
+n=log(1/3);
+
+initval;
+y =  0.2;
+c =  0.03;
+k =  2.7;
+m =  0.3;
+Psi = 1.5;
+R =  0.01;
+pi = 0.01;
+z = 0;
+u = 0;
+end;
+
+
+steady;
+
diff --git a/tests/steady_state/walsh1_old_ss.mod b/tests/steady_state/walsh1_old_ss.mod
index 39eb8910d83e9406554a5891482f923ab21837e5..1b27d832d0715c3f741a3d03cafa189cb23384ba 100644
--- a/tests/steady_state/walsh1_old_ss.mod
+++ b/tests/steady_state/walsh1_old_ss.mod
@@ -1,51 +1,51 @@
-var y c k m n R pi z u;
-varexo	e sigma;	 
-// sigma stands for phi in the eq 2.37 p.69
-
-parameters alpha beta delta gamm phi1 eta a b rho  phi2 Psi thetass;  
-//phi1 stands for capital phi in eq.2.68 and 2.69
-//phi2 stands for lowercase phi in eq. 2.66
-
-alpha = 0.36;
-beta = 0.989; 
-gamm = 0.5;
-delta = 0.019;
-phi1 = 2;
-phi2 = 0;
-eta = 1;
-a = 0.95;
-b = 2.56;
-rho = 0.95;
-Psi = 1.47630583;
-thetass = 1.0125;
-
-model;
-
-(a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*a*exp(c)^(-b) = (a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*(1-a)*exp(m)^(-b)+beta*(a*exp(c(+1))^(1-b)+(1-a)*exp(m(+1))^(1-b))^((b-phi1)/(1-b))*a*exp(c(+1))^(-b)/(1+pi(+1));
-
-Psi*(1-exp(n))^(-eta)/(a*exp(c)^(-b)*(a*exp(c)^(1-b) + (1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))) = (1-alpha)*exp(y)/exp(n);
-
-(a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*a*exp(c)^(-b) = beta*exp(R(+1))*(a*exp(c(+1))^(1-b)+(1-a)*exp(m(+1))^(1-b))^((b-phi1)/(1-b))*a*exp(c(+1))^(-b);
-
-exp(R) = alpha*exp(y)/exp(k(-1)) + 1-delta;
-
-exp(k) = (1-delta)*exp(k(-1))+exp(y)-exp(c);
-
-exp(y) = exp(z)*exp(k(-1))^alpha*exp(n)^(1-alpha);
-
-exp(m) = exp(m(-1))*(u+thetass)/(1+pi);
-
-z = rho*z(-1) + e;
-
-u = gamm*u(-1) + phi2*z(-1) + sigma;
-
-end;
-
-shocks;
-var e; stderr 0.007;
-var sigma;stderr 0.0089;
-end;
-
-
-steady;
-
+var y c k m n R pi z u;
+varexo	e sigma;	 
+// sigma stands for phi in the eq 2.37 p.69
+
+parameters alpha beta delta gamm phi1 eta a b rho  phi2 Psi thetass;  
+//phi1 stands for capital phi in eq.2.68 and 2.69
+//phi2 stands for lowercase phi in eq. 2.66
+
+alpha = 0.36;
+beta = 0.989; 
+gamm = 0.5;
+delta = 0.019;
+phi1 = 2;
+phi2 = 0;
+eta = 1;
+a = 0.95;
+b = 2.56;
+rho = 0.95;
+Psi = 1.47630583;
+thetass = 1.0125;
+
+model;
+
+(a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*a*exp(c)^(-b) = (a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*(1-a)*exp(m)^(-b)+beta*(a*exp(c(+1))^(1-b)+(1-a)*exp(m(+1))^(1-b))^((b-phi1)/(1-b))*a*exp(c(+1))^(-b)/(1+pi(+1));
+
+Psi*(1-exp(n))^(-eta)/(a*exp(c)^(-b)*(a*exp(c)^(1-b) + (1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))) = (1-alpha)*exp(y)/exp(n);
+
+(a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*a*exp(c)^(-b) = beta*exp(R(+1))*(a*exp(c(+1))^(1-b)+(1-a)*exp(m(+1))^(1-b))^((b-phi1)/(1-b))*a*exp(c(+1))^(-b);
+
+exp(R) = alpha*exp(y)/exp(k(-1)) + 1-delta;
+
+exp(k) = (1-delta)*exp(k(-1))+exp(y)-exp(c);
+
+exp(y) = exp(z)*exp(k(-1))^alpha*exp(n)^(1-alpha);
+
+exp(m) = exp(m(-1))*(u+thetass)/(1+pi);
+
+z = rho*z(-1) + e;
+
+u = gamm*u(-1) + phi2*z(-1) + sigma;
+
+end;
+
+shocks;
+var e; stderr 0.007;
+var sigma;stderr 0.0089;
+end;
+
+
+steady;
+
diff --git a/tests/steady_state/walsh1_old_ss_steadystate.m b/tests/steady_state/walsh1_old_ss_steadystate.m
index 61443ddbb80fa6f4e634c9f8dd057448ce41e5d0..125c652d78019fa1c7ec4e6fcfa67eb3225ab283 100644
--- a/tests/steady_state/walsh1_old_ss_steadystate.m
+++ b/tests/steady_state/walsh1_old_ss_steadystate.m
@@ -1,4 +1,4 @@
-function [ys,check] = wlash1_old_ss_steadystate(ys0,exo)
+function [ys,check] = walsh1_old_ss_steadystate(ys0,exo)
     global M_
     
     check = 0;
diff --git a/tests/steady_state/walsh1_ssm.mod b/tests/steady_state/walsh1_ssm.mod
index 8d1de749e0f4ba2449e0ca4cc7d010b430632871..11ad8da6b5da51bac483cf792105ded79f4e9f66 100644
--- a/tests/steady_state/walsh1_ssm.mod
+++ b/tests/steady_state/walsh1_ssm.mod
@@ -1,72 +1,72 @@
-var y c k m n R pi z u;
-varexo	e sigma;	 
-// sigma stands for phi in the eq 2.37 p.69
-
-parameters alpha beta delta gamm phi1 eta a b rho  phi2 Psi thetass;  
-//phi1 stands for capital phi in eq.2.68 and 2.69
-//phi2 stands for lowercase phi in eq. 2.66
-
-alpha = 0.36;
-beta = 0.989; 
-gamm = 0.5;
-delta = 0.019;
-phi1 = 2;
-phi2 = 0;
-eta = 1;
-a = 0.95;
-b = 2.56;
-rho = 0.95;
-Psi = 1.47630583;
-thetass = 1.0125;
-
-model;
-
-(a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*a*exp(c)^(-b) = (a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*(1-a)*exp(m)^(-b)+beta*(a*exp(c(+1))^(1-b)+(1-a)*exp(m(+1))^(1-b))^((b-phi1)/(1-b))*a*exp(c(+1))^(-b)/(1+pi(+1));
-
-Psi*(1-exp(n))^(-eta)/(a*exp(c)^(-b)*(a*exp(c)^(1-b) + (1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))) = (1-alpha)*exp(y)/exp(n);
-
-(a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*a*exp(c)^(-b) = beta*exp(R(+1))*(a*exp(c(+1))^(1-b)+(1-a)*exp(m(+1))^(1-b))^((b-phi1)/(1-b))*a*exp(c(+1))^(-b);
-
-exp(R) = alpha*exp(y)/exp(k(-1)) + 1-delta;
-
-exp(k) = (1-delta)*exp(k(-1))+exp(y)-exp(c);
-
-exp(y) = exp(z)*exp(k(-1))^alpha*exp(n)^(1-alpha);
-
-exp(m) = exp(m(-1))*(u+thetass)/(1+pi);
-
-z = rho*z(-1) + e;
-
-u = gamm*u(-1) + phi2*z(-1) + sigma;
-
-end;
-
-shocks;
-var e; stderr 0.007;
-var sigma;stderr 0.0089;
-end;
-
-steady_state_model;
-// solving in levels
-// calibrating n = 1/3 and recovering the value of Psi
-// adapting solution Walsh (2003) p. 84
-pi = thetass-1;
-en = 1/3;
-eR = 1/beta;
-y_k = (1/alpha)*(1/beta-1+delta);
-ek = en*y_k^(-1/(1-alpha));
-ec = ek*(y_k-delta);
-em = ec*(a/(1-a))^(-1/b)*((thetass-beta)/thetass)^(-1/b);
-ey = ek*y_k;
-Xss = a*ec^(1-b)*(1+(a/(1-a))^(-1/b)*((thetass-beta)/thetass)^((b-1)/b));
-Psi = (1-alpha)*(ey/en)*Xss^((b-phi1)/(1-b))*a*ec^(-b)*(1-en)^eta;
-n = log(en);
-k = log(ek);
-m = log(em);
-c = log(ec);
-y = log(ey);
-R = log(eR);
-end;
-
-steady;
-
+var y c k m n R pi z u;
+varexo	e sigma;	 
+// sigma stands for phi in the eq 2.37 p.69
+
+parameters alpha beta delta gamm phi1 eta a b rho  phi2 Psi thetass;  
+//phi1 stands for capital phi in eq.2.68 and 2.69
+//phi2 stands for lowercase phi in eq. 2.66
+
+alpha = 0.36;
+beta = 0.989; 
+gamm = 0.5;
+delta = 0.019;
+phi1 = 2;
+phi2 = 0;
+eta = 1;
+a = 0.95;
+b = 2.56;
+rho = 0.95;
+Psi = 1.47630583;
+thetass = 1.0125;
+
+model;
+
+(a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*a*exp(c)^(-b) = (a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*(1-a)*exp(m)^(-b)+beta*(a*exp(c(+1))^(1-b)+(1-a)*exp(m(+1))^(1-b))^((b-phi1)/(1-b))*a*exp(c(+1))^(-b)/(1+pi(+1));
+
+Psi*(1-exp(n))^(-eta)/(a*exp(c)^(-b)*(a*exp(c)^(1-b) + (1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))) = (1-alpha)*exp(y)/exp(n);
+
+(a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*a*exp(c)^(-b) = beta*exp(R(+1))*(a*exp(c(+1))^(1-b)+(1-a)*exp(m(+1))^(1-b))^((b-phi1)/(1-b))*a*exp(c(+1))^(-b);
+
+exp(R) = alpha*exp(y)/exp(k(-1)) + 1-delta;
+
+exp(k) = (1-delta)*exp(k(-1))+exp(y)-exp(c);
+
+exp(y) = exp(z)*exp(k(-1))^alpha*exp(n)^(1-alpha);
+
+exp(m) = exp(m(-1))*(u+thetass)/(1+pi);
+
+z = rho*z(-1) + e;
+
+u = gamm*u(-1) + phi2*z(-1) + sigma;
+
+end;
+
+shocks;
+var e; stderr 0.007;
+var sigma;stderr 0.0089;
+end;
+
+steady_state_model;
+// solving in levels
+// calibrating n = 1/3 and recovering the value of Psi
+// adapting solution Walsh (2003) p. 84
+pi = thetass-1;
+en = 1/3;
+eR = 1/beta;
+y_k = (1/alpha)*(1/beta-1+delta);
+ek = en*y_k^(-1/(1-alpha));
+ec = ek*(y_k-delta);
+em = ec*(a/(1-a))^(-1/b)*((thetass-beta)/thetass)^(-1/b);
+ey = ek*y_k;
+Xss = a*ec^(1-b)*(1+(a/(1-a))^(-1/b)*((thetass-beta)/thetass)^((b-1)/b));
+Psi = (1-alpha)*(ey/en)*Xss^((b-phi1)/(1-b))*a*ec^(-b)*(1-en)^eta;
+n = log(en);
+k = log(ek);
+m = log(em);
+c = log(ec);
+y = log(ey);
+R = log(eR);
+end;
+
+steady;
+
diff --git a/tests/steady_state/walsh1_ssm_block.mod b/tests/steady_state/walsh1_ssm_block.mod
index 05bd18125390f4b9829b493ef9300a63d918ae74..38fe294ee689e283ed5b5d70bd08dfcf4884b6e3 100644
--- a/tests/steady_state/walsh1_ssm_block.mod
+++ b/tests/steady_state/walsh1_ssm_block.mod
@@ -1,72 +1,72 @@
-var y c k m n R pi z u;
-varexo	e sigma;	 
-// sigma stands for phi in the eq 2.37 p.69
-
-parameters alpha beta delta gamm phi1 eta a b rho  phi2 Psi thetass;  
-//phi1 stands for capital phi in eq.2.68 and 2.69
-//phi2 stands for lowercase phi in eq. 2.66
-
-alpha = 0.36;
-beta = 0.989; 
-gamm = 0.5;
-delta = 0.019;
-phi1 = 2;
-phi2 = 0;
-eta = 1;
-a = 0.95;
-b = 2.56;
-rho = 0.95;
-Psi = 1.47630583;
-thetass = 1.0125;
-
-model(block);
-
-(a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*a*exp(c)^(-b) = (a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*(1-a)*exp(m)^(-b)+beta*(a*exp(c(+1))^(1-b)+(1-a)*exp(m(+1))^(1-b))^((b-phi1)/(1-b))*a*exp(c(+1))^(-b)/(1+pi(+1));
-
-Psi*(1-exp(n))^(-eta)/(a*exp(c)^(-b)*(a*exp(c)^(1-b) + (1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))) = (1-alpha)*exp(y)/exp(n);
-
-(a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*a*exp(c)^(-b) = beta*exp(R(+1))*(a*exp(c(+1))^(1-b)+(1-a)*exp(m(+1))^(1-b))^((b-phi1)/(1-b))*a*exp(c(+1))^(-b);
-
-exp(R) = alpha*exp(y)/exp(k(-1)) + 1-delta;
-
-exp(k) = (1-delta)*exp(k(-1))+exp(y)-exp(c);
-
-exp(y) = exp(z)*exp(k(-1))^alpha*exp(n)^(1-alpha);
-
-exp(m) = exp(m(-1))*(u+thetass)/(1+pi);
-
-z = rho*z(-1) + e;
-
-u = gamm*u(-1) + phi2*z(-1) + sigma;
-
-end;
-
-shocks;
-var e; stderr 0.007;
-var sigma;stderr 0.0089;
-end;
-
-steady_state_model;
-// solving in levels
-// calibrating n = 1/3 and recovering the value of Psi
-// adapting solution Walsh (2003) p. 84
-pi = thetass-1;
-en = 1/3;
-eR = 1/beta;
-y_k = (1/alpha)*(1/beta-1+delta);
-ek = en*y_k^(-1/(1-alpha));
-ec = ek*(y_k-delta);
-em = ec*(a/(1-a))^(-1/b)*((thetass-beta)/thetass)^(-1/b);
-ey = ek*y_k;
-Xss = a*ec^(1-b)*(1+(a/(1-a))^(-1/b)*((thetass-beta)/thetass)^((b-1)/b));
-Psi = (1-alpha)*(ey/en)*Xss^((b-phi1)/(1-b))*a*ec^(-b)*(1-en)^eta;
-n = log(en);
-k = log(ek);
-m = log(em);
-c = log(ec);
-y = log(ey);
-R = log(eR);
-end;
-
-steady;
-
+var y c k m n R pi z u;
+varexo	e sigma;	 
+// sigma stands for phi in the eq 2.37 p.69
+
+parameters alpha beta delta gamm phi1 eta a b rho  phi2 Psi thetass;  
+//phi1 stands for capital phi in eq.2.68 and 2.69
+//phi2 stands for lowercase phi in eq. 2.66
+
+alpha = 0.36;
+beta = 0.989; 
+gamm = 0.5;
+delta = 0.019;
+phi1 = 2;
+phi2 = 0;
+eta = 1;
+a = 0.95;
+b = 2.56;
+rho = 0.95;
+Psi = 1.47630583;
+thetass = 1.0125;
+
+model(block);
+
+(a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*a*exp(c)^(-b) = (a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*(1-a)*exp(m)^(-b)+beta*(a*exp(c(+1))^(1-b)+(1-a)*exp(m(+1))^(1-b))^((b-phi1)/(1-b))*a*exp(c(+1))^(-b)/(1+pi(+1));
+
+Psi*(1-exp(n))^(-eta)/(a*exp(c)^(-b)*(a*exp(c)^(1-b) + (1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))) = (1-alpha)*exp(y)/exp(n);
+
+(a*exp(c)^(1-b)+(1-a)*exp(m)^(1-b))^((b-phi1)/(1-b))*a*exp(c)^(-b) = beta*exp(R(+1))*(a*exp(c(+1))^(1-b)+(1-a)*exp(m(+1))^(1-b))^((b-phi1)/(1-b))*a*exp(c(+1))^(-b);
+
+exp(R) = alpha*exp(y)/exp(k(-1)) + 1-delta;
+
+exp(k) = (1-delta)*exp(k(-1))+exp(y)-exp(c);
+
+exp(y) = exp(z)*exp(k(-1))^alpha*exp(n)^(1-alpha);
+
+exp(m) = exp(m(-1))*(u+thetass)/(1+pi);
+
+z = rho*z(-1) + e;
+
+u = gamm*u(-1) + phi2*z(-1) + sigma;
+
+end;
+
+shocks;
+var e; stderr 0.007;
+var sigma;stderr 0.0089;
+end;
+
+steady_state_model;
+// solving in levels
+// calibrating n = 1/3 and recovering the value of Psi
+// adapting solution Walsh (2003) p. 84
+pi = thetass-1;
+en = 1/3;
+eR = 1/beta;
+y_k = (1/alpha)*(1/beta-1+delta);
+ek = en*y_k^(-1/(1-alpha));
+ec = ek*(y_k-delta);
+em = ec*(a/(1-a))^(-1/b)*((thetass-beta)/thetass)^(-1/b);
+ey = ek*y_k;
+Xss = a*ec^(1-b)*(1+(a/(1-a))^(-1/b)*((thetass-beta)/thetass)^((b-1)/b));
+Psi = (1-alpha)*(ey/en)*Xss^((b-phi1)/(1-b))*a*ec^(-b)*(1-en)^eta;
+n = log(en);
+k = log(ek);
+m = log(em);
+c = log(ec);
+y = log(ey);
+R = log(eR);
+end;
+
+steady;
+
diff --git a/tests/test.m b/tests/test.m
index f05f5f1c45875b0508f622724647c0285081f9e1..a23db431124a39b27d5d3bde662f34277192058c 100644
--- a/tests/test.m
+++ b/tests/test.m
@@ -1,4 +1,4 @@
-function test(a,b,n)
-  if max(max(abs(a)-abs(b))) > 1e-5
-    error(['Test error in test ' int2str(n)])
+function test(a,b,n)
+  if max(max(abs(a)-abs(b))) > 1e-5
+    error(['Test error in test ' int2str(n)])
   end
\ No newline at end of file
diff --git a/tests/walsh.mod b/tests/walsh.mod
new file mode 100644
index 0000000000000000000000000000000000000000..606746ca10823202e355a6c0bf1ad69a8e5062aa
--- /dev/null
+++ b/tests/walsh.mod
@@ -0,0 +1,225 @@
+@#define Blocks = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15","16", "17", "18", "19", "20", "21", "22", "23", "24", "25","26", "27", "28", "29", "30", "31", "32", "33", "34", "35","36", "37", "38", "39", "40", "41", "42", "43", "44", "45","46", "47", "48", "49", "50", "51", "52", "53", "54", "55","56", "57", "58", "59", "60", "61", "62", "63", "64", "65","66", "67", "68", "69", "70", "71", "72", "73", "74", "75","76", "77", "78", "79", "80", "81", "82", "83", "84", "85","86", "87", "88", "89", "90", "91", "92", "93", "94", "95","96", "97", "98", "99", "100", "101", "102", "103", "104", "105", "106", "107", "108", "109", "110", "111", "112", "113", "114", "115","116", "117", "118", "119", "120", "121", "122", "123", "124", "125","126", "127", "128", "129", "130", "131", "132", "133", "134", "135","136", "137", "138", "139", "140", "141", "142", "143", "144", "145","146", "147", "148", "149", "150", "151", "152", "153", "154", "155","156", "157", "158", "159", "160", "161", "162", "163", "164", "165","166", "167", "168", "169", "170", "171", "172", "173", "174", "175","176", "177", "178", "179", "180", "181", "182", "183", "184", "185","186", "187", "188", "189", "190", "191", "192", "193", "194", "195","196", "197", "198", "199", "200"]
+
+@#define blocks = Blocks[1:20]
+
+@#for block in blocks
+  var y_@{block} c_@{block} k_@{block} m_@{block} n_@{block} R_@{block} pi_@{block} z_@{block} u_@{block};
+@#endfor
+
+@#for block in blocks
+varexo	e_@{block} sigma_@{block};
+@#endfor
+
+// sigma stands for phi in the eq 2.37 p.69
+
+parameters alpha beta delta gamm phi1 eta a b rho  phi2 Psi thetass;
+//phi1 stands for capital phi in eq.2.68 and 2.69
+//phi2 stands for lowercase phi in eq. 2.66
+
+alpha = 0.36;
+beta = 0.989;
+gamm = 0.5;
+delta = 0.019;
+phi1 = 2;
+phi2 = 0;
+eta = 1;
+a = 0.95;
+b = 2.56;
+rho = 0.95;
+Psi = 1.47630583;
+thetass = 1.0125;
+
+model(use_dll);
+
+@#for block in blocks
+(a*exp(c_@{block})^(1-b)+(1-a)*exp(m_@{block})^(1-b))^((b-phi1)/(1-b))*a*exp(c_@{block})^(-b) = (a*exp(c_@{block})^(1-b)+(1-a)*exp(m_@{block})^(1-b))^((b-phi1)/(1-b))*(1-a)*exp(m_@{block})^(-b)+beta*(a*exp(c_@{block}(+1))^(1-b)+(1-a)*exp(m_@{block}(+1))^(1-b))^((b-phi1)/(1-b))*a*exp(c_@{block}(+1))^(-b)/(1+pi_@{block}(+1));
+
+Psi*(1-exp(n_@{block}))^(-eta)/(a*exp(c_@{block})^(-b)*(a*exp(c_@{block})^(1-b) + (1-a)*exp(m_@{block})^(1-b))^((b-phi1)/(1-b))) = (1-alpha)*exp(y_@{block})/exp(n_@{block});
+
+(a*exp(c_@{block})^(1-b)+(1-a)*exp(m_@{block})^(1-b))^((b-phi1)/(1-b))*a*exp(c_@{block})^(-b) = beta*exp(R_@{block}(+1))*(a*exp(c_@{block}(+1))^(1-b)+(1-a)*exp(m_@{block}(+1))^(1-b))^((b-phi1)/(1-b))*a*exp(c_@{block}(+1))^(-b);
+
+exp(R_@{block}) = alpha*exp(y_@{block})/exp(k_@{block}(-1)) + 1-delta;
+
+exp(k_@{block}) = (1-delta)*exp(k_@{block}(-1))+exp(y_@{block})-exp(c_@{block});
+
+exp(y_@{block}) = exp(z_@{block})*exp(k_@{block}(-1))^alpha*exp(n_@{block})^(1-alpha);
+
+exp(m_@{block}) = exp(m_@{block}(-1))*(u_@{block}+thetass)/(1+pi_@{block});
+
+z_@{block} = rho*z_@{block}(-1) + e_@{block};
+
+u_@{block} = gamm*u_@{block}(-1) + phi2*z_@{block}(-1) + sigma_@{block};
+
+@#endfor
+
+end;
+
+shocks;
+@#for block in blocks
+  var e_@{block}; stderr 0.007;
+  var sigma_@{block};stderr 0.0089;
+@#endfor
+end;
+
+steady_state_model;
+// solving in levels
+// calibrating n = 1/3 and recovering the value of Psi
+// adapting solution Walsh (2003) p. 84
+en = 1/3;
+eR = 1/beta;
+y_k = (1/alpha)*(1/beta-1+delta);
+ek = en*y_k^(-1/(1-alpha));
+ec = ek*(y_k-delta);
+em = ec*(a/(1-a))^(-1/b)*((thetass-beta)/thetass)^(-1/b);
+ey = ek*y_k;
+Xss = a*ec^(1-b)*(1+(a/(1-a))^(-1/b)*((thetass-beta)/thetass)^((b-1)/b));
+Psi = (1-alpha)*(ey/en)*Xss^((b-phi1)/(1-b))*a*ec^(-b)*(1-en)^eta;
+@#for block in blocks
+  pi_@{block} = thetass-1;
+  n_@{block} = log(en);
+  k_@{block} = log(ek);
+  m_@{block} = log(em);
+  c_@{block} = log(ec);
+  y_@{block} = log(ey);
+  R_@{block} = log(eR);
+@#endfor
+end;
+
+steady;
+
+loop_size = 100;
+
+tic;
+for i=1:loop_size
+  stoch_simul(order=1,irf=0,noprint,nomoments,dr=default);
+  dr = oo_.dr;
+end;
+e1 = toc;
+
+tic;
+for i=1:loop_size
+  stoch_simul(order=1,irf=0,noprint,nomoments,dr=cycle_reduction);
+  DR = oo_.dr;
+end;
+e2 = toc;
+
+tic;
+for i=1:loop_size
+  stoch_simul(order=1,irf=0,noprint,nomoments,dr=cycle_reduction,dr_cycle_reduction_tol=1e-6);
+  DR_ = oo_.dr;
+end;
+e3 = toc;
+
+tic;
+for i=1:loop_size
+  stoch_simul(order=1,irf=0,noprint,nomoments,dr=cycle_reduction,dr_cycle_reduction_tol=1e-5);
+  DR__ = oo_.dr;
+end;
+e4 = toc;
+
+tic;
+for i=1:loop_size
+  stoch_simul(order=1,irf=0,noprint,nomoments,dr=cycle_reduction,dr_cycle_reduction_tol=1e-4);
+  DR___ = oo_.dr;
+end;
+e5 = toc;
+
+tic;
+for i=1:loop_size
+  stoch_simul(order=1,irf=0,noprint,nomoments,dr=cycle_reduction,dr_cycle_reduction_tol=1e-3);
+  DR____ = oo_.dr;
+end;
+e6 = toc;
+
+tic;
+for i=1:loop_size
+  stoch_simul(order=1,irf=0,noprint,nomoments,dr=cycle_reduction,dr_cycle_reduction_tol=1e-2);
+  DR_____ = oo_.dr;
+end;
+e7 = toc;
+
+tic;
+for i=1:loop_size
+  stoch_simul(order=1,irf=0,noprint,nomoments,dr=cycle_reduction,dr_cycle_reduction_tol=200);
+  DR______ = oo_.dr;
+end;
+e8 = toc;
+
+disp(['Elapsed time (QZ algorithm): ' num2str(e1)])
+disp(['Elapsed time (Cycle reduction algorithm, tol = 1e-7): ' num2str(e2)])
+disp(['Elapsed time (Cycle reduction algorithm, tol = 1e-6): ' num2str(e3)])
+disp(['Elapsed time (Cycle reduction algorithm, tol = 1e-5): ' num2str(e4)])
+disp(['Elapsed time (Cycle reduction algorithm, tol = 1e-4): ' num2str(e5)])
+disp(['Elapsed time (Cycle reduction algorithm, tol = 1e-3): ' num2str(e6)])
+disp(['Elapsed time (Cycle reduction algorithm, tol = 1e-2): ' num2str(e7)])
+disp(['Elapsed time (Cycle reduction algorithm, tol = 1e-1): ' num2str(e8)])
+
+if e1<e2
+   disp(['cycle reduction algorithm is slower than QZ algorithm in solving the model (' int2str(M_.endo_nbr) ' equations)!'])
+end
+
+dx = max(max(dr.ghx-DR.ghx));
+du = max(max(dr.ghu-DR.ghu));
+dx_ = max(max(dr.ghx-DR_.ghx));
+du_ = max(max(dr.ghu-DR_.ghu));
+dx__ = max(max(dr.ghx-DR__.ghx));
+du__ = max(max(dr.ghu-DR__.ghu));
+dx___ = max(max(dr.ghx-DR___.ghx));
+du___ = max(max(dr.ghu-DR___.ghu));
+dx____ = max(max(dr.ghx-DR____.ghx));
+du____ = max(max(dr.ghu-DR____.ghu));
+dx_____ = max(max(dr.ghx-DR_____.ghx));
+du_____ = max(max(dr.ghu-DR_____.ghu));
+dx______ = max(max(dr.ghx-DR______.ghx));
+du______ = max(max(dr.ghu-DR______.ghu));
+
+
+if dx>1e-8
+   error('QZ and Cycle reduction algorithms don''t return the same results (tolerance parameter is 1e-7)!')
+end
+
+if du>1e-8
+   error('QZ and Cycle reduction algorithms don''t return the same results (tolerance parameter is 1e-7)!')
+end
+
+if dx_>1e-8 || du_>1e-8
+   disp('QZ and Cycle reduction algorithms don''t return the same results (tolerance parameter is 1e-6)!')
+else
+   [dx, dx_]
+   [du, du_]
+end
+
+if dx__>1e-8 || du__>1e-8
+   disp('QZ and Cycle reduction algorithms don''t return the same results (tolerance parameter is 1e-5)!')
+else
+   [dx, dx_, dx__]
+   [du, du_, du__]
+end
+
+if dx___>1e-8 || du___>1e-8
+   disp('QZ and Cycle reduction algorithms don''t return the same results (tolerance parameter is 1e-4)!')
+else
+   [dx, dx_, dx__, dx___]
+   [du, du_, du__, du___]
+end
+
+if dx____>1e-8 || du____>1e-8
+   disp('QZ and Cycle reduction algorithms don''t return the same results (tolerance parameter is 1e-3)!')
+else
+   [dx, dx_, dx__, dx___,dx____]
+   [du, du_, du__, du___,du____]
+end
+
+if dx_____>1e-8 || du_____>1e-8
+   disp('QZ and Cycle reduction algorithms don''t return the same results (tolerance parameter is 1e-2)!')
+else
+   [dx, dx_, dx__, dx___,dx____,dx_____]
+   [du, du_, du__, du___,du____,du_____]
+end
+
+if dx_____>1e-8 || du_____>1e-8
+   disp('QZ and Cycle reduction algorithms don''t return the same results (tolerance parameter is 1e-1)!')
+else
+   [dx, dx_, dx__, dx___,dx____,dx_____,dx______]
+   [du, du_, du__, du___,du____,du_____,du______]
+end
\ No newline at end of file
diff --git a/windows/README.txt b/windows/README.txt
index bf787983762d5ab1908ad94b15edb88bb297c1f9..c03aed769c8e036c2ad9038210f29a50ac0f3cd7 100644
--- a/windows/README.txt
+++ b/windows/README.txt
@@ -95,9 +95,11 @@ be displayed when you launch Dynare:
   [mex] Sylvester equation solution.
   [mex] Kronecker products.
   [mex] Sparse kronecker products.
+  [mex] Local state space iteration (second order).
   [mex] Bytecode evaluation.
   [mex] k-order perturbation solver.
   [mex] k-order solution simulation.
+  [mex] Quasi Monte-Carlo sequence (Sobol).
 
 On the contrary, if DLL are not detected, Dynare will fallback on
 slower alternatives written in M-files (only for some of the DLLs),
@@ -108,9 +110,11 @@ and display the following:
   [m]   Sylvester equation solution.
   [m]   Kronecker products.
   [m]   Sparse kronecker products.
+  [m]   Local state space iteration (second order).
   [no]  Bytecode evaluation.
   [no]  k-order perturbation solver.
   [no]  k-order solution simulation.
+  [no]  Quasi Monte-Carlo sequence (Sobol).
 
 In this last case, Dynare will run correctly on the basic features,
 but with suboptimal speed, and some features will be missing. There
diff --git a/windows/dynare.nsi b/windows/dynare.nsi
index 6b08d66e1ec7670ce2d64cb9ae512fe492d2ac18..c281d82af07e128c93611da8417a26d2c16ddafc 100644
--- a/windows/dynare.nsi
+++ b/windows/dynare.nsi
@@ -54,7 +54,7 @@ Section "Dynare core (preprocessor and M-files)"
  SectionIn RO
 !insertmacro DETERMINE_CONTEXT
  SetOutPath $INSTDIR
- File README.txt ..\NEWS mexopts-win32.bat mexopts-win64.bat ..\license.txt ..\dynare.el
+ File README.txt ..\NEWS mexopts-win32.bat mexopts-win64.bat ..\license.txt
 
  SetOutPath $INSTDIR\matlab
  File /r ..\matlab\*.m
@@ -63,6 +63,9 @@ Section "Dynare core (preprocessor and M-files)"
  SetOutPath $INSTDIR\contrib
  File /r ..\contrib\*.m
 
+ SetOutPath $INSTDIR\scripts
+ File /r ..\scripts\*
+
  WriteUninstaller $INSTDIR\uninstall.exe
 
  # Create start menu entries
@@ -157,13 +160,13 @@ Section "Uninstall"
  Delete $INSTDIR\license.txt
  Delete $INSTDIR\mexopts-win32.bat
  Delete $INSTDIR\mexopts-win64.bat
- Delete $INSTDIR\dynare.el
  Rmdir /r $INSTDIR\matlab
  Rmdir /r $INSTDIR\contrib
  Rmdir /r $INSTDIR\mex
  Rmdir /r $INSTDIR\dynare++
  Rmdir /r $INSTDIR\doc
  Rmdir /r $INSTDIR\examples
+ Rmdir /r $INSTDIR\scripts
  # We don't force deletion of installation directory (with /r), to avoid deleting important files
  Rmdir $INSTDIR