diff --git a/.gitignore b/.gitignore
index 6feb4505791daaf9c7175e2c360147a635dfebcf..ff09453b754322c625e31c013e1edc3165ef1ed3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -113,8 +113,7 @@ mex/build/matlab/run_m2html.m
 /preprocessor/doc/
 
 # MATLAB dir
-/matlab/dynare_m
-/matlab/dynare_m.exe
+/matlab/preprocessor*
 /matlab/dynare_version.m
 
 # DLL rules
diff --git a/.gitmodules b/.gitmodules
index 984c87900d99f0630e5ea4dba274a727cbad38a6..37399d3b103c4ee495b816415fd8cb78352f3283 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -23,4 +23,7 @@
 [submodule "matlab/modules/dseries"]
 	path = matlab/modules/dseries
 	url = https://github.com/DynareTeam/dseries.git
-	branch = old-oop-style
\ No newline at end of file
+	branch = old-oop-style
+[submodule "matlab/modules/reporting"]
+	path = matlab/modules/reporting
+	url = https://github.com/DynareTeam/reporting.git
\ No newline at end of file
diff --git a/Makefile.am b/Makefile.am
index d14a0f35165e371ccab98919eed52411375544db..7b23cec883b69b5b5c3acb6719f1a6b554dd75b8 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -35,17 +35,25 @@ EXTRA_DIST = \
 
 dist-hook:
 	rm -rf `find $(distdir)/matlab $(distdir)/examples -name *~`
-	rm -f $(distdir)/matlab/dynare_m$(EXEEXT) $(distdir)/matlab/dynare_version.m
+	rm -rf $(distdir)/matlab/preprocessor* $(distdir)/matlab/dynare_version.m
 	$(MKDIR_P) $(distdir)/mex/matlab $(distdir)/mex/octave
 	rm -rf `find $(distdir)/contrib -name '.git*'`
 
 install-exec-local:
 	$(MKDIR_P) $(DESTDIR)$(pkglibdir)/contrib/ms-sbvar/TZcode
+	cp -r contrib/ms-sbvar/TZcode/MatlabFiles $(DESTDIR)$(pkglibdir)/contrib/ms-sbvar/TZcode
 	cp -r examples $(DESTDIR)$(pkglibdir)
 	cp -r matlab $(DESTDIR)$(pkglibdir)
-	rm -f $(DESTDIR)$(pkglibdir)/matlab/dynare_m
-	cp preprocessor/dynare_m $(DESTDIR)$(pkglibdir)/matlab
-	cp -r contrib/ms-sbvar/TZcode/MatlabFiles $(DESTDIR)$(pkglibdir)/contrib/ms-sbvar/TZcode
+	rm -rf $(DESTDIR)$(pkglibdir)/matlab/preprocessor*
+	{ \
+	if [ -z "`file preprocessor/dynare_m | grep x86.64`" ]; then \
+	  ARCH="32"; \
+	else \
+	  ARCH="64"; \
+	fi; \
+	mkdir -p $(DESTDIR)$(pkglibdir)/matlab/preprocessor$$ARCH; \
+	cp preprocessor/dynare_m $(DESTDIR)$(pkglibdir)/matlab/preprocessor$$ARCH; \
+	}
 
 uninstall-local:
 	rm -f  $(DESTDIR)$(bindir)/dynare++
diff --git a/README.md b/README.md
index 3c65155fe141290a02db6129c9bb03ca3db1c7d3..5f46b8734f9a3713e90f9c91db91962ac6fe27b2 100644
--- a/README.md
+++ b/README.md
@@ -137,6 +137,7 @@ apt-get build-dep dynare
 Alternatively, if you want to build everything, manually install the following packages:
 
 - `build-essential` (for gcc, g++ and make)
+- `gfortran`
 - `liboctave-dev` or `octave3.2-headers` (will install ATLAS)
 - `libboost-graph-dev`
 - `libgsl0-dev`
diff --git a/README.extended-preprocessor.org b/README/README.extended-preprocessor.org
similarity index 100%
rename from README.extended-preprocessor.org
rename to README/README.extended-preprocessor.org
diff --git a/doc/dynare.texi b/doc/dynare.texi
index be8d36ec5b2453554805314e497719605e189910..2bc2608825abe304d3c73fa83b204702279df6c2 100644
--- a/doc/dynare.texi
+++ b/doc/dynare.texi
@@ -95,7 +95,7 @@
 @c %**end of header
 
 @copying
-Copyright @copyright{} 1996-2014, Dynare Team.
+Copyright @copyright{} 1996-2015, Dynare Team.
 
 @quotation
 Permission is granted to copy, distribute and/or modify this document
@@ -241,13 +241,19 @@ Stochastic solution and simulation
 
 Sensitivity and identification analysis
 
+* Performing sensitivity analysis::
+* Performing identification analysis::
+* IRF/Moment calibration::
+* Types of analysis and output files::
+
+Types of analysis and output files
 * Sampling::
 * Stability Mapping::
+* IRF/Moment restrictions::
 * Reduced Form Mapping::
 * RMSE::
 * Screening Analysis::
 * Identification Analysis::
-* Performing Sensitivity and Identification Analysis::
 
 Macro-processing language
 
@@ -727,9 +733,17 @@ cannot be named @file{test.mod}.
 
 @item noclearall
 By default, @code{dynare} will issue a @code{clear all} command to
-MATLAB or Octave, thereby deleting all workspace variables; this options
+MATLAB or Octave, thereby deleting all workspace variables; this option
 instructs @code{dynare} not to clear the workspace
 
+@item onlyclearglobals
+By default, @code{dynare} will issue a @code{clear all} command to
+MATLAB or Octave, thereby deleting all workspace variables; this
+option instructs @code{dynare} to clear only the global variables
+(@i{i.e.} @code{M_}, @code{options_}, @code{oo_},
+@code{estim_params_}, @code{bayestopt_}, and @code{dataset_}), leaving
+the other variables in the workspace.
+
 @item debug
 Instructs the preprocessor to write some debugging information about the
 scanning and parsing of the @file{.mod} file
@@ -785,6 +799,15 @@ graph
 @item nointeractive
 Instructs Dynare to not request user input
 
+@item nopathchange
+By default Dynare will change Matlab/Octave's path if
+@file{dynare/matlab} directory is not on top and if Dynare's routines
+are overriden by routines provided in other toolboxes. If one wishes to
+override Dynare's routines, the @code{nopathchange} options can be
+used. Alternatively, the path can be temporarly modified by the user at
+the top of the @file{*.mod} file (using Matlab/Octave's @code{addpath}
+command).
+
 @item cygwin
 Tells Dynare that your MATLAB is configured for compiling MEX files with
 Cygwin (@pxref{Software requirements}). This option is only available
@@ -828,6 +851,14 @@ Allows Dynare to issue a warning and continue processing when
 @item there are more endogenous variables than equations
 @item an undeclared symbol is assigned in @code{initval} or @code{endval}
 @end enumerate
+
+@item fast
+Only useful with model option @code{use_dll}. Don't recompile the MEX
+files when running again the same model file and the lists of variables
+and the equations haven't changed. We use a 32 bit checksum, stored in
+@code{<model filename>/checksum}. There is a very small probability that
+the preprocessor misses a change in the model. In case of doubt, re-run
+without the @code{fast} option.
 @end table
 
 @outputhead
@@ -839,7 +870,7 @@ details are given under the relevant computing tasks.
 
 The @code{M_}, @code{oo_}, and @code{options_} structures are saved in
 a file called @file{@var{FILENAME}_results.mat}. If they exist,
-@code{estim_params_}, @code{bayestopt_}, @code{dataset_}, and
+@code{estim_params_}, @code{bayestopt_}, @code{dataset_}, @code{oo_recursive_} and
 @code{estimation_info} are saved in the same file.
 
 @examplehead
@@ -867,6 +898,14 @@ during the computation.
 Structure containing the various results of the computations.
 @end defvr
 
+@defvr {MATLAB/Octave variable} oo_recursive_
+@anchor{oo_recursive_}
+Cell array containing the @code{oo_} structures obtained when estimating the model 
+for the different samples when performing recursive estimation and forecasting. 
+The @code{oo_} structure obtained for the sample ranging to the @math{i}th observation 
+is saved in the @math{i}th field. The fields for non-estimated endpoints are empty.
+@end defvr
+
 
 @node Dynare hooks
 @section Dynare hooks
@@ -1859,10 +1898,33 @@ end;
 
 @end deffn
 
-Dynare has the ability to output the list of model equations to a
-@LaTeX{} file, using the @code{write_latex_dynamic_model} command. The
-static model can also be written with the
-@code{write_latex_static_model} command.
+Dynare has the ability to output the original list of model equations
+to a @LaTeX{} file, using the @code{write_latex_original_model}
+command, the list of transformed model equations using the
+@code{write_latex_dynamic_model} command, and the list of static model
+equations using the @code{write_latex_static_model} command.
+
+@anchor{write_latex_original_model}
+
+@deffn Command write_latex_original_model ;
+
+@descriptionhead
+
+This command creates a @LaTeX{} file containing the model, as defined
+in the model block.
+
+If your @file{.mod} file is @file{@var{FILENAME}.mod}, then Dynare
+will create a file called @file{@var{FILENAME}_dynamic.tex},
+containing the list of all the dynamic model equations.
+
+If @LaTeX{} names were given for variables and parameters
+(@pxref{Variable declarations}), then those will be used; otherwise,
+the plain text names will be used.
+
+Time subscripts (@code{t}, @code{t+1}, @code{t-1}, @dots{}) will be
+appended to the variable names, as @LaTeX{} subscripts.
+
+@end deffn
 
 @anchor{write_latex_dynamic_model}
 
@@ -2283,7 +2345,7 @@ jump from t=200 to t=201.
 @end deffn
 
 @deffn Block histval ;
-
+@anchor{histval}
 @descriptionhead
 
 @customhead{In a deterministic perfect foresight context}
@@ -2323,6 +2385,11 @@ affect the starting point for impulse response functions). As for the case of
 perfect foresight simulations, all not explicitly specified variables are set to 0.
 Moreover, as only states enter the recursive policy functions, all values specified for control variables will be ignored.
 
+For @ref{Ramsey} policy, it also specifies the values of the endogenous states at 
+which the objective function of the planner is computed. Note that the initial values 
+of the Lagrange multipliers associated with the planner's problem cannot be set
+(@pxref{planner_objective_value}).
+
 @examplehead
 
 @example
@@ -2389,7 +2456,7 @@ The command accepts three file formats:
 
 @item
 M-file (extension @file{.m}): for each endogenous and exogenous
-variable, the file must contain a row vector of the same name.
+variable, the file must contain a row or column vector of the same name. Their length must be @code{periods+M_.maximum_lag+M_.maximum_lead} 
 
 @item
 MAT-file (extension @file{.mat}): same as for M-files.
@@ -4612,6 +4679,11 @@ a @uref{http://www.java.com/download,Java Runtime Environment}). Note that the
 base name (ie without extension) of the datafile has to be different from the
 base name of the model file.
 
+@item dirname = @var{FILENAME}
+Directory in which to store @code{estimation} output. To pass a
+subdirectory of a directory, you must quote the argument. Default:
+@code{<mod_file>}
+
 @item xls_sheet = @var{NAME}
 @anchor{xls_sheet}
 The name of the sheet with the data in an Excel file
@@ -4630,7 +4702,7 @@ the file
 Runs a recursive estimation and forecast for samples of size ranging
 of @var{INTEGER1} to @var{INTEGER2}. Option @code{forecast} must
 also be specified. The forecasts are stored in the
-@code{RecursiveForecast} field of the results structure (@pxref{RecursiveForecast}).
+@code{RecursiveForecast} field of the results structure (@pxref{RecursiveForecast}). The respective results structures @code{oo_} are saved in @code{oo_recursive_} (@pxref{oo_recursive_}).
 
 @item first_obs = @var{INTEGER}
 @anchor{first_obs}
@@ -4800,10 +4872,11 @@ compute the smoothed value of the variables of a model with calibrated parameter
 
 @item 1
 Uses @code{fmincon} optimization routine (available under MATLAB if
-the optimization toolbox is installed; not available under Octave)
+the Optimization Toolbox is installed; not available under Octave)
 
 @item 2
-Value no longer used
+Uses the continuous simulated annealing global optimization algorithm 
+described in @cite{Corana et al. (1987)} and @cite{Goffe et al. (1994)}.
 
 @item 3
 Uses @code{fminunc} optimization routine (available under MATLAB if
@@ -4816,7 +4889,9 @@ Uses Chris Sims's @code{csminwel}
 
 @item 5
 Uses Marco Ratto's @code{newrat}. This value is not compatible with non
-linear filters or DSGE-VAR models
+linear filters or DSGE-VAR models.
+This is a slice optimizer: most iterations are a sequence of univariate optimization step, one for each estimated parameter or shock.
+Uses @code{csminwel} for line search in each step.
 
 @item 6
 Uses a Monte-Carlo based optimization routine (see
@@ -4835,12 +4910,21 @@ routine (generally more efficient than the MATLAB or Octave implementation
 available with @code{mode_compute=7})
 
 @item 9
-Uses the CMA-ES (Covariance Matrix Adaptation Evolution Strategy) algorithm, an evolutionary algorithm for difficult non-linear non-convex optimization
+Uses the CMA-ES (Covariance Matrix Adaptation Evolution Strategy) algorithm of 
+@cite{Hansen and Kern (2004)}, an evolutionary algorithm for difficult non-linear non-convex optimization
 
 @item 10
 Uses the simpsa algorithm, based on the combination of the non-linear simplex and simulated annealing algorithms and proposed by
 @cite{Cardoso, Salcedo and Feyo de Azevedo (1996)}.
 
+@item 101
+Uses the SolveOpt algorithm for local nonlinear optimization problems proposed by
+@cite{Kuntsevich and Kappel (1997)}.
+
+@item 102
+Uses @code{simulannealbnd} optimization routine (available under MATLAB if
+the Global Optimization Toolbox is installed; not available under Octave)
+
 @item @var{FUNCTION_NAME}
 It is also possible to give a @var{FUNCTION_NAME} to this option,
 instead of an @var{INTEGER}. In that case, Dynare takes the return
@@ -4905,18 +4989,60 @@ Metropolis-Hastings simulations instead of starting from
 scratch. Shouldn't be used together with @code{mh_recover}
 
 @item optim = (@var{NAME}, @var{VALUE}, ...)
+@anchor{optim}
 A list of @var{NAME} and @var{VALUE} pairs. Can be used to set options for the optimization routines. The set of available options depends on the selected optimization routine (ie on the value of option @ref{mode_compute}):
 
 @table @code
 
 @item 1, 3, 7
-Available options are given in the documentation of the MATLAB optimization toolbox or in Octave's documentation.
+Available options are given in the documentation of the MATLAB Optimization Toolbox or in Octave's documentation.
+
+@item 2
+Available options are:
+
+@table @code
+
+@item 'initial_step_length'
+Initial step length. Default: @code{1}
+
+@item 'initial_temperature'
+Initial temperature. Default: @code{15}
+
+@item 'MaxIter'
+Maximum number of function evaluations. Default: @code{100000}
+
+@item 'neps'
+Number of final function values used to decide upon termination. Default: @code{10}
+
+@item 'ns'
+Number of cycles. Default: @code{10}
+
+@item 'nt'
+Number of iterations before temperature reduction. Default: @code{10}
+
+@item 'step_length_c'
+Step length adjustment. Default: @code{0.1}
+
+@item 'TolFun'
+Stopping criteria. Default: @code{1e-8}
+
+@item 'rt'
+Temperature reduction factor. Default: @code{0.1}
+
+@item 'verbosity'
+Controls verbosity of display during optimization, ranging from 0 (silent) to 3 
+(each function evaluation). Default: @code{1}
+
+@end table
 
 @item 4
 Available options are:
 
 @table @code
 
+@item 'InitialInverseHessian'
+Initial approximation for the inverse of the Hessian matrix of the posterior kernel (or likelihood). Obviously this approximation has to be a square, positive definite and symmetric matrix. Default: @code{'1e-4*eye(nx)'}, where @code{nx} is the number of parameters to be estimated.
+
 @item 'MaxIter'
 Maximum number of iterations. Default: @code{1000}
 
@@ -4929,8 +5055,24 @@ Size of the perturbation used to compute numerically the gradient of the objecti
 @item 'TolFun'
 Stopping criteria. Default: @code{1e-7}
 
-@item 'InitialInverseHessian'
-Initial approximation for the inverse of the Hessian matrix of the posterior kernel (or likelihood). Obviously this approximation has to be a square, positive definite and symmetric matrix. Default: @code{'1e-4*eye(nx)'}, where @code{nx} is the number of parameters to be estimated.
+@end table
+
+@item 5
+Available options are:
+
+@table @code
+
+@item 'Hessian'
+Triggers three types of Hessian computations. @code{0}: outer product gradient; @code{1} default DYNARE Hessian routine; @code{2} 'mixed' outer product gradient, where diagonal elements are obtained using second order derivation formula and outer product is used for correlation structure. 
+Both @{0@} and @{2@} options require univariate filters, to ensure using maximum number of individual densities and a positive definite Hessian.
+Both @{0@} and @{2@} are quicker than default DYNARE numeric Hessian, but provide decent starting values for Metropolis for large models (option @{2@} being more accurate than @{0@}).
+Default: @code{1}.
+
+@item 'MaxIter'
+Maximum number of iterations. Default: @code{1000}
+
+@item 'TolFun'
+Stopping criteria. Default: @code{1e-5} for numerical derivatives @code{1e-7} for analytic derivatives.
 
 @end table
 
@@ -4939,8 +5081,14 @@ Available options are:
 
 @table @code
 
-@item 'NumberOfMh'
-Number of MCMC run sequentially. Default: @code{3}
+@item 'AcceptanceRateTarget'
+A real number between zero and one. The scale parameter of the jumping distribution is adjusted so that the effective acceptance rate matches the value of option @code{'AcceptanceRateTarget'}. Default: @code{1.0/3.0}
+
+@item 'InitialCovarianceMatrix'
+Initial covariance matrix of the jumping distribution. Default is @code{'previous'} if option @code{mode_file} is used, @code{'prior'} otherwise.
+
+@item 'nclimb'
+Number of iterations in the last MCMC (climbing mode).
 
 @item 'ncov-mh'
 Number of iterations used for updating the covariance matrix of the jumping distribution. Default: @code{20000}
@@ -4948,14 +5096,8 @@ Number of iterations used for updating the covariance matrix of the jumping dist
 @item 'nscale-mh'
 Maximum number of iterations used for adjusting the scale parameter of the jumping distribution.  @code{200000}
 
-@item 'nclimb'
-Number of iterations in the last MCMC (climbing mode).
-
-@item 'InitialCovarianceMatrix'
-Initial covariance matrix of the jumping distribution. Default is @code{'previous'} if option @code{mode_file} is used, @code{'prior'} otherwise.
-
-@item 'AcceptanceRateTarget'
-A real number between zero and one. The scale parameter of the jumping distribution is adjusted so that the effective acceptance rate matches the value of option @code{'AcceptanceRateTarget'}. Default: @code{1.0/3.0}
+@item 'NumberOfMh'
+Number of MCMC run sequentially. Default: @code{3}
 
 @end table
 
@@ -4964,6 +5106,9 @@ Available options are:
 
 @table @code
 
+@item 'InitialSimplexSize'
+Initial size of the simplex, expressed as percentage deviation from the provided initial guess in each direction. Default: @code{.05}
+
 @item 'MaxIter'
 Maximum number of iterations. Default: @code{5000}
 
@@ -4979,10 +5124,6 @@ Tolerance parameter (w.r.t the objective function). Default: @code{1e-4}
 @item 'TolX'
 Tolerance parameter (w.r.t the instruments). Default: @code{1e-4}
 
-@item 'InitialSimplexSize'
-
-Initial size of the simplex, expressed as percentage deviation from the provided initial guess in each direction. Default: @code{.05}
-
 @end table
 
 @item 9
@@ -5009,6 +5150,9 @@ Available options are:
 
 @table @code
 
+@item 'EndTemperature'
+Terminal condition w.r.t the temperature. When the temperature reaches @code{EndTemperature}, the temperature is set to zero and the algorithm falls back into a standard simplex algorithm. Default: @code{.1}
+
 @item 'MaxIter'
 Maximum number of iterations. Default: @code{5000}
 
@@ -5021,11 +5165,33 @@ Tolerance parameter (w.r.t the objective function). Default: @code{1e-4}
 @item 'TolX'
 Tolerance parameter (w.r.t the instruments). Default: @code{1e-4}
 
-@item 'EndTemperature'
-Terminal condition w.r.t the temperature. When the temperature reaches @code{EndTemperature}, the temperature is set to zero and the algorithm falls back into a standard simplex algorithm. Default: @code{.1}
+@end table
+
+@item 101
+Available options are:
+
+@table @code
+
+@item 'LBGradientStep'
+Lower bound for the stepsize used for the difference approximation of gradients. Default: @code{1e-11}
+
+@item 'MaxIter'
+Maximum number of iterations. Default: @code{15000}
+
+@item 'SpaceDilation'
+Coefficient of space dilation. Default: @code{2.5}
+
+@item 'TolFun'
+Tolerance parameter (w.r.t the objective function). Default: @code{1e-6}
+
+@item 'TolX'
+Tolerance parameter (w.r.t the instruments). Default: @code{1e-6}
 
 @end table
 
+@item 102
+Available options are given in the documentation of the MATLAB Global Optimization Toolbox.
+
 @end table
 
 @customhead{Example 1}
@@ -5151,6 +5317,8 @@ singularity is encountered, Dynare by default automatically switches to the univ
 @item kalman_tol = @var{DOUBLE}
 @anchor{kalman_tol} Numerical tolerance for determining the singularity of the covariance matrix of the prediction errors during the Kalman filter (minimum allowed reciprocal of the matrix condition number). Default value is @code{1e-10}
 
+@item diffuse_kalman_tol = @var{DOUBLE}
+@anchor{diffuse_kalman_tol} Numerical tolerance for determining the singularity of the covariance matrix of the prediction errors (@math{F_{\infty}}) and the rank of the covariance matrix of the non-stationary state variables (@math{P_{\infty}}) during the Diffuse Kalman filter. Default value is @code{1e-6}
 
 @item filter_covariance
 @anchor{filter_covariance} Saves the series of one step ahead error of
@@ -5279,7 +5447,15 @@ missing observations.
 
 @item endogenous_prior
 Use endogenous priors as in @cite{Christiano, Trabandt and Walentin
-(2011)}.
+(2011)}. 
+The procedure is motivated by sequential Bayesian learning.  Starting from independent initial priors on the parameters, 
+specified in the @code{estimated_params}-block, the standard deviations observed in a "pre-sample", 
+taken to be the actual sample, are used to update the initial priors. Thus, the product of the initial 
+priors and the pre-sample likelihood of the standard deviations of the observables is used as the new prior 
+(for more information, see the technical appendix of @cite{Christiano, Trabandt and Walentin (2011)}). 
+This procedure helps in cases where the regular posterior estimates, which minimize in-sample forecast 
+errors, result in a large overprediction 
+of model variable variances (a statistic that is not explicitly targeted, but often of particular interest to researchers).
 
 @item use_univariate_filters_if_singularity_is_detected = @var{INTEGER}
 @anchor{use_univariate_filters_if_singularity_is_detected}
@@ -5507,7 +5683,7 @@ and end of the sample for which no forecasts can be made, e.g. entries (1,5,1) a
 the variables will be ordered in the order of declaration after the estimation 
 command (or in general declaration order if no variables are specified here). In case 
 of running the classical smoother, the variables will always be ordered in general 
-declaration order. If the @xref{selected_variables_only} option is specified with the classical smoother, 
+declaration order. If the @ref{selected_variables_only} option is specified with the classical smoother, 
 non-requested variables will be simply left out in this order.
 @end defvr
 
@@ -6379,7 +6555,7 @@ new, expanded model.
 Alternatively, you can either solve for optimal policy under commitment
 with @code{ramsey_policy}, for optimal policy under discretion with
 @code{discretionary_policy} or for optimal simple rule with
-@code{osr}.
+@code{osr} (also implying commitment).
 
 
 @anchor{osr}
@@ -6451,9 +6627,8 @@ is specified in the @code{optim_weights}-block. By attaching weights to
 endogenous variables, the subset of endogenous variables entering the
 objective function, @math{y}, is implicitly specified.
 
-The linear quadratic problem is solved using the numerical optimizer
-@code{csminwel} of Chris Sims.
 
+The linear quadratic problem is solved using the numerical optimizer specified with @ref{opt_algo}.
 
 @optionshead
 
@@ -6464,12 +6639,12 @@ by listing them after the command, as @code{stoch_simul}
 
 @table @code
 
-@item maxit = @var{INTEGER} Determines the maximum number of iterations
-used in the non-linear solver. Default: @code{1000}
+@item opt_algo = @var{INTEGER}
+@anchor{opt_algo}
+Specifies the optimizer for minimizing the objective function. The same solvers as for @code{mode_compute} (@pxref{mode_compute}) are available, except for 5,6, and 10. 
 
-@item tolf = @var{DOUBLE} Convergence criterion for termination based on
-the function value. Iteration will cease when it proves impossible to
-improve the function value by more than tolf. Default: @code{1e-7}
+@item optim = (@var{NAME}, @var{VALUE}, ...)
+A list of @var{NAME} and @var{VALUE} pairs. Can be used to set options for the optimization routines. The set of available options depends on the selected optimization routine (i.e. on the value of option @ref{opt_algo}). @xref{optim}.
 
 @end table
 
@@ -6570,7 +6745,7 @@ at the optimum, stored in fields of the form
 @descriptionhead
 
 This command computes the First Order Conditions for maximizing the policy maker objective function subject to the
-constraints provided by the equilibrium path of the economy.
+constraints provided by the equilibrium path of the private economy.
 
 The planner objective must be declared with the @code{planner_objective} command.
 
@@ -6600,6 +6775,7 @@ under optimal policy. Requires a @code{steady_state_model} block or a
 @end table
 
 @customhead{Steady state}
+@anchor{Ramsey 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
@@ -6624,12 +6800,32 @@ instrument.
 
 @deffn Command ramsey_policy [@var{VARIABLE_NAME}@dots{}];
 @deffnx Command ramsey_policy (@var{OPTIONS}@dots{}) [@var{VARIABLE_NAME}@dots{}];
+@anchor{ramsey_policy}
 
 @descriptionhead
 
 This command computes the first order approximation of the policy that
-maximizes the policy maker objective function submitted to the
-constraints provided by the equilibrium path of the economy.
+maximizes the policy maker's objective function subject to the
+constraints provided by the equilibrium path of the private economy and under 
+commitment to this optimal policy. Following @cite{Woodford (1999)}, the Ramsey 
+policy is computed using a timeless perspective. That is, the government forgoes 
+its first-period advantage and does not exploit the preset privates sector expectations 
+(which are the source of the well-known time inconsistency that requires the 
+assumption of commitment). Rather, it acts as if the initial multipliers had 
+been set to 0 in the distant past, giving them time to converge to their steady 
+state value. Consequently, the optimal decision rules are computed around this steady state 
+of the endogenous variables and the Lagrange multipliers.
+
+This first order approximation to the optimal policy conducted by Dynare is not to be 
+confused with a naive linear quadratic approach to optimal policy that can lead to 
+spurious welfare rankings (see @cite{Kim and Kim (2003)}). In the latter, the optimal policy 
+would be computed subject to the first order approximated FOCs of the 
+private economy. In contrast, Dynare first computes the FOCs of the Ramsey planner's problem
+subject to the nonlinear constraints that are the FOCs of the private economy 
+and only then approximates these FOCs of planner's problem to first order. Thereby, the second
+order terms that are required for a second-order correct welfare evaluation are 
+preserved.
+
 
 The planner objective must be declared with the @code{planner_objective} command.
 
@@ -6653,36 +6849,34 @@ under optimal policy. Requires a @code{steady_state_model} block or a
 
 @end table
 
-Note that only first order approximation is available (@i{i.e.}
-@code{order=1} must be specified).
+Note that only a first order approximation of the optimal Ramsey policy is 
+available, leading to a second-order accurate welfare ranking 
+(@i{i.e.} @code{order=1} must be specified).
 
 @outputhead
 
-This command generates all the output variables of @code{stoch_simul}.
+This command generates all the output variables of @code{stoch_simul}. For specifying
+the initial values for the endogenous state variables (except for the Lagrange
+multipliers), @pxref{histval}.
 
 @vindex oo_.planner_objective_value
+@anchor{planner_objective_value}
+
 In addition, it stores the value of planner objective function under
-Ramsey policy in @code{oo_.planner_objective_value}.
+Ramsey policy in @code{oo_.planner_objective_value}, given the initial values 
+of the endogenous state variables. If not specified with @code{histval}, they are 
+taken to be at their steady state values. The result is a 1 by 2 
+vector, where the first entry stores the value of the planner objective under 
+the timeless perspective to Ramsey policy, i.e. where the initial Lagrange
+multipliers associated with the planner's problem are set to their steady state
+values (@pxref{ramsey_policy}).
+In contrast, the second entry stores the value of the planner objective with 
+initial Lagrange multipliers of the planner's problem set to 0, i.e. it is assumed 
+that the planner succumbs to the temptation to exploit the preset private expecatations 
+in the first period (but not in later periods due to commitment).
 
 @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
-policy. Nevertheless, it is in general very difficult to compute the
-steady state with simply a numerical guess in @code{initval} for the
-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. A typical
-example is choosing inflation or nominal interest rate as an
-instrument.
+@xref{Ramsey steady state}.
 
 
 @end deffn
@@ -6767,386 +6961,92 @@ With respect to the previous version of the toolbox, in order to work
 properly, the GSA toolbox no longer requires that the Dynare
 estimation environment is set up.
 
-Sensitivity analysis results are saved locally in @code{<mod_file>/GSA},
-where @code{<mod_file>.mod} is the name of the DYNARE model file.
 
 @menu
-* Sampling::
-* Stability Mapping::
-* Reduced Form Mapping::
-* RMSE::
-* Screening Analysis::
-* Identification Analysis::
-* Performing Sensitivity and Identification Analysis::
+* Performing sensitivity analysis::
+* Performing identification analysis::
+* IRF/Moment calibration::
+* Types of analysis and output files::
 @end menu
 
-@node Sampling
-@subsection Sampling
 
-The following binary files are produced:
-@itemize
-@item
-@code{<mod_file>_prior.mat}: this file stores information about the analyses
-performed sampling from the prior ranges, @i{i.e.} @code{pprior=1} and @code{ppost=0};
+@node Performing sensitivity analysis
+@subsection Performing sensitivity analysis
 
-@item
-@code{<mod_file>_mc.mat}: this file stores information about the analyses performed
-sampling from multivariate normal, @i{i.e.} @code{pprior=0} and @code{ppost=0};
+@deffn Command dynare_sensitivity ;
+@deffnx Command dynare_sensitivity (@var{OPTIONS}@dots{});
 
-@item
-@code{<mod_file>_post.mat}: this file stores information about analyses performed
-using the Metropolis posterior sample, @i{i.e.} @code{ppost=1}.
-@end itemize
+@descriptionhead
 
-@node Stability Mapping
-@subsection Stability Mapping
+This command triggers sensitivity analysis on a DSGE model.
 
-Figure files produced are of the form @code{<mod_file>_prior_*.fig} and store results
-for stability mapping from prior Monte-Carlo samples:
-@itemize
-@item
-@code{<mod_file>_prior_stab_SA_*.fig}: plots of the Smirnov test analyses
-confronting the cdf of the sample fulfilling Blanchard-Kahn conditions
-with the cdf of the rest of the sample;
+@optionshead
+@customhead{Sampling Options}
+@anchor{Sampling Options}
+@table @code
 
-@item
-@code{<mod_file>_prior_stab_indet_SA_*.fig}: plots of the Smirnov test
-analyses confronting the cdf of the sample producing indeterminacy
-with the cdf of the original prior sample;
+@item nsam = @var{INTEGER}
+Size of the Monte-Carlo sample. Default: @code{2048}
 
-@item
-@code{<mod_file>_prior_stab_unst_SA_*.fig}: plots of the Smirnov test
-analyses confronting the cdf of the sample producing unstable (explosive
-roots) behavior with the cdf of the original prior sample;
+@item ilptau = @var{INTEGER}
+If equal to @code{1}, use @math{LP_\tau} quasi-Monte-Carlo.
+If equal to @code{0}, use LHS Monte-Carlo. Default: @code{1}
 
-@item
-@code{<mod_file>_prior_stable_corr_*.fig}: plots of bivariate projections
-of the sample fulfilling Blanchard-Kahn conditions;
+@item pprior = @var{INTEGER}
+If equal to @code{1}, sample from the prior distributions.
+If equal to @code{0}, sample from the multivariate normal @math{N(\bar{\theta},\Sigma)},
+where @math{\bar{\theta}} is the posterior mode and @math{\Sigma=H^{-1}}, @math{H}
+is the Hessian at the mode. Default: @code{1}
 
-@item
-@code{<mod_file>_prior_indeterm_corr_*.fig}: plots of bivariate projections
-of the sample producing indeterminacy;
+@item prior_range = @var{INTEGER}
+If equal to @code{1}, sample uniformly from prior ranges.
+If equal to @code{0}, sample from prior distributions. Default: @code{1}
 
-@item
-@code{<mod_file>_prior_unstable_corr_*.fig}: plots of bivariate projections
-of the sample producing instability;
+@item morris = @var{INTEGER}
+@anchor{morris}
+If equal to @code{0}, ANOVA mapping (Type I error)
+If equal to @code{1}, Screening analysis (Type II error)
+If equal to @code{2}, Analytic derivatives (similar to Type II error, only valid when
+@code{identification=1}).Default: @code{1} when @code{identification=1}, @code{0} otherwise
 
-@item
-@code{<mod_file>_prior_unacceptable_corr_*.fig}: plots of bivariate projections
-of the sample producing unacceptable solutions, @i{i.e.} either
-instability or indeterminacy or the solution could not be found (@i{e.g.}
-the steady state solution could not be found by the solver).
-@end itemize
+@item morris_nliv = @var{INTEGER}
+@anchor{morris_nliv}
+Number of levels in Morris design. Default: @code{6}
 
-Similar conventions apply for @code{<mod_file>_mc_*.fig} files, obtained when
-samples from multivariate normal are used.
+@item morris_ntra = @var{INTEGER}
+@anchor{morris_ntra}
+Number trajectories in Morris design. Default: @code{20}
 
-@node Reduced Form Mapping
-@subsection Reduced Form Mapping
+@item ppost = @var{INTEGER}
+If equal to @code{1}, use Metropolis posterior sample.
+If equal to @code{0}, do not use Metropolis posterior sample. NB: This
+overrides any other sampling option. Default: @code{0}
 
-The mapping of the reduced form solution forces the use of samples from
-prior ranges or prior distributions, @i{i.e.}: @code{pprior=1} and @code{ppost=0}. It
-uses 250 samples to optimize smoothing parameters and 1000 samples to compute the
-fit. The rest of the sample is used for out-of-sample validation. One can also
-load a previously estimated mapping with a new Monte-Carlo sample, to look at the
-forecast for the new Monte-Carlo sample.
+@item neighborhood_width = @var{DOUBLE}
+When @code{pprior=0} and @code{ppost=0}, allows for the sampling of
+parameters around the value specified in the @code{mode_file}, in the range
+@code{xparam1}@math{\pm\left|@code{xparam1}\times@code{neighborhood_width}\right|}. Default: @code{0}
 
-The following synthetic figures are produced:
-@itemize
-@item
-@code{<mod_file>_redform_<endo name>_vs_lags_*.fig}: shows bar charts
-of the sensitivity indices for the ten most important parameters driving
-the reduced form coefficients of the selected endogenous variables
-(@code{namendo}) versus lagged endogenous variables (@code{namlagendo}); suffix
-@code{log} indicates the results for log-transformed entries;
+@end table
+@customhead{Stability Mapping Options}
+@table @code
 
-@item
-@code{<mod_file>_redform_<endo name>_vs_shocks_*.fig}: shows bar charts
-of the sensitivity indices for the ten most important parameters driving
-the reduced form coefficients of the selected endogenous variables
-(@code{namendo}) versus exogenous variables (@code{namexo}); suffix @code{log}
-indicates the results for log-transformed entries;
+@item stab = @var{INTEGER}
+If equal to @code{1}, perform stability mapping.
+If equal to @code{0}, do not perform stability mapping. Default: @code{1}
 
-@item
-@code{<mod_file>_redform_GSA(_log).fig}: shows bar chart of all sensitivity
-indices for each parameter: this allows one to notice parameters that
-have a minor effect for any of the reduced form coefficients.
-@end itemize
+@item load_stab = @var{INTEGER}
+If equal to @code{1}, load a previously created sample.
+If equal to @code{0}, generate a new sample. Default: @code{0}
 
-Detailed results of the analyses are shown in the subfolder @code{<mod_file>/GSA/redform_stab},
-where the detailed results of the estimation of the single functional relationships
-between parameters @math{\theta} and reduced form coefficient are stored in separate directories
-named as:
+@item alpha2_stab = @var{DOUBLE}
+Critical value for correlations @math{\rho} in filtered samples:
+plot couples of parmaters with @math{\left|\rho\right|>} @code{alpha2_stab}.
+Default: @code{0.3}
 
-@itemize
-@item
-@code{<namendo>_vs_<namlagendo>}: for the entries of the transition matrix;
-
-@item
-@code{<namendo>_vs_<namexo>}: for entries of the matrix of the shocks.
-@end itemize
-Moreover, analyses for log-transformed entries are denoted with the following
-suffixes (@math{y} denotes the generic reduced form coefficient):
-@itemize
-@item
-@code{log}: @math{y^* = \log(y)};
-@item
-@code{minuslog}: @math{y^* = \log(-y)};
-@item
-@code{logsquared}: @math{y^* = \log(y^2)} for symmetric fat tails;
-@item
-@code{logskew}: @math{y^* = \log(|y + \lambda|)} for asymmetric fat tails.
-@end itemize
-The optimal type of transformation is automatically selected without the
-need of user intervention.
-
-@node RMSE
-@subsection RMSE
-
-The RMSE analysis can be performed with different types of sampling options:
-@enumerate
-@item
-When @code{pprior=1} and @code{ppost=0}, the toolbox analyzes the RMSEs for
-the Monte-Carlo sample obtained by sampling parameters from their prior distributions
-(or prior ranges): this analysis provides some hints about
-what parameter drives the fit of which observed series, prior to the full
-estimation;
-
-@item
-When @code{pprior=0} and @code{ppost=0}, the toolbox analyzes the RMSEs for
-a multivariate normal Monte-Carlo sample, with covariance matrix based on
-the inverse Hessian at the optimum: this analysis is useful when maximum likelihood
-estimation is done (@i{i.e.} no Bayesian estimation);
-
-@item
-When @code{ppost=1} the toolbox analyzes the RMSEs for the posterior sample
-obtained by Dynare's Metropolis procedure.
-@end enumerate
-
-The use of cases 2 and 3 requires an estimation step beforehand. To
-facilitate the sensitivity analysis after estimation, the @code{dynare_sensitivity}
-command also allows you to indicate some options of the @code{estimation}
-command. These are:
-@itemize @bullet
-@item @code{datafile}
-@item @code{nobs}
-@item @code{first_obs}
-@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}
-@end itemize
-
-Binary files produced my RMSE analysis are:
-@itemize
-@item
-@code{<mod_file>_prior_*.mat}: these files store the filtered and smoothed
-    variables for the prior Monte-Carlo sample, generated when doing RMSE analysis
-    (@code{pprior=1} and @code{ppost=0});
-@item
-@code{<mode_file>_mc_*.mat}: these files store the filtered and smoothed variables
-    for the multivariate normal Monte-Carlo sample, generated when doing
-    RMSE analysis (@code{pprior=0} and @code{ppost=0}).
-@end itemize
-
-Figure files @code{<mod_file>_rmse_*.fig} store results for the RMSE analysis.
-
-@itemize
-@item
-@code{<mod_file>_rmse_prior*.fig}: save results for the analysis using prior
-Monte-Carlo samples;
-
-@item
-@code{<mod_file>_rmse_mc*.fig}: save results for the analysis using multivariate
-normal Monte-Carlo samples;
-
-@item
-@code{<mod_file>_rmse_post*.fig}: save results for the analysis using Metropolis
-posterior samples.
-@end itemize
-
-The following types of figures are saved (we show prior sample to fix ideas,
-but the same conventions are used for multivariate normal and posterior):
-
-@itemize
-@item
-@code{<mod_file>_rmse_prior_*.fig}: for each parameter, plots the cdfs
-corresponding to the best 10% RMSEs of each observed series;
-
-@item
-@code{<mod_file>_rmse_prior_dens_*.fig}: for each parameter, plots the
-pdfs corresponding to the best 10% RMESs of each observed series;
-
-@item
-@code{<mod_file>_rmse_prior_<name of observedseries>_corr_*.fig}: for
-each observed series plots the bi-dimensional projections of samples
-with the best 10% RMSEs, when the correlation is significant;
-
-@item
-@code{<mod_file>_rmse_prior_lnlik*.fig}: for each observed series, plots
-in red the cdf of the log-likelihood corresponding to the best 10%
-RMSEs, in green the cdf of the rest of the sample and in blue the
-cdf of the full sample; this allows one to see the presence of some
-idiosyncratic behavior;
-
-@item
-@code{<mod_file>_rmse_prior_lnpost*.fig}: for each observed series, plots
-in red the cdf of the log-posterior corresponding to the best 10% RMSEs,
-in green the cdf of the rest of the sample and in blue the cdf of the full
-sample; this allows one to see idiosyncratic behavior;
-
-@item
-@code{<mod_file>_rmse_prior_lnprior*.fig}: for each observed series, plots
-in red the cdf of the log-prior corresponding to the best 10% RMSEs,
-in green the cdf of the rest of the sample and in blue the cdf of the full
-sample; this allows one to see idiosyncratic behavior;
-
-@item
-@code{<mod_file>_rmse_prior_lik_SA_*.fig}: when @code{lik_only=1}, this shows
-the Smirnov tests for the filtering of the best 10% log-likelihood values;
-
-@item
-@code{<mod_file>_rmse_prior_post_SA_*.fig}: when @code{lik_only=1}, this shows
-the Smirnov test for the filtering of the best 10% log-posterior values.
-@end itemize
-
-@node Screening Analysis
-@subsection Screening Analysis
-
-Screening analysis does not require any additional options with respect to
-those listed in @ref{Sampling Options}. The toolbox performs all the
-analyses required and displays results.
-
-The results of the screening analysis with Morris sampling design are stored
-in the subfolder @code{<mod_file>/GSA/SCREEN}. The data file @code{<mod_file>_prior} stores
-all the information of the analysis (Morris sample, reduced form coefficients,
-etc.).
-
-Screening analysis merely concerns reduced form coefficients. Similar
-synthetic bar charts as for the reduced form analysis with Monte-Carlo samples are
-saved:
-@itemize
-@item
-@code{<mod_file>_redform_<endo name>_vs_lags_*.fig}: shows bar charts
-of the elementary effect tests for the ten most important parameters
-driving the reduced form coefficients of the selected endogenous variables
-(@code{namendo}) versus lagged endogenous variables (@code{namlagendo});
-
-@item
-@code{<mod_file>_redform_<endo name>_vs_shocks_*.fig}: shows bar charts
-of the elementary effect tests for the ten most important parameters
-driving the reduced form coefficients of the selected endogenous variables
-(@code{namendo}) versus exogenous variables (@code{namexo});
-
-@item
-@code{<mod_file>_redform_screen.fig}: shows bar chart of all elementary
-effect tests for each parameter: this allows one to identify parameters that
-have a minor effect for any of the reduced form coefficients.
-@end itemize
-
-@node Identification Analysis
-@subsection Identification Analysis
-
-Setting the option @code{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
-@code{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 option @code{morris=2},
-which implements @cite{Iskrev (2010)} identification analysis.
-
-For example, the placing @code{identification; dynare_sensitivity(identification=1, morris=2);}
-in the Dynare model file trigger identification analysis using analytic derivatives
-@cite{Iskrev (2010)}, jointly with the mapping of the acceptable region.
-
-The identification analysis with derivatives can also be triggered by the
-commands @code{identification;} 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.
-
-@node Performing Sensitivity and Identification Analysis
-@subsection Performing Sensitivity and Identification Analysis
-
-@deffn Command dynare_sensitivity ;
-@deffnx Command dynare_sensitivity (@var{OPTIONS}@dots{});
-
-@descriptionhead
-
-This command triggers sensitivity analysis on a DSGE model.
-
-@optionshead
-@customhead{Sampling Options}
-@anchor{Sampling Options}
-@table @code
-
-@item nsam = @var{INTEGER}
-Size of the Monte-Carlo sample. Default: @code{2048}
-
-@item ilptau = @var{INTEGER}
-If equal to @code{1}, use @math{LP_\tau} quasi-Monte-Carlo.
-If equal to @code{0}, use LHS Monte-Carlo. Default: @code{1}
-
-@item pprior = @var{INTEGER}
-If equal to @code{1}, sample from the prior distributions.
-If equal to @code{0}, sample from the multivariate normal @math{N(\bar{\theta},\Sigma)},
-where @math{\bar{\theta}} is the posterior mode and @math{\Sigma=H^{-1}}, @math{H}
-is the Hessian at the mode. Default: @code{1}
-
-@item prior_range = @var{INTEGER}
-If equal to @code{1}, sample uniformly from prior ranges.
-If equal to @code{0}, sample from prior distributions. Default: @code{1}
-
-@item morris = @var{INTEGER}
-@anchor{morris}
-If equal to @code{0}, ANOVA mapping (Type I error)
-If equal to @code{1}, Screening analysis (Type II error)
-If equal to @code{2}, Analytic derivatives (similar to Type II error, only valid when
-@code{identification=1}).Default: @code{1} when @code{identification=1}, @code{0} otherwise
-
-@item morris_nliv = @var{INTEGER}
-@anchor{morris_nliv}
-Number of levels in Morris design. Default: @code{6}
-
-@item morris_ntra = @var{INTEGER}
-@anchor{morris_ntra}
-Number trajectories in Morris design. Default: @code{20}
-
-@item ppost = @var{INTEGER}
-If equal to @code{1}, use Metropolis posterior sample.
-If equal to @code{0}, do not use Metropolis posterior sample. NB: This
-overrides any other sampling option. Default: @code{0}
-
-@item neighborhood_width = @var{DOUBLE}
-When @code{pprior=0} and @code{ppost=0}, allows for the sampling of
-parameters around the value specified in the @code{mode_file}, in the range
-@code{xparam1}@math{\pm\left|@code{xparam1}\times@code{neighborhood_width}\right|}. Default: @code{0}
-
-@end table
-@customhead{Stability Mapping Options}
-@table @code
-
-@item stab = @var{INTEGER}
-If equal to @code{1}, perform stability mapping.
-If equal to @code{0}, do not perform stability mapping. Default: @code{1}
-
-@item load_stab = @var{INTEGER}
-If equal to @code{1}, load a previously created sample.
-If equal to @code{0}, generate a new sample. Default: @code{0}
-
-@item alpha2_stab = @var{DOUBLE}
-Critical value for correlations @math{\rho} in filtered samples:
-plot couples of parmaters with @math{\left|\rho\right|>} @code{alpha2_stab}.
-Default: @code{0.3}
-
-@item ksstat = @var{DOUBLE}
-Critical value for Smirnov statistics @math{d}: plot parameters with
-@math{d>} @code{ksstat}. Default: @code{0.1}
+@item ksstat = @var{DOUBLE}
+Critical value for Smirnov statistics @math{d}: plot parameters with
+@math{d>} @code{ksstat}. Default: @code{0.1}
 
 @item pvalue_ks = @var{DOUBLE}
 The threshold @math{pvalue} for significant Kolmogorov-Smirnov test (@i{i.e.} plot parameters with
@@ -7242,147 +7142,619 @@ Critical value for correlation @math{\rho}: plot couples of parmaters with
 @item first_obs = @var{INTEGER}
 @xref{first_obs}.
 
-@item prefilter = @var{INTEGER}
-@xref{prefilter}.
+@item prefilter = @var{INTEGER}
+@xref{prefilter}.
+
+@item presample = @var{INTEGER}
+@xref{presample}.
+
+@item nograph
+@xref{nograph}.
+
+@item nodisplay
+@xref{nodisplay}.
+
+@item graph_format = @var{FORMAT}
+@itemx graph_format = ( @var{FORMAT}, @var{FORMAT}@dots{} )
+@xref{graph_format}.
+
+@item conf_sig = @var{DOUBLE}
+@xref{conf_sig}.
+
+@item loglinear
+@xref{loglinear}.
+
+@item mode_file = @var{FILENAME}
+@xref{mode_file}.
+
+@item kalman_algo = @var{INTEGER}
+@xref{kalman_algo}.
+
+@end table
+@customhead{Identification Analysis Options}
+@table @code
+
+@item identification = @var{INTEGER}
+If equal to @code{1}, performs identification anlysis (forcing @code{redform=0} and @code{morris=1})
+If equal to @code{0}, no identification analysis. Default: @code{0}
+
+@item morris = @var{INTEGER}
+@xref{morris}.
+
+@item morris_nliv = @var{INTEGER}
+@xref{morris_nliv}.
+
+@item morris_ntra = @var{INTEGER}
+@xref{morris_ntra}.
+
+@item load_ident_files = @var{INTEGER}
+Loads previously performed identification analysis. Default: @code{0}
+
+@item useautocorr = @var{INTEGER}
+Use autocorrelation matrices in place of autocovariance matrices in moments
+for identification analysis. Default: @code{0}
+
+@item ar = @var{INTEGER}
+Maximum number of lags for moments in identification analysis. Default: @code{1}
+
+@item lik_init = @var{INTEGER}
+@xref{lik_init}.
+
+@end table
+
+@end deffn
+
+@node IRF/Moment calibration
+@subsection IRF/Moment calibration
+
+IRF and moment calibration can be defined in @code{irf_calibration} and @code{moment_calibration} blocks:
+
+@deffn Block irf_calibration;
+@deffnx Block irf_calibration(@var{OPTIONS}@dots{});
+
+@descriptionhead
+
+This block allows defining IRF calibration criteria and is terminated by @code{end;}. 
+To set IRF sign restrictions, the following syntax is used
+@example
+@var{VARIABLE_NAME}(@var{INTEGER}),@var{EXOGENOUS_NAME}, -;
+@var{VARIABLE_NAME}(@var{INTEGER}:@var{INTEGER}),@var{EXOGENOUS_NAME}, +;
+@end example
+To set IRF restrictions with specific intervals, the following syntax is used
+@example
+@var{VARIABLE_NAME}(@var{INTEGER}),@var{EXOGENOUS_NAME}, [@var{DOUBLE} @var{DOUBLE}];
+@var{VARIABLE_NAME}(@var{INTEGER}:@var{INTEGER}),@var{EXOGENOUS_NAME}, [@var{DOUBLE} @var{DOUBLE}];
+@end example
+
+When @code{(@var{INTEGER}:@var{INTEGER})} is used, the restriction is considered to be fulfilled by a logical OR.
+A list of restrictions must always be fulfilled with logical AND.
+
+@examplehead
+
+@example
+irf_calibration;
+y(1:4), e_ys, [ -50 50]; //[first year response with logical OR]
+@@#for ilag in 21:40
+R_obs(@@@{ilag@}), e_ys, [0 6]; //[response from 5th to 10th years with logical AND]
+@@#endfor
+end;
+@end example
+
+@end deffn
+
+@deffn Block moment_calibration;
+@deffnx Block moment_calibration(@var{OPTIONS}@dots{});
+
+@descriptionhead
+
+This block allows defining moment calibration criteria. This block is terminated by @code{end;}, and contains lines of the
+form:
+@example
+@var{VARIABLE_NAME1},@var{VARIABLE_NAME2}(+/-@var{INTEGER}), [@var{DOUBLE} @var{DOUBLE}];
+@var{VARIABLE_NAME1},@var{VARIABLE_NAME2}(+/-@var{INTEGER}), +/-;
+@var{VARIABLE_NAME1},@var{VARIABLE_NAME2}(+/-(@var{INTEGER}:@var{INTEGER})), [@var{DOUBLE} @var{DOUBLE}];
+@var{VARIABLE_NAME1},@var{VARIABLE_NAME2}((-@var{INTEGER}:+@var{INTEGER})), [@var{DOUBLE} @var{DOUBLE}];
+@end example
+
+When @code{(@var{INTEGER}:@var{INTEGER})} is used, the restriction is considered to be fulfilled by a logical OR.
+A list of restrictions must always be fulfilled with logical AND.
+
+@examplehead
+
+@example
+moment_calibration;
+y_obs,y_obs, [0.5 1.5]; //[unconditional variance]
+y_obs,y_obs(-(1:4)), +; //[sign restriction for first year acf with logical OR]
+@@#for ilag in -2:2
+y_obs,R_obs(@@@{ilag@}), -; //[-2:2 ccf with logical AND]
+@@#endfor
+@@#for ilag in -4:4
+y_obs,pie_obs(@@@{ilag@}), -; //[-4_4 ccf with logical AND]
+@@#endfor
+end;
+@end example
+
+@end deffn
+@node Performing identification analysis
+@subsection Performing identification analysis
+
+@deffn Command identification ;
+@deffnx Command identification (@var{OPTIONS}@dots{});
+
+@descriptionhead
+
+This command triggers identification analysis.
+
+@optionshead
+
+@table @code
+
+@item ar = @var{INTEGER}
+Number of lags of computed autocorrelations (theoretical moments). Default: @code{1}
+
+@item useautocorr = @var{INTEGER}
+If equal to @code{1}, compute derivatives of autocorrelation. If equal
+to @code{0}, compute derivatives of autocovariances. Default: @code{0}
+
+@item load_ident_files = @var{INTEGER}
+If equal to @code{1}, allow Dynare to load previously
+computed analyzes. Default: @code{0}
+
+@item prior_mc = @var{INTEGER}
+Size of Monte-Carlo sample. Default: @code{1}
+
+@item prior_range = @var{INTEGER}
+Triggers uniform sample within the range implied by the prior specifications (when
+@code{prior_mc>1}). Default: @code{0}
+
+@item advanced = @var{INTEGER}
+Shows a more detailed analysis, comprised of an analysis for the linearized rational
+expectation model as well as the associated reduced form solution. Further performs a brute
+force search of the groups of parameters best reproducing the behavior of each single parameter.
+The maximum dimension of the group searched is triggered by @code{max_dim_cova_group}. Default: @code{0}
+
+@item max_dim_cova_group = @var{INTEGER}
+In the brute force search (performed when @code{advanced=1}) this option sets the maximum dimension of groups
+of parameters that best reproduce the behavior of each single model parameter. Default: @code{2}
+
+@item periods = @var{INTEGER}
+When the analytic Hessian is not available (@i{i.e.} with missing values or diffuse
+Kalman filter or univariate Kalman filter), this triggers the length of stochastic simulation
+to compute Simulated Moments Uncertainty. Default: @code{300}
+
+@item replic = @var{INTEGER}
+When the analytic Hessian is not available, this triggers the number of replicas
+to compute Simulated Moments Uncertainty. Default: @code{100}
+
+@item gsa_sample_file = @var{INTEGER}
+If equal to @code{0}, do not use sample file.
+If equal to @code{1}, triggers gsa prior sample.
+If equal to @code{2}, triggers gsa Monte-Carlo sample (@i{i.e.} loads a sample corresponding to
+@code{pprior=0} and @code{ppost=0} in the @code{dynare_sensitivity} options). Default: @code{0}
+
+@item gsa_sample_file = @var{FILENAME}
+Uses the provided path to a specific user defined sample file. Default: @code{0}
+
+@item parameter_set = @code{calibration} | @code{prior_mode} | @code{prior_mean} | @code{posterior_mode} | @code{posterior_mean} | @code{posterior_median}
+Specify the parameter set to use. Default: @code{prior_mean}
+
+@item lik_init = @var{INTEGER}
+@xref{lik_init}.
+
+@item kalman_algo = @var{INTEGER}
+@xref{kalman_algo}.
+
+@item nograph
+@xref{nograph}.
+
+@item nodisplay
+@xref{nodisplay}.
+
+@item graph_format = @var{FORMAT}
+@itemx graph_format = ( @var{FORMAT}, @var{FORMAT}@dots{} )
+@xref{graph_format}.
+
+@end table
+
+@end deffn
+
+@node Types of analysis and output files
+@subsection Types of analysis and output files
+
+The sensitivity analysis toolbox includes several types of analyses.
+Sensitivity analysis results are saved locally in @code{<mod_file>/gsa},
+where @code{<mod_file>.mod} is the name of the DYNARE model file.
+
+@menu
+* Sampling::
+* Stability Mapping::
+* IRF/Moment restrictions::
+* Reduced Form Mapping::
+* RMSE::
+* Screening Analysis::
+* Identification Analysis::
+@end menu
+
+@node Sampling
+@subsubsection Sampling
+
+The following binary files are produced:
+@itemize
+@item
+@code{<mod_file>_prior.mat}: this file stores information about the analyses
+performed sampling from the prior, @i{i.e.} @code{pprior=1} and @code{ppost=0};
+
+@item
+@code{<mod_file>_mc.mat}: this file stores information about the analyses performed
+sampling from multivariate normal, @i{i.e.} @code{pprior=0} and @code{ppost=0};
+
+@item
+@code{<mod_file>_post.mat}: this file stores information about analyses performed
+using the Metropolis posterior sample, @i{i.e.} @code{ppost=1}.
+@end itemize
+
+@node Stability Mapping
+@subsubsection Stability Mapping
+
+Figure files produced are of the form @code{<mod_file>_prior_*.fig} and store results
+for stability mapping from prior Monte-Carlo samples:
+@itemize
+@item
+@code{<mod_file>_prior_stable.fig}: plots of the Smirnov test and the correlation analyses
+confronting the cdf of the sample fulfilling Blanchard-Kahn conditions (blue color)
+with the cdf of the rest of the sample (red color), @i{i.e.} either
+instability or indeterminacy or the solution could not be found (@i{e.g.}
+the steady state solution could not be found by the solver);
+
+@item
+@code{<mod_file>_prior_indeterm.fig}: plots of the Smirnov test and the correlation
+analyses confronting the cdf of the sample producing indeterminacy (red color)
+with the cdf of the rest of the sample (blue color);
+
+@item
+@code{<mod_file>_prior_unstable.fig}: plots of the Smirnov test and the correlation
+analyses confronting the cdf of the sample producing explosive roots (red color) 
+with the cdf of the rest of the sample (blue color);
+
+@item
+@code{<mod_file>_prior_wrong.fig}: plots of the Smirnov test and the correlation
+analyses confronting the cdf of the sample where the solution could not be found (@i{e.g.}
+the steady state solution could not be found by the solver - red color) 
+with the cdf of the rest of the sample (blue color);
+
+@item
+@code{<mod_file>_prior_calib.fig}: plots of the Smirnov test and the correlation
+analyses splitting the sample fulfilling Blanchard-Kahn conditions, 
+by confronting the cdf of the sample where IRF/moment restrictions are matched (blue color)
+with the cdf where IRF/moment restrictions are NOT matched (red color);
+
+@end itemize
+
+Similar conventions apply for @code{<mod_file>_mc_*.fig} files, obtained when
+samples from multivariate normal are used.
+
+@node IRF/Moment restrictions
+@subsubsection IRF/Moment restrictions
+
+The following binary files are produced:
+@itemize
+@item
+@code{<mod_file>_prior_restrictions.mat}: this file stores information about the IRF/moment restriction analysis
+performed sampling from the prior ranges, @i{i.e.} @code{pprior=1} and @code{ppost=0};
+
+@item
+@code{<mod_file>_mc_restrictions.mat}: this file stores information about the IRF/moment restriction analysis performed
+sampling from multivariate normal, @i{i.e.} @code{pprior=0} and @code{ppost=0};
+
+@item
+@code{<mod_file>_post_restrictions.mat}: this file stores information about IRF/moment restriction analysis performed
+using the Metropolis posterior sample, @i{i.e.} @code{ppost=1}.
+@end itemize
+
+Figure files produced are of the form @code{<mod_file>_prior_irf_calib_*.fig} and @code{<mod_file>_prior_moment_calib_*.fig} and store results
+for mapping restrictions from prior Monte-Carlo samples:
+@itemize
+@item
+@code{<mod_file>_prior_irf_calib_<ENDO_NAME>_vs_<EXO_NAME>_<PERIOD>.fig}: plots of the Smirnov test and the correlation
+analyses splitting the sample fulfilling Blanchard-Kahn conditions,
+by confronting the cdf of the sample where the individual IRF restriction 
+@code{<ENDO_NAME>} vs. @code{<EXO_NAME>} at period(s) @code{<PERIOD>} is matched (blue color)
+with the cdf where the IRF restriction is NOT matched (red color)
+
+@item
+@code{<mod_file>_prior_irf_calib_<ENDO_NAME>_vs_<EXO_NAME>_ALL.fig}: plots of the Smirnov test and the correlation
+analyses splitting the sample fulfilling Blanchard-Kahn conditions,
+by confronting the cdf of the sample where ALL the individual IRF restrictions for the same couple
+@code{<ENDO_NAME>} vs. @code{<EXO_NAME>} are matched (blue color)
+with the cdf where the IRF restriction is NOT matched (red color)
+
+@item
+@code{<mod_file>_prior_irf_restrictions.fig}: plots visual information on the IRF restrictions 
+compared to the actual Monte Carlo realization from prior sample.
+
+@item
+@code{<mod_file>_prior_moment_calib_<ENDO_NAME1>_vs_<ENDO_NAME2>_<LAG>.fig}: plots of the Smirnov test and the correlation
+analyses splitting the sample fulfilling Blanchard-Kahn conditions,
+by confronting the cdf of the sample where the individual acf/ccf moment restriction 
+@code{<ENDO_NAME1>} vs. @code{<ENDO_NAME2>} at lag(s) @code{<LAG>} is matched (blue color)
+with the cdf where the IRF restriction is NOT matched (red color)
+
+@item
+@code{<mod_file>_prior_moment_calib_<ENDO_NAME>_vs_<EXO_NAME>_ALL.fig}: plots of the Smirnov test and the correlation
+analyses splitting the sample fulfilling Blanchard-Kahn conditions,
+by confronting the cdf of the sample where ALL the individual acf/ccf moment restrictions for the same couple
+@code{<ENDO_NAME1>} vs. @code{<ENDO_NAME2>} are matched (blue color)
+with the cdf where the IRF restriction is NOT matched (red color)
+
+@item
+@code{<mod_file>_prior_moment_restrictions.fig}: plots visual information on the moment restrictions 
+compared to the actual Monte Carlo realization from prior sample.
+
+@end itemize
+
+Similar conventions apply for @code{<mod_file>_mc_*.fig} and @code{<mod_file>_post_*.fig} files, obtained when
+samples from multivariate normal or from posterior are used.
+
+@node Reduced Form Mapping
+@subsubsection Reduced Form Mapping
+
+When the option @code{threshold_redform} is not set, or it is empty (the default), this analysis estimates a multivariate
+smoothing spline ANOVA model (the 'mapping') for the selected entries in the transition matrix of the shock matrix of the reduce form first order solution of the model.
+This mapping is done either with prior samples or with MC samples with @code{neighborhood_width}.
+Unless @code{neighborhood_width} is set with MC samples, the  mapping of the reduced form solution forces the use of samples from
+prior ranges or prior distributions, @i{i.e.}: @code{pprior=1} and @code{ppost=0}. It
+uses 250 samples to optimize smoothing parameters and 1000 samples to compute the
+fit. The rest of the sample is used for out-of-sample validation. One can also
+load a previously estimated mapping with a new Monte-Carlo sample, to look at the
+forecast for the new Monte-Carlo sample.
+
+The following synthetic figures are produced:
+@itemize
+@item
+@code{<mod_file>_redform_<endo name>_vs_lags_*.fig}: shows bar charts
+of the sensitivity indices for the ten most important parameters driving
+the reduced form coefficients of the selected endogenous variables
+(@code{namendo}) versus lagged endogenous variables (@code{namlagendo}); suffix
+@code{log} indicates the results for log-transformed entries;
+
+@item
+@code{<mod_file>_redform_<endo name>_vs_shocks_*.fig}: shows bar charts
+of the sensitivity indices for the ten most important parameters driving
+the reduced form coefficients of the selected endogenous variables
+(@code{namendo}) versus exogenous variables (@code{namexo}); suffix @code{log}
+indicates the results for log-transformed entries;
+
+@item
+@code{<mod_file>_redform_gsa(_log).fig}: shows bar chart of all sensitivity
+indices for each parameter: this allows one to notice parameters that
+have a minor effect for any of the reduced form coefficients.
+@end itemize
+
+Detailed results of the analyses are shown in the subfolder @code{<mod_file>/gsa/redform_prior} for prior samples and in @code{<mod_file>/gsa/redform_mc} for MC samples with option @code{neighborhood_width},
+where the detailed results of the estimation of the single functional relationships
+between parameters @math{\theta} and reduced form coefficient (denoted as @math{y} hereafter) are stored in separate directories
+named as:
+
+@itemize
+@item
+@code{<namendo>_vs_<namlagendo>}: for the entries of the transition matrix;
+
+@item
+@code{<namendo>_vs_<namexo>}: for entries of the matrix of the shocks.
+@end itemize
 
-@item presample = @var{INTEGER}
-@xref{presample}.
+The following files are stored in each directory (we stick with prior sample but similar convetins are used for MC samples):
+@itemize
+@item
+@code{<mod_file>_prior_<namendo>_vs_<namexo>.fig}: histogram and CDF plot of the MC sample of the individual entry
+of the shock matrix, in sample and out of sample fit of the ANOVA model;
 
-@item nograph
-@xref{nograph}.
+@item
+@code{<mod_file>_prior_<namendo>_vs_<namexo>_map_SE.fig}: for entries of the shock matrix it shows graphs of the estimated first order ANOVA terms @math{y = f(\theta_i)} for each deep parameter @math{\theta_i}; 
 
-@item nodisplay
-@xref{nodisplay}.
+@item
+@code{<mod_file>_prior_<namendo>_vs_<namlagendo>.fig}: histogram and CDF plot of the MC sample of the individual entry
+of the transition matrix, in sample and out of sample fit of the ANOVA model;
 
-@item graph_format = @var{FORMAT}
-@itemx graph_format = ( @var{FORMAT}, @var{FORMAT}@dots{} )
-@xref{graph_format}.
+@item
+@code{<mod_file>_prior_<namendo>_vs_<namlagendo>_map_SE.fig}: for entries of the transition matrix it shows graphs of the estimated first order ANOVA terms @math{y = f(\theta_i)} for each deep parameter @math{\theta_i}; 
 
-@item conf_sig = @var{DOUBLE}
-@xref{conf_sig}.
+@item
+@code{<mod_file>_prior_<namendo>_vs_<namexo>_map.mat}, @code{<mod_file>_<namendo>_vs_<namlagendo>_map.mat}: these files store info in the estimation; 
 
-@item loglinear
-@xref{loglinear}.
+@end itemize
 
-@item mode_file = @var{FILENAME}
-@xref{mode_file}.
+When option @code{logtrans_redform} is set, the ANOVA estimation is performed using a log-transformation of each @code{y}.
+The ANOVA mapping is then transformed back onto the original scale, to allow comparability with the baseline estimation.
+Graphs for this log-transformed case, are stored in the same folder in files denoted with the @code{_log} suffix.
 
-@item kalman_algo = @var{INTEGER}
-@xref{kalman_algo}.
+When the option @code{threshold_redform} is set, the analysis is performed via Monte Carlo filtering, by displaying parameters that drive the individual entry @code{y} inside the range specified in @code{threshold_redform}. If no entry is found (or all entries are in the range), the MCF algorithm ignores the range specified in @code{threshold_redform} and performs the analysis splitting the MC sample of @code{y} into deciles. Setting @code{threshold_redform=[-inf inf]} triggers this approach for all @code{y}'s.
 
-@end table
-@customhead{Identification Analysis Options}
-@table @code
+Results are stored in subdirectories of @code{<mod_file>/gsa/redform_prior} named 
+@itemize
+@item
+@code{<mod_file>_prior_<namendo>_vs_<namlagendo>_threshold}: for the entries of the transition matrix;
 
-@item identification = @var{INTEGER}
-If equal to @code{1}, performs identification anlysis (forcing @code{redform=0} and @code{morris=1})
-If equal to @code{0}, no identification analysis. Default: @code{0}
+@item
+@code{<mod_file>_prior_<namendo>_vs_<namexo>_threshold}: for entries of the matrix of the shocks.
+@end itemize
 
-@item morris = @var{INTEGER}
-@xref{morris}.
+The files saved are named
+@itemize
+@item
+@code{<mod_file>_prior_<namendo>_vs_<namexo>_threshold.fig},@code{<mod_file>_<namendo>_vs_<namlagendo>_threshold.fig}: graphical outputs; 
+@item
+@code{<mod_file>_prior_<namendo>_vs_<namexo>_threshold.mat},@code{<mod_file>_<namendo>_vs_<namlagendo>_threshold.mat}: info on the analysis; 
 
-@item morris_nliv = @var{INTEGER}
-@xref{morris_nliv}.
+@end itemize
 
-@item morris_ntra = @var{INTEGER}
-@xref{morris_ntra}.
+@node RMSE
+@subsubsection RMSE
 
-@item load_ident_files = @var{INTEGER}
-Loads previously performed identification analysis. Default: @code{0}
+The RMSE analysis can be performed with different types of sampling options:
+@enumerate
+@item
+When @code{pprior=1} and @code{ppost=0}, the toolbox analyzes the RMSEs for
+the Monte-Carlo sample obtained by sampling parameters from their prior distributions
+(or prior ranges): this analysis provides some hints about
+what parameter drives the fit of which observed series, prior to the full
+estimation;
 
-@item useautocorr = @var{INTEGER}
-Use autocorrelation matrices in place of autocovariance matrices in moments
-for identification analysis. Default: @code{0}
+@item
+When @code{pprior=0} and @code{ppost=0}, the toolbox analyzes the RMSEs for
+a multivariate normal Monte-Carlo sample, with covariance matrix based on
+the inverse Hessian at the optimum: this analysis is useful when maximum likelihood
+estimation is done (@i{i.e.} no Bayesian estimation);
 
-@item ar = @var{INTEGER}
-Maximum number of lags for moments in identification analysis. Default: @code{1}
+@item
+When @code{ppost=1} the toolbox analyzes the RMSEs for the posterior sample
+obtained by Dynare's Metropolis procedure.
+@end enumerate
 
-@item lik_init = @var{INTEGER}
-@xref{lik_init}.
+The use of cases 2 and 3 requires an estimation step beforehand. To
+facilitate the sensitivity analysis after estimation, the @code{dynare_sensitivity}
+command also allows you to indicate some options of the @code{estimation}
+command. These are:
+@itemize @bullet
+@item @code{datafile}
+@item @code{nobs}
+@item @code{first_obs}
+@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}
+@end itemize
 
-@end table
+Binary files produced my RMSE analysis are:
+@itemize
+@item
+@code{<mod_file>_prior_*.mat}: these files store the filtered and smoothed
+    variables for the prior Monte-Carlo sample, generated when doing RMSE analysis
+    (@code{pprior=1} and @code{ppost=0});
+@item
+@code{<mode_file>_mc_*.mat}: these files store the filtered and smoothed variables
+    for the multivariate normal Monte-Carlo sample, generated when doing
+    RMSE analysis (@code{pprior=0} and @code{ppost=0}).
+@end itemize
 
-@end deffn
+Figure files @code{<mod_file>_rmse_*.fig} store results for the RMSE analysis.
 
-@deffn Command identification ;
-@deffnx Command identification (@var{OPTIONS}@dots{});
+@itemize
+@item
+@code{<mod_file>_rmse_prior*.fig}: save results for the analysis using prior
+Monte-Carlo samples;
 
-@descriptionhead
+@item
+@code{<mod_file>_rmse_mc*.fig}: save results for the analysis using multivariate
+normal Monte-Carlo samples;
 
-This command triggers identification analysis.
+@item
+@code{<mod_file>_rmse_post*.fig}: save results for the analysis using Metropolis
+posterior samples.
+@end itemize
 
-@optionshead
+The following types of figures are saved (we show prior sample to fix ideas,
+but the same conventions are used for multivariate normal and posterior):
 
-@table @code
+@itemize
+@item
+@code{<mod_file>_rmse_prior_params_*.fig}: for each parameter, plots the cdfs 
+corresponding to the best 10% RMSEs of each observed series (only those cdfs below the significance threshold @code{alpha_rmse});
 
-@item ar = @var{INTEGER}
-Number of lags of computed autocorrelations (theoretical moments). Default: @code{1}
+@item
+@code{<mod_file>_rmse_prior_<var_obs>_*.fig}: if a parameter significantly affects the fit of @code{var_obs}, all possible trade-off's with other observables for same parameter are plotted;
 
-@item useautocorr = @var{INTEGER}
-If equal to @code{1}, compute derivatives of autocorrelation. If equal
-to @code{0}, compute derivatives of autocovariances. Default: @code{0}
+@item
+@code{<mod_file>_rmse_prior_<var_obs>_map.fig}: plots the MCF analysis of parameters significantly driving the fit the observed series @code{var_obs};
 
-@item load_ident_files = @var{INTEGER}
-If equal to @code{1}, allow Dynare to load previously
-computed analyzes. Default: @code{0}
+@item
+@code{<mod_file>_rmse_prior_lnlik*.fig}: for each observed series, plots
+in BLUE the cdf of the log-likelihood corresponding to the best 10%
+RMSEs, in RED the cdf of the rest of the sample and in BLACK the
+cdf of the full sample; this allows one to see the presence of some
+idiosyncratic behavior;
 
-@item prior_mc = @var{INTEGER}
-Size of Monte-Carlo sample. Default: @code{1}
+@item
+@code{<mod_file>_rmse_prior_lnpost*.fig}: for each observed series, plots
+in BLUE the cdf of the log-posterior corresponding to the best 10% RMSEs,
+in RED the cdf of the rest of the sample and in BLACK the cdf of the full
+sample; this allows one to see idiosyncratic behavior;
 
-@item prior_range = @var{INTEGER}
-Triggers uniform sample within the range implied by the prior specifications (when
-@code{prior_mc>1}). Default: @code{0}
+@item
+@code{<mod_file>_rmse_prior_lnprior*.fig}: for each observed series, plots
+in BLUE the cdf of the log-prior corresponding to the best 10% RMSEs,
+in RED the cdf of the rest of the sample and in BLACK the cdf of the full
+sample; this allows one to see idiosyncratic behavior;
 
-@item advanced = @var{INTEGER}
-Shows a more detailed analysis, comprised of an analysis for the linearized rational
-expectation model as well as the associated reduced form solution. Further performs a brute
-force search of the groups of parameters best reproducing the behavior of each single parameter.
-The maximum dimension of the group searched is triggered by @code{max_dim_cova_group}. Default: @code{0}
+@item
+@code{<mod_file>_rmse_prior_lik.fig}: when @code{lik_only=1}, this shows
+the MCF tests for the filtering of the best 10% log-likelihood values;
 
-@item max_dim_cova_group = @var{INTEGER}
-In the brute force search (performed when @code{advanced=1}) this option sets the maximum dimension of groups
-of parameters that best reproduce the behavior of each single model parameter. Default: @code{2}
+@item
+@code{<mod_file>_rmse_prior_post.fig}: when @code{lik_only=1}, this shows
+the MCF tests for the filtering of the best 10% log-posterior values.
+@end itemize
 
-@item periods = @var{INTEGER}
-When the analytic Hessian is not available (@i{i.e.} with missing values or diffuse
-Kalman filter or univariate Kalman filter), this triggers the length of stochastic simulation
-to compute Simulated Moments Uncertainty. Default: @code{300}
+@node Screening Analysis
+@subsubsection Screening Analysis
 
-@item replic = @var{INTEGER}
-When the analytic Hessian is not available, this triggers the number of replicas
-to compute Simulated Moments Uncertainty. Default: @code{100}
+Screening analysis does not require any additional options with respect to
+those listed in @ref{Sampling Options}. The toolbox performs all the
+analyses required and displays results.
 
-@item gsa_sample_file = @var{INTEGER}
-If equal to @code{0}, do not use sample file.
-If equal to @code{1}, triggers gsa prior sample.
-If equal to @code{2}, triggers gsa Monte-Carlo sample (@i{i.e.} loads a sample corresponding to
-@code{pprior=0} and @code{ppost=0} in the @code{dynare_sensitivity} options). Default: @code{0}
+The results of the screening analysis with Morris sampling design are stored
+in the subfolder @code{<mod_file>/gsa/screen}. The data file @code{<mod_file>_prior} stores
+all the information of the analysis (Morris sample, reduced form coefficients,
+etc.).
 
-@item gsa_sample_file = @var{FILENAME}
-Uses the provided path to a specific user defined sample file. Default: @code{0}
+Screening analysis merely concerns reduced form coefficients. Similar
+synthetic bar charts as for the reduced form analysis with Monte-Carlo samples are
+saved:
+@itemize
+@item
+@code{<mod_file>_redform_<endo name>_vs_lags_*.fig}: shows bar charts
+of the elementary effect tests for the ten most important parameters
+driving the reduced form coefficients of the selected endogenous variables
+(@code{namendo}) versus lagged endogenous variables (@code{namlagendo});
 
-@item parameter_set = @code{calibration} | @code{prior_mode} | @code{prior_mean} | @code{posterior_mode} | @code{posterior_mean} | @code{posterior_median}
-Specify the parameter set to use. Default: @code{prior_mean}
+@item
+@code{<mod_file>_redform_<endo name>_vs_shocks_*.fig}: shows bar charts
+of the elementary effect tests for the ten most important parameters
+driving the reduced form coefficients of the selected endogenous variables
+(@code{namendo}) versus exogenous variables (@code{namexo});
 
-@item lik_init = @var{INTEGER}
-@xref{lik_init}.
+@item
+@code{<mod_file>_redform_screen.fig}: shows bar chart of all elementary
+effect tests for each parameter: this allows one to identify parameters that
+have a minor effect for any of the reduced form coefficients.
+@end itemize
 
-@item kalman_algo = @var{INTEGER}
-@xref{kalman_algo}.
+@node Identification Analysis
+@subsubsection Identification Analysis
 
-@item nograph
-@xref{nograph}.
+Setting the option @code{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.
 
-@item nodisplay
-@xref{nodisplay}.
+Prerequisite for properly running all the identification routines, is the keyword
+@code{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 option @code{morris=2},
+which implements @cite{Iskrev (2010)} identification analysis.
 
-@item graph_format = @var{FORMAT}
-@itemx graph_format = ( @var{FORMAT}, @var{FORMAT}@dots{} )
-@xref{graph_format}.
+For example, the placing @code{identification; dynare_sensitivity(identification=1, morris=2);}
+in the Dynare model file trigger identification analysis using analytic derivatives
+@cite{Iskrev (2010)}, jointly with the mapping of the acceptable region.
 
-@end table
+The identification analysis with derivatives can also be triggered by the
+commands @code{identification;} 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.
 
-@end deffn
 
 @node Markov-switching SBVAR
 @section Markov-switching SBVAR
@@ -8322,6 +8694,7 @@ constructed as explained above.
 @subsection Macro directives
 
 @deffn {Macro directive} @@#include "@var{FILENAME}"
+@deffnx {Macro directive} @@#include @var{MACRO_VARIABLE}
 This directive simply includes the content of another file at the
 place where it is inserted. It is exactly equivalent to a copy/paste
 of the content of the included file. Note that it is possible to nest
@@ -8331,6 +8704,7 @@ includes (@i{i.e.} to include a file from an included file).
 
 @example
 @@#include "modelcomponent.mod"
+@@#include location_of_modfile
 @end example
 
 @end deffn
@@ -11406,7 +11780,7 @@ Report Title. Default: @code{none}
 @end defmethod
 
 @anchor{addPage}
-@defmethod Report addPage footnote, orientation, paper, title, titleFormat
+@defmethod Report addPage footnote, orientation, paper, title, titleFormat, titleTruncate
 Adds a @code{Page} to the @code{Report}.
 @optionshead
 @table @code
@@ -11433,6 +11807,12 @@ number of cell array entries must be equal to that of the @ref{title}
 option if you do not want to use the default value for the title (and
 subtitles). Default: @code{\large\bfseries}
 
+@item titleTruncate, @code{INTEGER}
+Useful when automatically generating page titles that may become too
+long, @code{titleTruncate} can be used to truncate a title (and
+subsequent subtitles) when they pass the specified number of
+characters. Default: @code{off}
+
 @end table
 @end defmethod
 
@@ -11450,7 +11830,7 @@ command. Default: @code{`!'}
 @end defmethod
 
 @anchor{addGraph}
-@defmethod Report addGraph axisShape, data, graphDirName, graphName, graphSize, height, showGrid, showLegend, showLegendBox, legendLocation, legendOrientation, legendFontSize, miscTikzAxisOptions, miscTikzPictureOptions, seriesToUse, shade, shadeColor, shadeOpacity, tickFontSize, title, titleFontSize, titleFormat, width, writeCSV, xlabel, ylabel, xAxisTight, xrange, xTicks, xTickLabels, xTickLabelAnchor, xTickLabelRotation, yAxisTight, yTickLabelFixed, yTickLabelPrecision, yTickLabelScaled, yTickLabelZeroFill, yrange, showZeroline, zeroLineColor
+@defmethod Report addGraph axisShape, data, graphDirName, graphName, graphSize, height, showGrid, showLegend, legendAt, showLegendBox, legendLocation, legendOrientation, legendFontSize, miscTikzAxisOptions, miscTikzPictureOptions, seriesToUse, shade, shadeColor, shadeOpacity, tickFontSize, title, titleFontSize, titleFormat, width, writeCSV, xlabel, ylabel, xAxisTight, xrange, xTicks, xTickLabels, xTickLabelAnchor, xTickLabelRotation, yAxisTight, yTickLabelFixed, yTickLabelPrecision, yTickLabelScaled, yTickLabelZeroFill, yrange, showZeroline, zeroLineColor
 Adds a @code{Graph} to a @code{Section}.
 @optionshead
 @table @code
@@ -11489,10 +11869,16 @@ Whether or not to display the legend. NB: Unless you use the
 @code{tex} name associated with the @code{dseries}. You can modify this
 @code{tex} name by using @ref{tex_rename}. Default: @code{false}
 
+@item legendAt, @code{NUMERICAL_VECTOR}
+The coordinates for the legend location. If this option is passed, it
+overrides the @ref{legendLocation} option. Must be of size 2. Default:
+@code{empty}.
+
 @item showLegendBox, @code{BOOLEAN}
 Whether or not to display a box around the legend. Default:
 @code{false}
 
+@anchor{legendLocation}
 @item legendLocation, @code{`south west'} | @code{`south east'} | @code{`north west'} | @code{`north east'} | @code{`outer north east'}
 Where to place the legend in the graph. Default: @code{`south east'}
 
@@ -11694,7 +12080,7 @@ with the same base name as specified by @ref{tableName} with the ending
 @end defmethod
 
 @anchor{addSeries}
-@defmethod Report addSeries data, graphHline, graphLegendName, graphLineColor, graphLineStyle, graphLineWidth, graphMarker, graphMarkerEdgeColor, graphMarkerFaceColor, graphMarkerSize, graphMiscTikzAddPlotOptions, graphShowInLegend, graphVline, tableDataRhs, tableRowColor, tableRowIndent, tableShowMarkers, tableAlignRight, tableNegColor, tablePosColor, tableSubSectionHeader, zeroTol
+@defmethod Report addSeries data, graphBar, graphBarColor, graphBarFillColor, graphBarWidth, graphFanShadeColor, graphFanShadeOpacity, graphHline, graphLegendName, graphLineColor, graphLineStyle, graphLineWidth, graphMarker, graphMarkerEdgeColor, graphMarkerFaceColor, graphMarkerSize, graphMiscTikzAddPlotOptions, graphShowInLegend, graphVline, tableDataRhs, tableRowColor, tableRowIndent, tableShowMarkers, tableAlignRight, tableNegColor, tablePosColor, tableSubSectionHeader, zeroTol
 Adds a @code{Series} to a @code{Graph} or a @code{Table}. NB: Options specific
 to graphs begin with `@code{graph}' while options specific to tables begin with
 `@code{table}'.
@@ -11704,6 +12090,32 @@ to graphs begin with `@code{graph}' while options specific to tables begin with
 @item data, @code{dseries}
 @xref{data}.
 
+@anchor{graphBar}
+@item graphBar, @code{BOOLEAN}
+Whether or not to display this series as a bar graph as oppsed to the
+default of displaying it as a line graph. Default: @code{false}
+
+@anchor{graphFanShadeColor}
+@item graphFanShadeColor, @code{STRING}
+The shading color to use between a series and the previously-added
+series in a graph. Useful for making fan charts. Default: @code{empty}
+
+@item graphFanShadeOpacity, @code{INTEGER}
+The opacity of the color passed in @ref{graphFanShadeColor}. Default:
+@code{50}
+
+@item graphBarColor, @code{STRING}
+The outline color of each bar in the bar graph. Only active if
+@ref{graphBar} is passed. Default: @code{`black'}
+
+@item graphBarFillColor, @code{STRING}
+The fill color of each bar in the bar graph. Only active if
+@ref{graphBar} is passed. Default: @code{`black'}
+
+@item graphBarWidth, @code{DOUBLE}
+The width of each bar in the bar graph. Only active if @ref{graphBar}
+is passed. Default: @code{2}
+
 @item graphHline, @code{DOUBLE}
 Use this option to draw a horizontal line at the given value. Default:
 @code{empty}
@@ -12110,6 +12522,11 @@ Expansion Approach to Simulation of Stochastic Forward-Looking Models
 with an Application to a Non-Linear Phillips Curve,'' @i{Computational
 Economics}, 17, 125--139
 
+@item
+Corona, Angelo,  M. Marchesi, Claudio Martini, and Sandro Ridella (1987):
+``Minimizing multimodal functions of continuous variables with the ``simulated annealing'' algorithm'',
+@i{ACM Transactions on Mathematical Software}, 13(3), 262--280
+
 @item
 Christiano, Lawrence J., Mathias Trabandt and Karl Walentin (2011):
 ``Introducing financial frictions and unemployment into a small open
@@ -12158,6 +12575,16 @@ International Meeting on Bayesian Statistics, pp. 169--194, Oxford University Pr
 Geweke, John (1999): ``Using simulation methods for Bayesian econometric models:
 Inference, development and communication,'' @i{Econometric Reviews}, 18(1), 1--73
 
+@item 
+Goffe, William L., Gary D. Ferrier, and John Rogers (1994): ``Global Optimization 
+of Statistical Functions with Simulated Annealing,'' @i{Journal of Econometrics}, 60(1/2), 
+65--100
+
+@item
+Hansen, Nikolaus and Stefan Kern (2004): ``Evaluating the CMA Evolution Strategy 
+on Multimodal Test Functions''. In: @i{Eighth International Conference on Parallel 
+Problem Solving from Nature PPSN VIII, Proceedings}, Berlin: Springer, 282--291 
+
 @item
 Ireland, Peter (2004): ``A Method for Taking Models to the Data,''
 @i{Journal of Economic Dynamics and Control}, 28, 1205--26
@@ -12177,6 +12604,11 @@ 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
 
+@item
+Kim, Jinill and Sunghyun Kim (2003): ``Spurious welfare reversals in 
+international business cycle models,'' @i{Journal of International
+Economics}, 60, 471--500
+
 @item
 Kim, Jinill, Sunghyun Kim, Ernst Schaumburg, and Christopher A. Sims
 (2008): ``Calculating and using second-order accurate solutions of
@@ -12191,6 +12623,11 @@ 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
 
+@item 
+Kuntsevich, Alexei V. and  Franz Kappel (1997): ``SolvOpt - The solver 
+for local nonlinear optimization problems (version 1.1, Matlab, C, FORTRAN)'', 
+University of Graz, Graz, Austria
+
 @item
 Laffargue, Jean-Pierre (1990): ``Résolution d'un modèle
 macroéconomique avec anticipations rationnelles'', @i{Annales
@@ -12247,6 +12684,12 @@ Villemot, Sébastien (2011): ``Solving rational expectations models at
 first order: what Dynare does,'' @i{Dynare Working Papers}, 2,
 CEPREMAP
 
+@item
+Woodford, Michael (2011): ``Commentary: How Should Monetary Policy Be 
+Conducted in an Era of Price Stability?'' @i{Proceedings - Economic Policy Symposium - Jackson Hole}, 
+277-316
+
+
 @end itemize
 
 @node Command and Function Index
diff --git a/dynare++/kord/journal.cweb b/dynare++/kord/journal.cweb
index 9b7d658cddb5c4f700e49c352408d2a67b477fdf..b43b27bcc9ae2c428e8baf9df430b7f54d3c78b7 100644
--- a/dynare++/kord/journal.cweb
+++ b/dynare++/kord/journal.cweb
@@ -101,7 +101,7 @@ void SystemResources::getRUS(double& load_avg, long int& pg_avail,
 	majflt = -1;
 #endif
 
-#if !defined(__MINGW32__) && !defined(__CYGWIN32__)
+#if !defined(__MINGW32__) && !defined(__CYGWIN32__) && !defined(__CYGWIN__) && !defined(__MINGW64__) && !defined(__CYGWIN64__)
 	getloadavg(&load_avg, 1);
 #else
 	load_avg = -1.0;
diff --git a/dynare++/parser/cc/dynamic_atoms.cpp b/dynare++/parser/cc/dynamic_atoms.cpp
index f02b580af1281f094a69b06bc60c268695734146..ca6b6dcd219158d9faf22f76da01c2c5ea460332 100644
--- a/dynare++/parser/cc/dynamic_atoms.cpp
+++ b/dynare++/parser/cc/dynamic_atoms.cpp
@@ -341,6 +341,12 @@ int DynamicAtoms::index(const char* name, int ll) const
 	return -1;
 }
 
+bool DynamicAtoms::is_referenced(const char* name) const
+{
+	Tvarmap::const_iterator it = vars.find(name);
+	return it != vars.end();
+}
+
 const DynamicAtoms::Tlagmap& DynamicAtoms::lagmap(const char* name) const
 {
 	Tvarmap::const_iterator it = vars.find(name);
diff --git a/dynare++/parser/cc/dynamic_atoms.h b/dynare++/parser/cc/dynamic_atoms.h
index 03cb0411fdc1ff8f54b4e4bc07ae6621324362af..7d44d6dcc2e71faa4066145281b9229dbd6c7bc5 100644
--- a/dynare++/parser/cc/dynamic_atoms.h
+++ b/dynare++/parser/cc/dynamic_atoms.h
@@ -182,6 +182,9 @@ namespace ogp {
 		/** Return index of the variable described by the variable
 		 * name and lag/lead. If it doesn't exist, return -1. */
 		int index(const char* name, int ll) const;
+		/** Return true if a variable is referenced, i.e. it has lag
+		 * map. */
+		bool is_referenced(const char* name) const;
 		/** Return the lag map for the variable name. */
 		const Tlagmap& lagmap(const char* name) const;
 		/** Return the variable name for the tree index. It throws an
diff --git a/dynare++/parser/cc/static_atoms.cpp b/dynare++/parser/cc/static_atoms.cpp
index 0151cade68f2c66c2c7a83e6f3f39bc634b3e799..7276cc0c9a90e9b40dd39f0a6dff566e99e317de 100644
--- a/dynare++/parser/cc/static_atoms.cpp
+++ b/dynare++/parser/cc/static_atoms.cpp
@@ -41,15 +41,14 @@ void StaticAtoms::import_atoms(const DynamicAtoms& da, OperationTree& otree, Tin
 		register_name(name);
 		int tnew = otree.add_nulary();
 		assign(name, tnew);
-		try {
-			const DynamicAtoms::Tlagmap& lmap = da.lagmap(name);
+        if (da.is_referenced(name)) {
+            const DynamicAtoms::Tlagmap& lmap = da.lagmap(name);
 			for (DynamicAtoms::Tlagmap::const_iterator it = lmap.begin();
 				 it != lmap.end(); ++it) {
 				int told = (*it).second;
 				tmap.insert(Tintintmap::value_type(told, tnew));
 			}
-		} catch (const ogu::Exception& e) {
-		}
+        }
 	}
 }
 
diff --git a/dynare++/parser/cc/tree.cpp b/dynare++/parser/cc/tree.cpp
index 08c90fae610a7b1215c06e4714ba706351eee1ed..8ff4267c6f634f1c432621981cef2fb6d3aa251d 100644
--- a/dynare++/parser/cc/tree.cpp
+++ b/dynare++/parser/cc/tree.cpp
@@ -1,5 +1,6 @@
 // Copyright (C) 2005-2011, Ondra Kamenik
 
+
 #include "utils/cc/exception.h"
 
 #include "tree.h"
@@ -55,7 +56,7 @@ int OperationTree::add_unary(code_t code, int op)
 		 code == SQRT ||
 		 code == ERF))
 		return zero;
-	if (op == zero && code == LOG || op == nan)
+	if ((op == zero && code == LOG) || op == nan)
 		return nan;
 	if (op == zero && (code == EXP ||
 					   code == COS ||
@@ -86,39 +87,43 @@ int OperationTree::add_binary(code_t code, int op1, int op2)
 	if (op1 == nan || op2 == nan)
 		return nan;
 	// for plus
-	if (code == PLUS)
+	if (code == PLUS) {
 		if (op1 == zero && op2 == zero)
 			return zero;
 		else if (op1 == zero)
 			return op2;
 		else if (op2 == zero)
 			return op1;
+    }
 	// for minus
-	if (code == MINUS)
+	if (code == MINUS) {
 		if (op1 == zero && op2 == zero)
 			return zero;
 		else if (op1 == zero)
 			return add_unary(UMINUS, op2);
 		else if (op2 == zero)
 			return op1;
+    }
 	// for times
-	if (code == TIMES)
+	if (code == TIMES) {
 		if (op1 == zero || op2 == zero)
 			return zero;
 		else if (op1 == one)
 			return op2;
 		else if (op2 == one)
 			return op1;
+    }
 	// for divide
-	if (code == DIVIDE)
+	if (code == DIVIDE) {
 		if (op1 == op2)
 			return one;
 		else if (op1 == zero)
 			return zero;
 		else if (op2 == zero)
 			return nan;
+    }
 	// for power
-	if (code == POWER)
+	if (code == POWER) {
 		if (op1 == zero && op2 == zero)
 			return nan;
 		else if (op1 == zero)
@@ -129,6 +134,7 @@ int OperationTree::add_binary(code_t code, int op1, int op2)
 			return one;
 		else if (op2 == one)
 			return op1;
+    }
 
 	// order operands of commutative operations
 	if (code == TIMES || code == PLUS)
diff --git a/dynare++/src/dynare_atoms.cpp b/dynare++/src/dynare_atoms.cpp
index e0121d5306c910dd5ea1723f43673deeae5036ff..c1ae58bc40c7db5a1010124025b4bfcef5314121 100644
--- a/dynare++/src/dynare_atoms.cpp
+++ b/dynare++/src/dynare_atoms.cpp
@@ -135,22 +135,19 @@ void DynareAtomValues::setValues(ogp::EvalTree& et) const
 
 	// set parameteres
 	for (unsigned int i = 0; i < atoms.get_params().size(); i++) {
-		try {
+        if (atoms.is_referenced(atoms.get_params()[i])) {
 			const ogp::DynamicAtoms::Tlagmap& lmap = atoms.lagmap(atoms.get_params()[i]);
 			for (ogp::DynamicAtoms::Tlagmap::const_iterator it = lmap.begin();
 				 it != lmap.end(); ++it) {
 				int t = (*it).second;
 				et.set_nulary(t, paramvals[i]);
 			}
-		} catch (const ogu::Exception& e) {
-			// ignore non-referenced parameters; there is no
-			// lagmap for them
 		}
 	}
 
 	// set endogenous
 	for (unsigned int outer_i = 0; outer_i < atoms.get_endovars().size(); outer_i++) {
-		try {
+        if (atoms.is_referenced(atoms.get_endovars()[outer_i])) {
 			const ogp::DynamicAtoms::Tlagmap& lmap = atoms.lagmap(atoms.get_endovars()[outer_i]);
 			for (ogp::DynamicAtoms::Tlagmap::const_iterator it = lmap.begin();
 				 it != lmap.end(); ++it) {
@@ -165,15 +162,12 @@ void DynareAtomValues::setValues(ogp::EvalTree& et) const
 				else
 					et.set_nulary(t, yyp[i-atoms.nstat()-atoms.npred()]);
 			}
-		} catch (const ogu::Exception& e) {
-			// ignore non-referenced endogenous variables; there is no
-			// lagmap for them
 		}
 	}
 
 	// set exogenous
 	for (unsigned int outer_i = 0; outer_i < atoms.get_exovars().size(); outer_i++) {
-		try {
+        if (atoms.is_referenced(atoms.get_exovars()[outer_i])) {
 			const ogp::DynamicAtoms::Tlagmap& lmap = atoms.lagmap(atoms.get_exovars()[outer_i]);
 			for (ogp::DynamicAtoms::Tlagmap::const_iterator it = lmap.begin();
 				 it != lmap.end(); ++it) {
@@ -184,8 +178,6 @@ void DynareAtomValues::setValues(ogp::EvalTree& et) const
 					et.set_nulary(t, xx[i]);
 				}
 			}
-		} catch (const ogu::Exception& e) {
-			// ignore non-referenced variables
 		}
 	}
 }
diff --git a/dynare++/src/forw_subst_builder.cpp b/dynare++/src/forw_subst_builder.cpp
index 5f85f0fabad81faa308fe20e10f59705dd57e1b2..e2fa6cf55838c502afdcc17a3ce0e8c03b4cb8ae 100644
--- a/dynare++/src/forw_subst_builder.cpp
+++ b/dynare++/src/forw_subst_builder.cpp
@@ -1,5 +1,6 @@
 // Copyright (C) 2006-2011, Ondra Kamenik
 
+
 #include "forw_subst_builder.h"
 
 using namespace ogdyn;
@@ -47,18 +48,20 @@ void ForwSubstBuilder::substitute_for_term(int t, int i, int j)
 		// first make lagsubst be substitution setting f(x(+4)) to f(x(+1))
 		// this is lag = -3 (1-mlead)
 		map<int,int> lagsubst;
-		model.variable_shift_map(model.eqs.nulary_of_term(t), 1-mlead, lagsubst);
+        unordered_set<int> nult = model.eqs.nulary_of_term(t);// make copy of nult!
+		model.variable_shift_map(nult, 1-mlead, lagsubst);
 		int lagt = model.eqs.add_substitution(t, lagsubst);
-		// now maxlead of lagt is +1
-		// add AUXLD_*_*_1 = f(x(+1)) to the model
-		char name[100];
-		sprintf(name, "AUXLD_%d_%d_%d", i, j, 1);
-		model.atoms.register_uniq_endo(name);
-		info.num_aux_variables++;
-		const char* ss = model.atoms.get_name_storage().query(name);
-		int auxt = model.eqs.add_nulary(name);
-		model.eqs.add_formula(model.eqs.add_binary(ogp::MINUS, auxt, lagt));
-		aux_map.insert(Tsubstmap::value_type(ss, lagt));
+
+        // now maxlead of lagt is +1
+        // add AUXLD_*_*_1 = f(x(+1)) to the model
+        char name[100];
+        sprintf(name, "AUXLD_%d_%d_%d", i, j, 1);
+        model.atoms.register_uniq_endo(name);
+        info.num_aux_variables++;
+        const char* ss = model.atoms.get_name_storage().query(name);
+        int auxt = model.eqs.add_nulary(name);
+        model.eqs.add_formula(model.eqs.add_binary(ogp::MINUS, auxt, lagt));
+        aux_map.insert(Tsubstmap::value_type(ss, lagt));
 		// now add variables and equations
 		// AUXLD_*_*_2 = AUXLD_*_*_1(+1) through
 		// AUXLD_*_*_{mlead-1} = AUXLD_*_*_{mlead-2}(+1)
@@ -82,7 +85,9 @@ void ForwSubstBuilder::substitute_for_term(int t, int i, int j)
 			aux_map.insert(Tsubstmap::value_type(ss, lagt));
 		}
 
-		// now we have to substitute AUXLEAD_*_*{mlead-1}(+1) for t
+		// now we have to substitute AUXLD_*_*{mlead-1}(+1) for t
+        sprintf(name, "AUXLD_%d_%d_%d", i, j, mlead-1);
+        ss = model.atoms.get_name_storage().query(name);
 		model.substitute_atom_for_term(ss, +1, t);
 	}
 }
diff --git a/dynare++/src/planner_builder.cpp b/dynare++/src/planner_builder.cpp
index d2a38dfd4f14d3f612da128c2e2b4494acc6f2b5..6958a8ab62d3f46b3e3733ff065f16ba09402519 100644
--- a/dynare++/src/planner_builder.cpp
+++ b/dynare++/src/planner_builder.cpp
@@ -327,11 +327,11 @@ MultInitSS::MultInitSS(const PlannerBuilder& pb, const Vector& pvals, Vector& yy
 	ogp::FormulaCustomEvaluator fe(builder.static_tree, terms);
 	fe.eval(dssav, *this);
 
-	// solve overdetermined system b+F*lambda=0 => lambda=-(F^T*F)^{-1}*F^T*b
-	GeneralMatrix FtF(F, "transpose", F);
-	Vector lambda(builder.diff_f_static.dim2());
-	F.multVecTrans(0.0, lambda, -1.0, b);
-	ConstGeneralMatrix(FtF).multInvLeft(lambda);
+	// solve overdetermined system b+F*lambda=0 using SVD decomposition
+    SVDDecomp decomp(F);
+    Vector lambda(builder.diff_f_static.dim2());
+    decomp.solve(b, lambda);
+    lambda.mult(-1);
 
 	// take values of lambda and put it to yy
 	for (int fi = 0; fi < builder.diff_f_static.dim2(); fi++) {
diff --git a/dynare++/sylv/cc/GeneralMatrix.cpp b/dynare++/sylv/cc/GeneralMatrix.cpp
index b50b3ed4f3c82938a95c2a85e02a068e334981f4..75834f522e4eb367ee6876475b9d0db6aef138fe 100644
--- a/dynare++/sylv/cc/GeneralMatrix.cpp
+++ b/dynare++/sylv/cc/GeneralMatrix.cpp
@@ -481,3 +481,76 @@ void ConstGeneralMatrix::print() const
 		printf("\n");
 	}
 }
+
+void SVDDecomp::construct(const GeneralMatrix& A)
+{
+    // quick exit if empty matrix
+    if (minmn == 0) {
+        U.unit();
+        VT.unit();
+        conv = true;
+        return;
+    }
+
+    // make copy of the matrix
+    GeneralMatrix AA(A);
+
+    lapack_int m = AA.numRows();
+    lapack_int n = AA.numCols();
+    double* a = AA.base();
+    lapack_int lda = AA.getLD();
+    double* s = sigma.base();
+    double* u = U.base();
+    lapack_int ldu = U.getLD();
+    double* vt = VT.base();
+    lapack_int ldvt = VT.getLD();
+    double tmpwork;
+    lapack_int lwork = -1;
+    lapack_int info;
+
+    lapack_int* iwork = new lapack_int[8*minmn];
+    // query for optimal lwork
+    dgesdd("A", &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, &tmpwork,
+                  &lwork, iwork, &info);
+    lwork = (lapack_int)tmpwork;
+    Vector work(lwork);
+    // do the decomposition
+    dgesdd("A", &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, work.base(),
+                  &lwork, iwork, &info);
+    delete [] iwork;
+    if (info < 0)
+        throw SYLV_MES_EXCEPTION("Internal error in SVDDecomp constructor");
+    if (info == 0)
+        conv = true;
+}
+
+void SVDDecomp::solve(const GeneralMatrix& B, GeneralMatrix& X) const
+{
+    if (B.numRows() != U.numRows())
+        throw SYLV_MES_EXCEPTION("Incompatible number of rows ");
+
+    // reciprocal condition number for determination of zeros in the
+    // end of sigma
+    double rcond = 1e-13;
+
+    // solve U: B = U^T*B
+    GeneralMatrix UTB(U, "trans", B);
+    // determine nz=number of zeros in the end of sigma
+    int nz = 0;
+    while (nz < minmn && sigma[minmn-1-nz] < rcond*sigma[0])
+        nz++;
+    // take relevant B for sigma inversion
+    int m = U.numRows();
+    int n = VT.numCols();
+    GeneralMatrix Bprime(UTB, m-minmn, 0, minmn-nz, B.numCols());
+    // solve sigma
+    for (int i = 0; i < minmn-nz; i++)
+        Vector(i, Bprime).mult(1.0/sigma[i]);
+    // solve VT
+    X.zeros();
+    //- copy Bprime to right place of X
+    for (int i = 0; i < minmn-nz; i++)
+        Vector(n-minmn+i, X) = ConstVector(i, Bprime);
+    //- multiply with VT
+    X.multLeftTrans(VT);
+}
diff --git a/dynare++/sylv/cc/GeneralMatrix.h b/dynare++/sylv/cc/GeneralMatrix.h
index 18413b762d67f970ab53197e2af757ac8dada72e..d24c11cad951535efdce167133c6d72bc9a28b2f 100644
--- a/dynare++/sylv/cc/GeneralMatrix.h
+++ b/dynare++/sylv/cc/GeneralMatrix.h
@@ -7,6 +7,8 @@
 
 #include "Vector.h"
 
+#include <algorithm>
+
 class GeneralMatrix;
 
 class ConstGeneralMatrix {
@@ -272,6 +274,40 @@ private:
 	static int md_length;
 };
 
+class SVDDecomp {
+protected:
+    /** Minimum of number of rows and columns of the decomposed
+     * matrix. */
+    const int minmn;
+    /** Singular values. */
+    Vector sigma;
+    /** Orthogonal matrix U. */
+    GeneralMatrix U;
+    /** Orthogonal matrix V^T. */
+    GeneralMatrix VT;
+    /** Convered flag. */
+    bool conv;
+public:
+    SVDDecomp(const GeneralMatrix& A)
+        : minmn(std::min<int>(A.numRows(), A.numCols())),
+          sigma(minmn),
+          U(A.numRows(), A.numRows()),
+          VT(A.numCols(), A.numCols()),
+          conv(false)
+        {construct(A);}
+    const GeneralMatrix& getU() const
+        {return U;}
+    const GeneralMatrix& getVT() const
+        {return VT;}
+    void solve(const GeneralMatrix& B, GeneralMatrix& X) const;
+    void solve(const Vector& b, Vector& x) const
+        {
+            GeneralMatrix xmat(x.base(), x.length(), 1);
+            solve(GeneralMatrix(b.base(), b.length(), 1), xmat);
+        }
+private:
+    void construct(const GeneralMatrix& A);
+};
 
 
 
diff --git a/license.txt b/license.txt
index 27122feb62a644eb287fd64444356008477e6cd0..0f9bcbaf496436b22be33b2dfc1aa57d8deac416 100644
--- a/license.txt
+++ b/license.txt
@@ -1,6 +1,6 @@
 Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
 Upstream-Name: Dynare
-Upstream-Contact: Dynare Team, whose members in 2014 are:
+Upstream-Contact: Dynare Team, whose members in 2015 are:
                   Stéphane Adjemian <stephane.adjemian@univ-lemans.fr>
                   Houtan Bastani <houtan@dynare.org>
                   Michel Juillard <michel.juillard@mjui.fr>
@@ -14,7 +14,7 @@ Upstream-Contact: Dynare Team, whose members in 2014 are:
 Source: http://www.dynare.org
 
 Files: *
-Copyright: 1996-2014 Dynare Team
+Copyright: 1996-2015 Dynare Team
 License: GPL-3+
 
 Files: matlab/AIM/SP*
@@ -39,20 +39,33 @@ License: public-domain
  Journal of Economic Dynamics and Control, 2010, vol. 34, issue 3,
  pages 472-489
 
-Files: matlab/bfgsi1.m matlab/csolve.m matlab/csminit1.m matlab/numgrad2.m
- matlab/numgrad3.m matlab/numgrad3_.m matlab/numgrad5.m
- matlab/numgrad5_.m matlab/csminwel1.m matlab/bvar_density.m
+Files: matlab/bfgsi1.m matlab/csolve.m matlab/optimization/csminit1.m matlab/optimization/numgrad2.m
+ matlab/optimization/numgrad3.m matlab/optimization/numgrad3_.m matlab/optimization/numgrad5.m
+ matlab/optimization/numgrad5_.m matlab/optimization/csminwel1.m matlab/bvar_density.m
  matlab/bvar_toolbox.m matlab/partial_information/PI_gensys.m matlab/qzswitch.m
  matlab/qzdiv.m
 Copyright: 1993-2009 Christopher Sims
            2006-2013 Dynare Team
 License: GPL-3+
 
-Files: matlab/cmaes.m
+Files: matlab/optimization/cmaes.m
 Copyright: 2001-2012 Nikolaus Hansen
            2012 Dynare Team
 License: GPL-3+
 
+Files: matlab/optimization/solvopt.m
+Copyright: 1997-2008 Alexei Kuntsevich and Franz Kappel 
+           2008-2015 Giovanni Lombardo
+           2015 Dynare Team
+License: GPL-3+
+
+Files: matlab/optimization/simulated_annealing.m
+Copyright: 1995 E.G.Tsionas 
+           1995-2002 Thomas Werner 
+           2002-2015 Giovanni Lombardo
+           2015 Dynare Team
+License: GPL-3+
+
 Files: matlab/endogenous_prior.m
 Copyright: 2011 Lawrence J. Christiano, Mathias Trabandt and Karl Walentin
            2013 Dynare Team
@@ -63,7 +76,7 @@ Copyright: 2008-2012 VZLU Prague, a.s.
            2014 Dynare Team
 License: GPL-3+
 
-Files: matlab/simpsa.m matlab/simpsaget.m matlab/simpsaset.m
+Files: matlab/optimization/simpsa.m matlab/optimization/simpsaget.m matlab/optimization/simpsaset.m
 Copyright: 2005 Henning Schmidt, FCC, henning@fcc.chalmers.se
            2006 Brecht Donckels, BIOMATH, brecht.donckels@ugent.be
            2013 Dynare Team
@@ -126,7 +139,7 @@ License: permissive
  distribute this software.
 
 Files: doc/dynare.texi doc/*.tex doc/*.svg doc/*.dia doc/*.pdf doc/*.bib
-Copyright: 1996-2014 Dynare Team
+Copyright: 1996-2015 Dynare Team
 License: GFDL-NIV-1.3+
 
 Files: doc/userguide/*.tex doc/userguide/*.bib doc/userguide/*.pdf
diff --git a/m4/ax_matlab_version.m4 b/m4/ax_matlab_version.m4
index c7a1d5f3ea3ed92d5d2fcad812abec3945b74691..211da84778add1c26c72e6b4abc774c244937ad8 100644
--- a/m4/ax_matlab_version.m4
+++ b/m4/ax_matlab_version.m4
@@ -1,4 +1,4 @@
-dnl Copyright (C) 2009-2014 Dynare Team
+dnl Copyright (C) 2009-2015 Dynare Team
 dnl
 dnl This file is part of Dynare.
 dnl
@@ -22,6 +22,9 @@ AC_REQUIRE([AX_MATLAB])
 AC_MSG_CHECKING([for MATLAB version])
 if test "x$MATLAB_VERSION" != "x"; then
   case $MATLAB_VERSION in
+    *2015a | *2015A)
+      MATLAB_VERSION="8.5"
+      ;;
     *2014b | *2014B)
       MATLAB_VERSION="8.4"
       ;;
diff --git a/matlab/DsgeSmoother.m b/matlab/DsgeSmoother.m
index 309f2d9ab89241b93733b58e5c3224cd6b75a38a..a692965f1b7edc62e3ce32bd871e9c02a68990ef 100644
--- a/matlab/DsgeSmoother.m
+++ b/matlab/DsgeSmoother.m
@@ -17,18 +17,20 @@ function [alphahat,etahat,epsilonhat,ahat,SteadyState,trend_coeff,aK,T,R,P,PK,de
 %   o trend_coeff   [double]  (n*1) vector, parameters specifying the slope of the trend associated to each observed variable.
 %   o aK            [double]  (K,n,T+K) array, k (k=1,...,K) steps ahead filtered (endogenous) variables.
 %   o T and R       [double]  Matrices defining the state equation (T is the (m*m) transition matrix).
-%    P:             3D array of one-step ahead forecast error variance
-%                   matrices
-%    PK:            4D array of k-step ahead forecast error variance
-%                   matrices (meaningless for periods 1:d)
-%    
+%   o P:            3D array of one-step ahead forecast error variance
+%                       matrices
+%   o PK:           4D array of k-step ahead forecast error variance
+%                       matrices (meaningless for periods 1:d)
+%   o decomp        4D array of shock decomposition of k-step ahead
+%                       filtered variables
+% 
 % ALGORITHM 
 %   Diffuse Kalman filter (Durbin and Koopman)       
 %
 % SPECIAL REQUIREMENTS
 %   None
 
-% Copyright (C) 2006-2012 Dynare Team
+% Copyright (C) 2006-2014 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -67,9 +69,16 @@ M_ = set_all_parameters(xparam1,estim_params_,M_);
 %------------------------------------------------------------------------------
 % 2. call model setup & reduction program
 %------------------------------------------------------------------------------
+oldoo.restrict_var_list = oo_.dr.restrict_var_list; 
+oldoo.restrict_columns = oo_.dr.restrict_columns;
 oo_.dr.restrict_var_list = bayestopt_.smoother_var_list;
 oo_.dr.restrict_columns = bayestopt_.smoother_restrict_columns;
+
 [T,R,SteadyState,info,M_,options_,oo_] = dynare_resolve(M_,options_,oo_);
+
+oo_.dr.restrict_var_list = oldoo.restrict_var_list;
+oo_.dr.restrict_columns = oldoo.restrict_columns;
+
 bayestopt_.mf = bayestopt_.smoother_mf;
 if options_.noconstant
     constant = zeros(vobs,1);
@@ -172,6 +181,7 @@ elseif options_.lik_init == 5            % Old diffuse Kalman filter only for th
     Pinf  = [];
 end
 kalman_tol = options_.kalman_tol;
+diffuse_kalman_tol = options_.diffuse_kalman_tol;
 riccati_tol = options_.riccati_tol;
 data1 = Y-trend;
 % -----------------------------------------------------------------------------
@@ -197,7 +207,7 @@ if kalman_algo == 1 || kalman_algo == 3
     [alphahat,epsilonhat,etahat,ahat,P,aK,PK,decomp] = missing_DiffuseKalmanSmootherH1_Z(ST, ...
                                                       Z,R1,Q,H,Pinf,Pstar, ...
                                                       data1,vobs,np,smpl,data_index, ...
-                                                      options_.nk,kalman_tol,options_.filter_decomposition);
+                                                      options_.nk,kalman_tol,diffuse_kalman_tol,options_.filter_decomposition);
     if isinf(alphahat)
         if kalman_algo == 1
             kalman_algo = 2;
@@ -224,7 +234,7 @@ if kalman_algo == 2 || kalman_algo == 4
     [alphahat,epsilonhat,etahat,ahat,P,aK,PK,decomp] = missing_DiffuseKalmanSmootherH3_Z(ST, ...
                                                       Z,R1,Q,diag(H), ...
                                                       Pinf,Pstar,data1,vobs,np,smpl,data_index, ...
-                                                      options_.nk,kalman_tol,...
+                                                      options_.nk,kalman_tol,diffuse_kalman_tol, ...
                                                       options_.filter_decomposition);
 end
 
diff --git a/matlab/McMCDiagnostics.m b/matlab/McMCDiagnostics.m
index ed719034cf5b59be6e972e0c883e5e9c69ceeebc..ce85ecbf3cc5e8e38866d46c357045932373be3c 100644
--- a/matlab/McMCDiagnostics.m
+++ b/matlab/McMCDiagnostics.m
@@ -86,14 +86,14 @@ if nblck == 1 % Brooks and Gelman tests need more than one block
         fprintf('\nCONVERGENCE DIAGNOSTICS: Invalid option for geweke_interval. Using the default of [0.2 0.5].\n')
         options_.convergence.geweke.geweke_interval=[0.2 0.5];
     end
-    first_obs_begin_sample = max(1,ceil(options_.mh_drop*options_.mh_replic));
-    last_obs_begin_sample = first_obs_begin_sample+round(options_.convergence.geweke.geweke_interval(1)*options_.mh_replic*(1-options_.mh_drop));
-    first_obs_end_sample = first_obs_begin_sample+round(options_.convergence.geweke.geweke_interval(2)*options_.mh_replic*(1-options_.mh_drop));
+    first_obs_begin_sample = max(1,ceil(options_.mh_drop*NumberOfDraws));
+    last_obs_begin_sample = first_obs_begin_sample+round(options_.convergence.geweke.geweke_interval(1)*NumberOfDraws*(1-options_.mh_drop));
+    first_obs_end_sample = first_obs_begin_sample+round(options_.convergence.geweke.geweke_interval(2)*NumberOfDraws*(1-options_.mh_drop));
     param_name=[];
     for jj=1:npar
         param_name = strvcat(param_name,get_the_name(jj,options_.TeX,M_,estim_params_,options_));
     end
-    fprintf('\nGeweke (1992) Convergence Tests, based on means of draws %d to %d vs %d to %d.\n',first_obs_begin_sample,last_obs_begin_sample,first_obs_end_sample,options_.mh_replic);
+    fprintf('\nGeweke (1992) Convergence Tests, based on means of draws %d to %d vs %d to %d.\n',first_obs_begin_sample,last_obs_begin_sample,first_obs_end_sample,NumberOfDraws);
     fprintf('p-values are for Chi2-test for equality of means.\n');    
     Geweke_header={'Parameter', 'Post. Mean', 'Post. Std', 'p-val No Taper'};
     print_string=['%',num2str(size(param_name,2)+3),'s \t %12.3f \t %12.3f \t %12.3f'];
diff --git a/matlab/PosteriorFilterSmootherAndForecast.m b/matlab/PosteriorFilterSmootherAndForecast.m
deleted file mode 100644
index b636565633d0c722330bd42bf132107d1eb8969a..0000000000000000000000000000000000000000
--- a/matlab/PosteriorFilterSmootherAndForecast.m
+++ /dev/null
@@ -1,275 +0,0 @@
-function PosteriorFilterSmootherAndForecast(Y,gend, type,data_index)
-
-% function PosteriorFilterSmootherAndForecast(Y,gend, type)
-% Computes posterior filter smoother and forecasts
-%
-% INPUTS
-%    Y:      data
-%    gend:   number of observations
-%    type:   posterior
-%            prior
-%            gsa
-%
-% OUTPUTS
-%    none
-%
-% SPECIAL REQUIREMENTS
-%    none
-
-% Copyright (C) 2005-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_ estim_params_ oo_ M_ bayestopt_
-
-nvx  = estim_params_.nvx;
-nvn  = estim_params_.nvn;
-ncx  = estim_params_.ncx;
-ncn  = estim_params_.ncn;
-np   = estim_params_.np ;
-npar = nvx+nvn+ncx+ncn+np;
-offset = npar-np;
-naK = length(options_.filter_step_ahead);
-
-MaxNumberOfPlotPerFigure = 4;% The square root must be an integer!
-MaxNumberOfBytes=options_.MaxNumberOfBytes;
-endo_nbr=M_.endo_nbr;
-exo_nbr=M_.exo_nbr;
-nvobs     = length(options_.varobs);
-nn = sqrt(MaxNumberOfPlotPerFigure);
-iendo = 1:endo_nbr;
-i_last_obs = gend+(1-M_.maximum_endo_lag:0);
-horizon = options_.forecast;
-maxlag = M_.maximum_endo_lag;
-
-CheckPath('Plots/',M_.dname);
-MetropolisFolder = CheckPath('metropolis',M_.dname);
-ModelName = M_.fname;
-BaseName = [MetropolisFolder filesep Model_name];
-
-load_last_mh_history_file(MetropolisFolder,ModelName);
-
-FirstMhFile = record.KeepedDraws.FirstMhFile;
-FirstLine = record.KeepedDraws.FirstLine;
-TotalNumberOfMhFiles = sum(record.MhDraws(:,2)); LastMhFile = TotalNumberOfMhFiles;
-TotalNumberOfMhDraws = sum(record.MhDraws(:,1));
-NumberOfDraws = TotalNumberOfMhDraws-floor(options_.mh_drop*TotalNumberOfMhDraws);
-
-B = min(1200, round(0.25*NumberOfDraws));
-B = 200;
-
-MAX_nruns = min(B,ceil(options_.MaxNumberOfBytes/(npar+2)/8));
-MAX_nsmoo = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*gend)/8));
-MAX_ninno = min(B,ceil(MaxNumberOfBytes/(exo_nbr*gend)/8));
-MAX_nerro = min(B,ceil(MaxNumberOfBytes/(length(options_.varobs)*gend)/8));
-if naK
-    MAX_naK   = min(B,ceil(MaxNumberOfBytes/(length(options_.varobs)* ...
-                                             length(options_.filter_step_ahead)*gend)/8));
-end
-if horizon
-    MAX_nforc1 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/8));
-    MAX_nforc2 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/ ...
-                            8));
-    IdObs    = bayestopt_.mfys;
-
-end
-
-varlist = options_.varlist;
-if isempty(varlist)
-    varlist = M_.endo_names;
-    SelecVariables = transpose(1:M_.endo_nbr);
-    nvar = M_.endo_nbr;
-else
-    nvar = size(varlist,1);
-    SelecVariables = [];
-    for i=1:nvar
-        if ~isempty(strmatch(varlist(i,:),M_.endo_names,'exact'))
-            SelecVariables = [SelecVariables;strmatch(varlist(i,:),M_.endo_names,'exact')];
-        end
-    end
-end
-
-irun1 = 1;
-irun2 = 1;
-irun3 = 1;
-irun4 = 1;
-irun5 = 1;
-irun6 = 1;
-irun7 = 1;
-ifil1 = 0;
-ifil2 = 0;
-ifil3 = 0;
-ifil4 = 0;
-ifil5 = 0;
-ifil6 = 0;
-ifil7 = 0;
-
-h = waitbar(0,'Bayesian smoother...');
-
-stock_param = zeros(MAX_nruns, npar);
-stock_logpo = zeros(MAX_nruns,1);
-stock_ys = zeros(MAX_nruns,endo_nbr);
-if options_.smoother
-    stock_smooth = zeros(endo_nbr,gend,MAX_nsmoo);
-    stock_innov  = zeros(exo_nbr,gend,B);
-    stock_error = zeros(nvobs,gend,MAX_nerro);
-end
-if options_.filter_step_ahead
-    stock_filter = zeros(naK,endo_nbr,gend+options_.filter_step_ahead(end),MAX_naK);
-end
-if options_.forecast
-    stock_forcst_mean = zeros(endo_nbr,horizon+maxlag,MAX_nforc1);
-    stock_forcst_total = zeros(endo_nbr,horizon+maxlag,MAX_nforc2);
-end
-
-for b=1:B
-    [deep, logpo] = GetOneDraw(type);
-    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);
-
-    if options_.loglinear
-        stock_smooth(dr.order_var,:,irun1) = alphahat(1:endo_nbr,:)+ ...
-            repmat(log(dr.ys(dr.order_var)),1,gend);
-    else
-        stock_smooth(dr.order_var,:,irun1) = alphahat(1:endo_nbr,:)+ ...
-            repmat(dr.ys(dr.order_var),1,gend);
-    end
-    if nvx
-        stock_innov(:,:,irun2)  = etahat;
-    end
-    if nvn
-        stock_error(:,:,irun3)  = epsilonhat;
-    end
-    if naK
-        stock_filter(:,dr.order_var,:,irun4) = aK(options_.filter_step_ahead,1:endo_nbr,:);
-    end
-    stock_param(irun5,:) = deep;
-    stock_logpo(irun5,1) = logpo;
-    stock_ys(irun5,:) = SteadyState';
-
-    if horizon
-        yyyy = alphahat(iendo,i_last_obs);
-        yf = forcst2a(yyyy,dr,zeros(horizon,exo_nbr));
-        if options_.prefilter == 1
-            yf(:,IdObs) = yf(:,IdObs)+repmat(bayestopt_.mean_varobs', ...
-                                             horizon+maxlag,1);
-        end
-        yf(:,IdObs) = yf(:,IdObs)+(gend+[1-maxlag:horizon]')*trend_coeff';
-        if options_.loglinear
-            yf = yf+repmat(log(SteadyState'),horizon+maxlag,1);
-        else
-            yf = yf+repmat(SteadyState',horizon+maxlag,1);
-        end
-        yf1 = forcst2(yyyy,horizon,dr,1);
-        if options_.prefilter
-            yf1(:,IdObs,:) = yf1(:,IdObs,:)+ ...
-                repmat(bayestopt_.mean_varobs',[horizon+maxlag,1,1]);
-        end
-        yf1(:,IdObs,:) = yf1(:,IdObs,:)+repmat((gend+[1-maxlag:horizon]')* ...
-                                               trend_coeff',[1,1,1]);
-        if options_.loglinear
-            yf1 = yf1 + repmat(log(SteadyState'),[horizon+maxlag,1,1]);
-        else
-            yf1 = yf1 + repmat(SteadyState',[horizon+maxlag,1,1]);
-        end
-
-        stock_forcst_mean(:,:,irun6) = yf';
-        stock_forcst_total(:,:,irun7) = yf1';
-    end
-
-    irun1 = irun1 + 1;
-    irun2 = irun2 + 1;
-    irun3 = irun3 + 1;
-    irun4 = irun4 + 1;
-    irun5 = irun5 + 1;
-    irun6 = irun6 + 1;
-    irun7 = irun7 + 1;
-
-    if irun1 > MAX_nsmoo || b == B
-        stock = stock_smooth(:,:,1:irun1-1);
-        ifil1 = ifil1 + 1;
-        save([BaseName '_smooth' int2str(ifil1) '.mat'],'stock');
-        irun1 = 1;
-    end
-
-    if nvx && (irun2 > MAX_ninno || b == B)
-        stock = stock_innov(:,:,1:irun2-1);
-        ifil2 = ifil2 + 1;
-        save([BaseName '_inno' int2str(ifil2) '.mat'],'stock');
-        irun2 = 1;
-    end
-
-    if nvn && (irun3 > MAX_error || b == B)
-        stock = stock_error(:,:,1:irun3-1);
-        ifil3 = ifil3 + 1;
-        save([BaseName '_error' int2str(ifil3) '.mat'],'stock');
-        irun3 = 1;
-    end
-
-    if naK && (irun4 > MAX_naK || b == B)
-        stock = stock_filter(:,:,:,1:irun4-1);
-        ifil4 = ifil4 + 1;
-        save([BaseName '_filter' int2str(ifil4) '.mat'],'stock');
-        irun4 = 1;
-    end
-
-    if irun5 > MAX_nruns || b == B
-        stock = stock_param(1:irun5-1,:);
-        ifil5 = ifil5 + 1;
-        save([BaseName '_param' int2str(ifil5) '.mat'],'stock','stock_logpo','stock_ys');
-        irun5 = 1;
-    end
-
-    if horizon && (irun6 > MAX_nforc1 || b == B)
-        stock = stock_forcst_mean(:,:,1:irun6-1);
-        ifil6 = ifil6 + 1;
-        save([BaseName '_forc_mean' int2str(ifil6) '.mat'],'stock');
-        irun6 = 1;
-    end
-
-    if horizon && (irun7 > MAX_nforc2 ||  b == B)
-        stock = stock_forcst_total(:,:,1:irun7-1);
-        ifil7 = ifil7 + 1;
-        save([BaseName '_forc_total' int2str(ifil7) '.mat'],'stock');
-        irun7 = 1;
-    end
-
-    waitbar(b/B,h);
-
-end
-close(h)
-
-% ??????
-stock_gend=gend;
-stock_data=Y;
-save([BaseName '_data.mat'],'stock_gend','stock_data');
-
-if options_.smoother
-    pm3(endo_nbr,gend,ifil1,B,'Smoothed variables',...
-        M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,...
-        'names2','smooth',MetropolisFolder,'_smooth')
-end
-
-if options_.forecast
-    pm3(endo_nbr,horizon+maxlag,ifil6,B,'Forecasted variables (mean)',...
-        M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,...
-        'names2','smooth',MetropolisFolder,'_forc_mean')
-    pm3(endo_nbr,horizon+maxlag,ifil6,B,'Forecasted variables (total)',...
-        M_.endo_names(SelecVariables),M_.endo_names,'tit_tex',M_.endo_names,...
-        'names2','smooth',MetropolisFolder,'_forc_total')
-end
diff --git a/matlab/PosteriorIRF.m b/matlab/PosteriorIRF.m
index fc1c3bcf58ce1b158458f244062f46433da3188f..47da7e86fcd5a421ef5764d68afae00368301a1f 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-2013 Dynare Team
+% Copyright (C) 2006-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -93,8 +93,15 @@ elseif strcmpi(type,'gsa')
 else
     MhDirectoryName = CheckPath('prior',M_.dname);
 end
-delete([MhDirectoryName filesep M_.fname '_IRF_DSGEs*.mat']);
-delete([MhDirectoryName filesep M_.fname '_IRF_BVARDSGEs*.mat']);
+
+%delete old stale files before creating new ones
+delete_stale_file([MhDirectoryName filesep M_.fname '_IRF_DSGEs*.mat']);
+delete_stale_file([MhDirectoryName filesep M_.fname '_IRF_BVARDSGEs*.mat']);
+delete_stale_file([MhDirectoryName filesep M_.fname '_irf_dsge*.mat']);
+delete_stale_file([MhDirectoryName filesep M_.fname '_irf_bvardsge*.mat']);
+delete_stale_file([MhDirectoryName filesep M_.fname '_param_irf*.mat']);
+
+
 if strcmpi(type,'posterior')
     B = options_.sub_draws;
     options_.B = B;
@@ -112,16 +119,7 @@ else% type = 'prior'
     B = options_.prior_draws;
     options_.B = B;
 end
-try
-    delete([MhDirectoryName filesep M_.fname '_irf_dsge*.mat'])
-catch
-    disp('No _IRFs (dsge) files to be deleted!')
-end
-try
-    delete([MhDirectoryName filesep M_.fname '_irf_bvardsge*.mat'])
-catch
-    disp('No _IRFs (bvar-dsge) files to be deleted!')
-end
+
 irun = 0;
 IRUN = 0;
 irun2 = 0;
diff --git a/matlab/PosteriorIRF_core2.m b/matlab/PosteriorIRF_core2.m
index c20702eb5f4658996bb7aa9a0690a6e49ba7724d..1fef8cdff4472e6795ec5b603c7214f4d2aa751e 100644
--- a/matlab/PosteriorIRF_core2.m
+++ b/matlab/PosteriorIRF_core2.m
@@ -1,17 +1,28 @@
-function myoutput=PosteriorIRF_core2(myinputs,fpar,npar,whoiam, ThisMatlab)
+function myoutput=PosteriorIRF_core2(myinputs,fpar,npar,whoiam,ThisMatlab)
+% function myoutput=PosteriorIRF_core2(myinputs,fpar,npar,whoiam, ThisMatlab)
 % Generates the Posterior IRFs plot from the IRFs generated in
 % PosteriorIRF_core1
+% 
 % PARALLEL CONTEXT
-% Perform in parallel execution a portion of the PosteriorIRF.m code.
-% See also the comment in random_walk_metropolis_hastings_core.m funtion.
+% Performs in parallel execution a portion of the PosteriorIRF.m code.
+% For more information, see the comment in random_walk_metropolis_hastings_core.m 
+% function.
 %
 % INPUTS
-%   See the comment in random_walk_metropolis_hastings_core.m funtion.
+%   o myimput            [struc]     The mandatory variables for local/remote
+%                                    parallel computing obtained from random_walk_metropolis_hastings.m
+%                                    function.
+%   o fblck and nblck    [integer]   The Metropolis-Hastings chains.
+%   o whoiam             [integer]   In concurrent programming a modality to refer to the differents thread running in parallel is needed.
+%                                    The integer whoaim is the integer that
+%                                    allows us to distinguish between them. Then it is the index number of this CPU among all CPUs in the
+%                                    cluster.
+%   o ThisMatlab         [integer]   Allows us to distinguish between the
+%                                    'main' matlab, the slave matlab worker, local matlab, remote matlab,
+%                                     ... Then it is the index number of this slave machine in the cluster.
 %
 % OUTPUTS
-% o myoutput  [struc]
-%  Contained:
-%  OutputFileName (i.e. the figures without the file .txt).
+% o myoutput             [struc]    Contained: OutputFileName (i.e. the figures without the file .txt).
 %
 % ALGORITHM
 %   Portion of PosteriorIRF.m function code. Specifically the last 'for' cycle.
@@ -19,7 +30,7 @@ function myoutput=PosteriorIRF_core2(myinputs,fpar,npar,whoiam, ThisMatlab)
 % SPECIAL REQUIREMENTS.
 %   None.
 %
-% Copyright (C) 2006-2013 Dynare Team
+% Copyright (C) 2006-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -100,13 +111,9 @@ for i=fpar:npar,
             set(0,'CurrentFigure',hh)
             subplot(nn,nn,subplotnum);
             if ~MAX_nirfs_dsgevar
-                h1 = area(1:options_.irf,HPDIRF(:,2,j,i));
-                set(h1,'FaceColor',[.9 .9 .9]);
-                set(h1,'BaseValue',min(HPDIRF(:,1,j,i)));
+                h1 = area(1:options_.irf,HPDIRF(:,2,j,i),'FaceColor',[.9 .9 .9],'BaseValue',min(HPDIRF(:,1,j,i))); %grey below HPDIsup and minimum of HPDIinf
                 hold on
-                h2 = area(1:options_.irf,HPDIRF(:,1,j,i),'FaceColor',[1 1 1],'BaseValue',min(HPDIRF(:,1,j,i)));
-                set(h2,'FaceColor',[1 1 1]);
-                set(h2,'BaseValue',min(HPDIRF(:,1,j,i)));
+                h2 = area(1:options_.irf,HPDIRF(:,1,j,i),'FaceColor',[1 1 1],'BaseValue',min(HPDIRF(:,1,j,i))); %white below HPDIinf and minimum of HPDIinf
                 plot(1:options_.irf,MeanIRF(:,j,i),'-k','linewidth',3)
                 % plot([1 options_.irf],[0 0],'-r','linewidth',0.5);
                 box on
@@ -114,18 +121,14 @@ for i=fpar:npar,
                 xlim([1 options_.irf]);
                 hold off
             else
-                h1 = area(1:options_.irf,HPDIRF(:,2,j,i));
-                set(h1,'FaceColor',[.9 .9 .9]);
-                set(h1,'BaseValue',min([min(HPDIRF(:,1,j,i)),min(HPDIRFdsgevar(:,1,j,i))]));
-                hold on;
-                h2 = area(1:options_.irf,HPDIRF(:,1,j,i));
-                set(h2,'FaceColor',[1 1 1]);
-                set(h2,'BaseValue',min([min(HPDIRF(:,1,j,i)),min(HPDIRFdsgevar(:,1,j,i))]));
+                h1 = area(1:options_.irf,HPDIRF(:,2,j,i),'FaceColor',[.9 .9 .9],'BaseValue',min([min(HPDIRF(:,1,j,i)),min(HPDIRFdsgevar(:,1,j,i))])); %grey below HPDIsup and minimum of HPDIinf and HPDIRFdsgevar
+                hold on
+                h2 = area(1:options_.irf,HPDIRF(:,1,j,i),'FaceColor',[1 1 1],'BaseValue',min([min(HPDIRF(:,1,j,i)),min(HPDIRFdsgevar(:,1,j,i))])); %white below HPDIinf and minimum of  HPDIinf and HPDIRFdsgevar
                 plot(1:options_.irf,MeanIRF(:,j,i),'-k','linewidth',3)
-                % plot([1 options_.irf],[0 0],'-r','linewidth',0.5);
                 plot(1:options_.irf,MeanIRFdsgevar(:,j,i),'--k','linewidth',2)
                 plot(1:options_.irf,HPDIRFdsgevar(:,1,j,i),'--k','linewidth',1)
                 plot(1:options_.irf,HPDIRFdsgevar(:,2,j,i),'--k','linewidth',1)
+                % plot([1 options_.irf],[0 0],'-r','linewidth',0.5);
                 box on
                 axis tight
                 xlim([1 options_.irf]);
@@ -156,6 +159,4 @@ for i=fpar:npar,
     end
 end% loop over exo_var
 
-
-
 myoutput.OutputFileName = OutputFileName;
diff --git a/matlab/add_path_to_mex_files.m b/matlab/add_path_to_mex_files.m
new file mode 100644
index 0000000000000000000000000000000000000000..70f9fa7f55914e8751c2ce6b5b08d4e691fabdfe
--- /dev/null
+++ b/matlab/add_path_to_mex_files.m
@@ -0,0 +1,89 @@
+function mexpath = add_path_to_mex_files(dynareroot, modifypath)
+    
+% Copyright (C) 2015 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+if nargin<2
+    modifypath = true;
+end
+    
+if isoctave
+    mexpath = {[dynareroot '../mex/octave/']};
+    if modifypath
+        addpath(mexpath{1});
+    end
+else
+    % Add win32 specific paths for Dynare Windows package
+    if strcmp(computer, 'PCWIN')
+        tmp = [dynareroot '../mex/matlab/win32-7.5-8.5/'];
+        if exist(tmp, 'dir')
+            mexpath = tmp;
+            if modifypath
+                addpath(mexpath);
+            end
+        end
+    end
+    % Add win64 specific paths for Dynare Windows package
+    if strcmp(computer, 'PCWIN64')
+        if matlab_ver_less_than('7.8')
+            tmp = [dynareroot '../mex/matlab/win64-7.5-7.7/'];
+            if exist(tmp, 'dir')
+                mexpath = tmp;
+                if modifypath
+                    addpath(mexpath);
+                end
+            end
+        else
+            tmp = [dynareroot '../mex/matlab/win64-7.8-8.5/'];
+            if exist(tmp, 'dir')
+                mexpath = tmp;
+                if modifypath
+                    addpath(mexpath);
+                end
+            end
+        end
+    end
+    % Add OS X 32bits specific paths for Dynare Mac package
+    if strcmp(computer, 'MACI')
+        tmp = [dynareroot '../mex/matlab/osx32-7.5-7.11/'];
+        if exist(tmp, 'dir')
+            mexpath = tmp;
+            if modifypath && exist(mexpath, 'dir')
+                addpath(mexpath);
+            end
+        end
+    end
+    % Add OS X 64bits specific paths for Dynare Mac package
+    if strcmp(computer, 'MACI64')
+        tmp = [dynareroot '../mex/matlab/osx64/'];
+        if exist(tmp, 'dir')
+            mexpath = tmp;
+            if modifypath && exist(mexpath, 'dir')
+                addpath(mexpath);
+            end
+        end
+    end
+    % Add generic MATLAB path (with higher priority than the previous ones)
+    if exist('mexpath')
+        mexpath = { mexpath, [dynareroot '../mex/matlab/'] };
+    else
+        mexpath = { [dynareroot '../mex/matlab/'] };
+    end
+    if modifypath
+        addpath([dynareroot '../mex/matlab/']);
+    end
+end
\ No newline at end of file
diff --git a/matlab/bfgsi1.m b/matlab/bfgsi1.m
index 48d58562daf11bbad5d65cf6fa3a424df879f789..c3b87ca49f8d550649da7047c39be84e972c65a3 100644
--- a/matlab/bfgsi1.m
+++ b/matlab/bfgsi1.m
@@ -1,13 +1,20 @@
 function H = bfgsi1(H0,dg,dx)
 % H = bfgsi1(H0,dg,dx)
-% dg is previous change in gradient; dx is previous change in x;
+% Update Inverse Hessian matrix
+% 
+% Inputs:
+%   H0  [npar by npar]  initial inverse Hessian matrix
+%   dg  [npar by 1]     previous change in gradient
+%   dx  [npar by 1]     previous change in x;
+% 
 % 6/8/93 version that updates inverse hessian instead of hessian
 % itself.
-
+% 
 % Original file downloaded from:
 % http://sims.princeton.edu/yftp/optimize/mfiles/bfgsi.m
-
+% 
 % Copyright (C) 1993-2009 Christopher Sims
+% Copyright (C) 2009-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -41,4 +48,4 @@ else
     disp(['|H*dg| = ' num2str(Hdg'*Hdg)])
     H=H0;
 end
-save H.dat H
+save('H.dat','H')
diff --git a/matlab/check_matlab_path.m b/matlab/check_matlab_path.m
new file mode 100644
index 0000000000000000000000000000000000000000..ccd9d63087a35905e5893ffd92bfb7e92793ebb5
--- /dev/null
+++ b/matlab/check_matlab_path.m
@@ -0,0 +1,150 @@
+function check_matlab_path(change_path_flag)
+    
+% Copyright (C) 2015 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+if ~nargin || isempty(change_path_flag)
+    change_path_flag = true;
+end
+
+% Get path to dynare/matlab folder.
+DYNARE_PATH = strrep(which('dynare'),'dynare.m','');
+
+if isempty(DYNARE_PATH)
+    % Nothing to do here (this case should not happen)
+    disp('dynare.m is not in the Matlab''s path.')
+    return
+else
+    % Removes trailing slash.
+    DYNARE_PATH = DYNARE_PATH(1:end-1);
+end
+
+% Get matlab path
+MATLAB_PATH = path();
+
+% Position of DYNARE_PATH in MATLAB_PATH
+idDYNARE = strfind(MATLAB_PATH,DYNARE_PATH);
+
+if isempty(idDYNARE)
+    disp('dynare.m is not in the Matlab''s path.')
+    return
+else
+    if isequal(length(idDYNARE),1)
+        if isequal(idDYNARE, 1)
+            % Dynare is on top of matlab's path! Nothing to do here...
+            return
+        else
+            str0 = sprintf('Dynare is not on top of matlab''s path!');
+            % Check that this will not create a problem
+            MATLAB_PATH_ = path2cell(MATLAB_PATH);
+            DYNARE_ROUTINES = getallroutinenames(DYNARE_PATH, getalldirectories(DYNARE_PATH));
+            MATLAB_ROUTINES = {};
+            for i=1:position(idDYNARE, MATLAB_PATH)
+                TMP_MATLAB_ROUTINES = getallroutinenames(MATLAB_PATH_{i});
+                MATLAB_ROUTINES = { MATLAB_ROUTINES{:}  TMP_MATLAB_ROUTINES{:} };
+            end
+            COMMON_ROUTINES = intersect(MATLAB_ROUTINES, DYNARE_ROUTINES);
+            if ~isempty(COMMON_ROUTINES)
+                warning off backtrace
+                skipline()
+                if length(COMMON_ROUTINES)==1
+                    warning(sprintf('%s This can cause problems because the Dynare version of %s will be overriden.', str0, COMMON_ROUTINES{1}));
+                else
+                    str1 = repmat('%s, ', 1, length(COMMON_ROUTINES)-1);
+                    str2 = 'and %s ';
+                    str3 = sprintf(['%s This can cause problems because the Dynare versions of ' str1, str2, 'will be overriden.'], str0, COMMON_ROUTINES{:});
+                    warning(str3);
+                end
+                if change_path_flag
+                    skipline()
+                    msg = sprintf('I put %s on top of your matlab''s path. Note that this is a', DYNARE_PATH);
+                    msg = sprintf(' %s a temporary change (ie will not affect future matlab''s session).', msg);
+                    msg = sprintf(' %s If the ordering was intentional, ie if you really want to override the routines distributed with Dynare,', msg);
+                    msg = sprintf(' %s you can change this behaviour using option nopathchange (see the reference manual).', msg);
+                    warning(msg);
+                    skipline()
+                    rmpath(DYNARE_PATH)
+                    addpath(DYNARE_PATH)    
+                end
+                warning on backtrace
+            end
+        end
+    else
+        % Check that the user did not put all the subfolders in the path.
+        % => If DYNARE_PATH/qz is in the path while mjdgges dll is available
+        % it most likely means that user wrongly put all subfolders in the 
+        % matlab's path!
+        mexpath = add_path_to_mex_files([DYNARE_PATH filesep], false);
+        MATLAB_PATH = path2cell(MATLAB_PATH);
+        for i=1:length(mexpath)
+            if exist([mexpath{i} filesep 'mjdgges.' mexext],'file') && ismember([DYNARE_PATH filesep 'qz'],MATLAB_PATH)
+                msg = sprintf(['You  put all the dynare/matlab subfolders in matlab''s path! Only ' ...
+                               'the dynare/matlab folder (without subfolders)\nshould be in the ' ...
+                               'path, Dynare will automatically add any required subfolders in the ' ...
+                               'path.']);
+                error(msg)
+            end
+        end
+    end
+end
+
+function q = path2cell(p)
+    % Converts the output of path() to a cell 
+    s = strfind(p,pathsep);
+    n = length(s)+1;
+    q = cell(n,1);
+    q(1) = {p(1:s(1)-1)};
+    q(n) = {p(s(end)+1:end)};
+    for i=2:n-1
+        q(i) = {p(s(i-1)+1:s(i)-1)}; 
+    end
+    
+function flist = getallroutinenames(p, excludedsubfolders)
+    if nargin<2
+        excludedsubfolders = {};
+    end
+    dd = dir(p);
+    flist = {};
+    for f=1:length(dd)
+        if ~(isequal(dd(f).name,'.') || isequal(dd(f).name,'..'))
+            if dd(f).isdir
+                if ~ismember(dd(f).name, excludedsubfolders)
+                    r = getallroutinenames([ p filesep dd(f).name]);
+                    flist = { flist{:} r{:} };
+                end
+            else
+                % Filter out files without m extension.
+                if isequal(dd(f).name(end-1:end),'.m')
+                    flist{length(flist)+1} = [dd(f).name];
+                end
+            end
+        end
+    end
+
+function dlist = getalldirectories(p)
+    dd = dir(p);
+    dlist = {};
+    for f = 1:length(dd)
+        if ~(isequal(dd(f).name,'.') || isequal(dd(f).name,'..'))
+            if dd(f).isdir
+                dlist{length(dlist)+1} = [dd(f).name];
+            end
+        end
+    end
+    
+function n = position(i, currentpath)
+    n = length(strfind(currentpath(1:i), pathsep));
\ No newline at end of file
diff --git a/matlab/reports/@vspace/write.m b/matlab/check_valid_ver.m
similarity index 57%
rename from matlab/reports/@vspace/write.m
rename to matlab/check_valid_ver.m
index 4ea1d2e23568efbb4edcdddba9da41410372357b..9b61813ad640c80bb65b5bb04715d9ec69e20927 100644
--- a/matlab/reports/@vspace/write.m
+++ b/matlab/check_valid_ver.m
@@ -1,18 +1,17 @@
-function o = write(o, fid)
-%function o = write(o, fid)
-% Write a Vspace object
+function check_valid_ver(ver)
+%function check_valid_ver(ver)
+% Checks that ver is valid
 %
 % INPUTS
-%   o           [vspace]   vspace object
-%   fid         [integer]  file id
+%    ver    [string]    dynare version number
 %
 % OUTPUTS
-%   o           [vspace]   vspace object
+%    none
 %
 % SPECIAL REQUIREMENTS
-%   none
+%    none
 
-% Copyright (C) 2013-2014 Dynare Team
+% Copyright (C) 2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -29,16 +28,12 @@ function o = write(o, fid)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-assert(fid ~= -1);
-
-for i=1:o.number
-    fprintf(fid, ' \\par \\medskip ');
-end
-
-if o.hline > 0
-    fprintf(fid, '\\\\\n');
-    for i=1:o.hline
-        fprintf(fid, '\\midrule');
-    end
+test_ver = strsplit(ver, {'.', '-'});
+errmsg = 'check_valid_ver: the desired version must be in the proper format';
+assert (length(test_ver) == 3 && ...
+    ~isempty(str2double(test_ver{1})) && ...
+    ~isempty(str2double(test_ver{2})), errmsg);
+if isnan(str2double(test_ver{3}))
+    assert(strcmp(test_ver{3}, 'unstable'), errmsg);
 end
 end
\ No newline at end of file
diff --git a/matlab/cli/prior.m b/matlab/cli/prior.m
new file mode 100644
index 0000000000000000000000000000000000000000..d00e0555b5191228f1b5a4306905dffa6ececa4d
--- /dev/null
+++ b/matlab/cli/prior.m
@@ -0,0 +1,141 @@
+function varargout = prior(varargin)
+
+% Computes various prior statistics and display them in the command window.
+%
+% INPUTS
+%   'table', 'moments', 'optimize', 'simulate', 'plot'
+%
+% OUTPUTS
+%   none
+%
+% SPECIAL REQUIREMENTS
+%   none
+
+% Copyright (C) 2015 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+if isempty(varargin) || ( isequal(length(varargin), 1) && isequal(varargin{1},'help'))
+    skipline()
+    disp('Possible options are:')
+    disp(' + table       Prints a table describing the priors.')
+    disp(' + moments     Computes and displays moments of the endogenous variables at the prior mode.')
+    disp(' + optimize    Optimizes the prior density (starting from a random initial guess).')
+    disp(' + simulate    Computes the effective prior mass (using a Monte-Carlo).')
+    disp(' + plot        Plots the marginal prior densities.')
+    skipline()
+    return
+end
+
+global options_ M_ estim_params_ bayestopt_ oo_ objective_function_penalty_base
+
+donesomething = false;
+
+% Temporarly change qz_criterium option value
+changed_qz_criterium_flag  = 0;
+if isempty(options_.qz_criterium)
+    options_.qz_criterium = 1+1e-9;
+    changed_qz_criterium_flag  = 1;
+end
+
+M_.dname = M_.fname;
+
+% Temporarly set options_.order equal to one
+order = options_.order;
+options_.order = 1;
+
+[xparam1,estim_params_,bayestopt_,lb,ub,M_] = set_prior(estim_params_,M_,options_);
+
+if ismember('plot', varargin)
+    plot_priors(bayestopt_,M_,estim_params_,options_)
+    donesomething = true;
+end
+
+if ismember('table', varargin)
+    print_table_prior(lb, ub, options_, M_, bayestopt_, estim_params_);
+    donesomething = true;
+end
+
+if ismember('simulate', varargin) % Prior simulations (BK).
+    results = prior_sampler(0,M_,bayestopt_,options_,oo_,estim_params_);
+    % Display prior mass info
+    skipline(2)
+    disp(['Prior mass = ' num2str(results.prior.mass)])
+    disp(['BK indeterminacy share                = ' num2str(results.bk.indeterminacy_share)])
+    disp(['BK unstability share                  = ' num2str(results.bk.unstability_share)])
+    disp(['BK singularity share                  = ' num2str(results.bk.singularity_share)])
+    disp(['Complex jacobian share                = ' num2str(results.jacobian.problem_share)])
+    disp(['mjdgges crash share                   = ' num2str(results.dll.problem_share)])
+    disp(['Steady state problem share            = ' num2str(results.ss.problem_share)])
+    disp(['Complex steady state  share           = ' num2str(results.ss.complex_share)])
+    disp(['Analytical steady state problem share = ' num2str(results.ass.problem_share)])
+    skipline(2)
+    donesomething = true;
+end
+
+if ismember('optimize', varargin) % Prior optimization.
+    optimize_prior(options_, M_, oo_, bayestopt_, estim_params_);
+    donesomething = true;
+end
+
+if ismember('moments', varargin) % Prior simulations (2nd order moments).
+    % Set estimated parameters to the prior mode...
+    xparam1 = bayestopt_.p5;
+    % ... Except for uniform priors!
+    k = find(isnan(xparam1));
+    xparam1(k) = bayestopt_.p5(k);
+    % Update vector of parameters and covariance matrices
+    M_ = set_all_parameters(xparam1,estim_params_,M_);
+    % Check model.
+    check_model(M_);
+    % Compute state space representation of the model.
+    oo_.dr=set_state_space(oo_.dr, M_, options_);
+    % Solve model
+    [dr,info, M_ ,options_ , oo_] = resol(0, M_ , options_ ,oo_);
+    % Compute and display second order moments
+    disp_th_moments(oo_.dr,[]);
+    skipline(2)
+    donesomething = true;
+end
+
+if changed_qz_criterium_flag
+    options_.qz_criterium = [];
+end
+
+options_.order = order;
+
+if ~donesomething
+    error('prior: Unexpected arguments!')
+end
+
+function format_string = build_format_string(PriorStandardDeviation,LowerBound,UpperBound)
+format_string = ['%s & %s & %6.4f &'];
+if ~isnumeric(PriorStandardDeviation)
+    format_string = [ format_string , ' %s &'];
+else
+    format_string = [ format_string , ' %6.4f &'];
+end
+if ~isnumeric(LowerBound)
+    format_string = [ format_string , ' %s &'];
+else
+    format_string = [ format_string , ' %6.4f &'];
+end
+if ~isnumeric(UpperBound)
+    format_string = [ format_string , ' %s &'];
+else
+    format_string = [ format_string , ' %6.4f &'];
+end
+format_string = [ format_string , ' %6.4f & %6.4f \\\\ \n'];
\ No newline at end of file
diff --git a/matlab/conditional_variance_decomposition_mc_analysis.m b/matlab/conditional_variance_decomposition_mc_analysis.m
index 0042398001db9ec0941a0e91d20c309436f61053..22273f2be96270453b38d935efc1873073239953 100644
--- a/matlab/conditional_variance_decomposition_mc_analysis.m
+++ b/matlab/conditional_variance_decomposition_mc_analysis.m
@@ -1,7 +1,27 @@
 function oo_ = ...
     conditional_variance_decomposition_mc_analysis(NumberOfSimulations, type, dname, fname, Steps, exonames, exo, var_list, endogenous_variable_index, mh_conf_sig, oo_)
 % This function analyses the (posterior or prior) distribution of the
-% endogenous conditional variance decomposition.
+% endogenous variables' conditional variance decomposition.
+%
+% INPUTS
+%   NumberOfSimulations     [integer]           scalar, number of simulations.
+%   type                    [string]            'prior' or 'posterior'
+%   dname                   [string]            directory name where to save
+%   fname                   [string]            name of the mod-file
+%   Steps                   [integers]          horizons at which to conduct decomposition
+%   exonames                [string]            (n_exo*char_length) character array with names of exogenous variables        
+%   exo                     [string]            name of current exogenous
+%                                               variable
+%   var_list                [string]            (n_endo*char_length) character array with name
+%                                               of endogenous variables
+%   endogenous_variable_index [integer]         index of the current
+%                                               endogenous variable
+%   mh_conf_sig             [double]            2 by 1 vector with upper
+%                                               and lower bound of HPD intervals
+%   oo_                     [structure]         Dynare structure where the results are saved.
+%
+% OUTPUTS
+%   oo_          [structure]        Dynare structure where the results are saved.
 
 % Copyright (C) 2009-2013 Dynare Team
 %
diff --git a/matlab/reports/@section/addTable.m b/matlab/convert_oo_.m
similarity index 54%
rename from matlab/reports/@section/addTable.m
rename to matlab/convert_oo_.m
index 30f79c73d60eb3a05976e9e81ac4f391c99e9ccf..355f5a812069e314630ab555159d5134c8cea63c 100644
--- a/matlab/reports/@section/addTable.m
+++ b/matlab/convert_oo_.m
@@ -1,19 +1,18 @@
-function o = addTable(o, varargin)
-%function o = addTable(o, varargin)
-% Add a report_table to the Cell Array of report_tables in the report
+function oo_ = convert_oo_(oo_, ver)
+%function oo_ = convert_oo_(oo_, ver)
+% Converts oo_ from oo_.dynare_version to ver
 %
 % INPUTS
-%   1 args => add empty report_table
-%   2 args => add given report_table
-%   3 args => add report_table at index
+%    oo_    [struct]    dynare output struct
+%    ver    [string]    desired oo_ output version
 %
 % OUTPUTS
-%   updated section object
+%    oo_    [struct]    dynare output struct
 %
 % SPECIAL REQUIREMENTS
-%   none
+%    none
 
-% Copyright (C) 2013-2014 Dynare Team
+% Copyright (C) 2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -30,9 +29,19 @@ function o = addTable(o, varargin)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-for i=1:length(o.elements)
-    assert(~isa(o.elements{i}, 'paragraph'), ...
-           '@addTable: A Section that contains a Paratable cannot contain a Table');
+check_valid_ver(ver);
+
+if isfield(oo_, 'dynare_version')
+    ver_orig = oo_.dynare_version;
+else
+    ver_orig = '4.4.3';
+end
+
+if strcmp(ver_orig, ver)
+    return;
+end
+
+if ver_less_than(ver_orig, '4.5.0') && ver_greater_than_equal(ver, '4.5.0')
+    oo_.exo_simul = oo_.exo_simul';
 end
-o.elements{end+1} = report_table(varargin{:});
 end
diff --git a/matlab/covariance_mc_analysis.m b/matlab/covariance_mc_analysis.m
index a24ec665e27c7d71f3041c742e4e6f062aada26d..d98992f0eb9b17ebe72fac678c57f7da94ccc6cd 100644
--- a/matlab/covariance_mc_analysis.m
+++ b/matlab/covariance_mc_analysis.m
@@ -1,8 +1,24 @@
 function oo_ = covariance_mc_analysis(NumberOfSimulations,type,dname,fname,vartan,nvar,var1,var2,mh_conf_sig,oo_)
 % This function analyses the (posterior or prior) distribution of the
-% endogenous variables covariance matrix.
+% endogenous variables' covariance matrix.
+% 
+% INPUTS
+%   NumberOfSimulations     [integer]           scalar, number of simulations.
+%   type                    [string]            'prior' or 'posterior'
+%   dname                   [string]            directory name where to save
+%   fname                   [string]            name of the mod-file
+%   vartan                  [char]              array of characters (with nvar rows).
+%   nvar                    [integer]           nvar is the number of stationary variables.
+%   var1                    [string]            name of the first variable
+%   var2                    [string]            name of the second variable
+%   mh_conf_sig             [double]            2 by 1 vector with upper
+%                                               and lower bound of HPD intervals
+%   oo_                     [structure]         Dynare structure where the results are saved.
+%
+% OUTPUTS
+%   oo_                     [structure]        Dynare structure where the results are saved.
 
-% Copyright (C) 2008-2013 Dynare Team
+% Copyright (C) 2008-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/det_forecast.m b/matlab/det_forecast.m
deleted file mode 100644
index dceb694386243d47324cc660f6a5d5372a55e1f4..0000000000000000000000000000000000000000
--- a/matlab/det_forecast.m
+++ /dev/null
@@ -1,163 +0,0 @@
-function det_cond_forecast(constrained_paths, constrained_vars, options_cond_fcst, constrained_perfect_foresight)
-% Computes forecasts using the schocks retrieved from a condition forecast for a deterministic model.
-%
-% INPUTS
-%  o constrained_paths    [double]      m*p array, where m is the number of constrained endogenous variables and p is the number of constrained periods.
-%  o constrained_vars     [char]        m*x array holding the names of the controlled endogenous variables.
-%  o options_cond_fcst    [structure]   containing the options. The fields are:
-%                                                             + replic              [integer]   scalar, number of monte carlo simulations.
-%                                                             + parameter_set       [char]      values of the estimated parameters:
-%                                                                                               "posterior_mode",
-%                                                                                               "posterior_mean",
-%                                                                                               "posterior_median",
-%                                                                                               "prior_mode" or
-%                                                                                               "prior mean".
-%                                                                                   [double]     np*1 array, values of the estimated parameters.
-%                                                             + controlled_varexo   [char]       m*x array, list of controlled exogenous variables.
-%                                                             + conf_sig            [double]     scalar in [0,1], probability mass covered by the confidence bands.
-%  o constrained_perfect_foresight [double] m*1 array indicating if the endogenous variables path is perfectly foresight (1) or is a surprise (0)
-%
-%
-% OUTPUTS
-%  None.
-%
-% SPECIAL REQUIREMENTS
-%  This routine has to be called after an estimation statement or an estimated_params block.
-%
-% REMARKS
-%  [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) 2013 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_ M_
-
-if ~isfield(options_cond_fcst,'periods') || isempty(options_cond_fcst.periods)
-    options_cond_fcst.periods = 60;
-end
-
-maximum_lag = M_.maximum_lag;
-maximum_lead = M_.maximum_lead;
-ys = oo_.steady_state;
-ny = size(ys,1);
-xs = [oo_.exo_steady_state ; oo_.exo_det_steady_state];
-nx = size(xs,1);
-
-constrained_periods = size(constrained_paths,2);
-n_endo_constrained = size(constrained_vars,1);
-if isfield(options_cond_fcst,'controlled_varexo')
-    n_control_exo = size(options_cond_fcst.controlled_varexo, 1);
-    if n_control_exo ~= n_endo_constrained
-        error(['det_cond_forecast:: the number of exogenous controlled variables (' int2str(n_control_exo) ') has to be equal to the number of constrained endogenous variabes (' int2str(n_endo_constrained) ')'])
-    end;
-else
-    error('det_cond_forecast:: to run a deterministic conditional forecast you have to specified the exogenous variables controlled using the option controlled_varex in forecast command');
-end;
-
-exo_names = M_.exo_names;
-controlled_varexo = zeros(1,n_control_exo);
-for i = 1:nx
-    for j=1:n_control_exo
-        if strcmp(exo_names(i,:), options_cond_fcst.controlled_varexo(j,:))
-            controlled_varexo(j) = i;
-        end
-    end
-end
-
-save_options_initval_file = options_.initval_file;
-options_.initval_file = '__';
-
-[pos_constrained_pf, junk] = find(constrained_perfect_foresight);
-indx_endo_solve_pf = constrained_vars(pos_constrained_pf);
-if isempty(indx_endo_solve_pf)
-    pf = 0;
-else
-    pf = length(indx_endo_solve_pf);
-end;
-indx_endo_solve_surprise = setdiff(constrained_vars, indx_endo_solve_pf);
-
-if isempty(indx_endo_solve_surprise)
-    surprise = 0;
-else
-    surprise = length(indx_endo_solve_surprise);
-end;
-
-eps = options_.solve_tolf;
-maxit = options_.simul.maxit;
-
-% Check the solution using a unconditional forecast (soft tune)
-
-initial_conditions = oo_.steady_state;
-terminal_conditions = oo_.steady_state;
-exo = oo_.exo_simul;
-T = options_.periods + 2;
-endo_simul = zeros(ny, T);
-endo_simul(:,1) = initial_conditions;
-endo_simul(:,T) = initial_conditions;
-exo_simul = zeros(T, nx);
-exo_simul(1,:) = [oo_.exo_steady_state' oo_.exo_det_steady_state'];
-exo_simul(T,:) = [oo_.exo_steady_state'  oo_.exo_det_steady_state'];
-past_val = 0;
-
-if pf && ~surprise
-    make_ex_;
-    make_y_;
-    oo_.endo_simul(:,1) = initial_conditions;
-    oo_.endo_simul(:,options_.periods + 2) = terminal_conditions;
-    %oo_.exo_simul = repmat(oo_.exo_steady_state, options_.periods + 2, 1);
-    oo_.exo_simul = exo;
-    simul();
-    endo_simul = oo_.endo_simul;
-    exo_simul = oo_.exo_simul;
-else
-    for t=1:constrained_periods
-        make_ex_;
-        make_y_;
-        disp(['t=' int2str(t) ' constrained_periods=' int2str(constrained_periods)]);
-        oo_.endo_simul(:,1) = initial_conditions;
-        oo_.endo_simul(:,options_.periods + 2) = terminal_conditions;
-        time_index_constraint = maximum_lag + 1:maximum_lag + constrained_periods - t + 1;
-        if t <= constrained_periods
-            for j = controlled_varexo
-                if constrained_perfect_foresight(j)
-                    for time = time_index_constraint;
-                        oo_.exo_simul(time,j) = exo(past_val + time,j);
-                    end;
-                    oo_.exo_simul(time+1, j)= oo_.exo_steady_state(j);
-                else
-                    oo_.exo_simul(maximum_lag + 1,j) = exo(maximum_lag + t,j);
-                end;
-            end;
-        else
-            tmp = size(oo_.exo_simul,1);
-            oo_.exo_simul = repmat(oo_.exo_steady_state',tmp,1);
-        end;
-        past_val = past_val + length(time_index_constraint);
-        simul();
-        initial_conditions = oo_.endo_simul(:,2);
-        if t < constrained_periods
-            endo_simul(:,t+1) = initial_conditions;
-            exo_simul(t+1,:) = oo_.exo_simul(2,:);
-        else
-            endo_simul(:,t + 1:t + options_cond_fcst.periods + maximum_lead) = oo_.endo_simul(:,maximum_lag + 1:maximum_lag + options_cond_fcst.periods + maximum_lead);
-            exo_simul(t+1,:) = oo_.exo_simul(2,:);
-        end;
-    end;
-end;
-oo_.endo_simul = endo_simul;
-oo_.exo_simul = exo_simul;
diff --git a/matlab/disp_dr.m b/matlab/disp_dr.m
index 34fd620c341e48912d01f60d0bcf51f32af57fa9..906431437ef611439a9563cab4e467dd5c24114c 100644
--- a/matlab/disp_dr.m
+++ b/matlab/disp_dr.m
@@ -1,5 +1,5 @@
-
 function disp_dr(dr,order,var_list)
+% function disp_dr(dr,order,var_list)
 % Display the decision rules
 %
 % INPUTS
@@ -7,8 +7,8 @@ function disp_dr(dr,order,var_list)
 %    order [int]:            order of approximation
 %    var_list [char array]:  list of endogenous variables for which the
 %                            decision rules should be printed
-
-% Copyright (C) 2001-2012 Dynare Team
+% 
+% Copyright (C) 2001-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -55,44 +55,67 @@ for i=1:nvar
     end
 end
 
+% get length of display strings
+header_label_length=16; %default
+for ii=1:length(ivar)
+    header_label_length=max(header_label_length,length(deblank(M_.endo_names(k1(ivar(ii)),:)))+2);
+end
+header_label_format  = sprintf('%%%ds',header_label_length);
+value_format_float  = sprintf('%%%d.6f',header_label_length);
+value_format_zero  = sprintf('%%%dd',header_label_length);
+
+% account for additional characters introduced by auxiliary variables
+if ~isempty(M_.aux_vars)
+    aux_vars_type = [M_.aux_vars.type];
+    if any(aux_vars_type==4)
+        aux_var_additional_characters=14;
+    else
+        aux_var_additional_characters=3;
+    end
+else
+    aux_var_additional_characters=0;
+end
+
+var_name_width=max([max(size(deblank(M_.endo_names(k1(ivar),:)),2)),max(size(deblank(M_.exo_names),2))]);
+
+%deal with covariances
+if order > 1
+    var_name_width=max(2*(var_name_width+aux_var_additional_characters)+2,20); %account for covariances, separated by comma    
+else
+    var_name_width=max(var_name_width+aux_var_additional_characters,20);
+end
+label_format  = sprintf('%%-%ds',var_name_width);
+
+
+%% start displayimg
 disp('POLICY AND TRANSITION FUNCTIONS')
 % variable names
-str = '                        ';
+str = char(32*ones(1,var_name_width)); 
 for i=1:nvar
-    str = [str sprintf('%16s',M_.endo_names(k1(ivar(i)),:))];
+    str = [str sprintf(header_label_format,deblank(M_.endo_names(k1(ivar(i)),:)))];
 end
 disp(str);
 %
 % constant
 %
-str = 'Constant            ';
+str=sprintf(label_format,'Constant');
 flag = 0;
 for i=1:nvar
     x = dr.ys(k1(ivar(i)));
     if order > 1
         x = x + dr.ghs2(ivar(i))/2;
     end
-    if abs(x) > 1e-6
-        flag = 1;
-        str = [str sprintf('%16.6f',x)];
-    else
-        str = [str '               0'];
-    end
+    [str,flag]=get_print_string(str,x,value_format_zero,value_format_float,flag,options_);
 end
 if flag
     disp(str)
 end
 if order > 1
-    str = '(correction)        ';
+    str = sprintf(label_format,'(correction)');
     flag = 0;
     for i=1:nvar
         x = dr.ghs2(ivar(i))/2;
-        if abs(x) > 1e-6
-            flag = 1;
-            str = [str sprintf('%16.6f',x)];
-        else
-            str = [str '               0'];
-        end
+        [str,flag]=get_print_string(str,x,value_format_zero,value_format_float,flag,options_);
     end
     if flag
         disp(str)
@@ -108,15 +131,10 @@ for k=1:nx
     else
         str1 = subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2);
     end
-    str = sprintf('%-20s',str1);
+    str = sprintf(label_format,str1);
     for i=1:nvar
         x = dr.ghx(ivar(i),k);
-        if abs(x) > 1e-6
-            flag = 1;
-            str = [str sprintf('%16.6f',x)];
-        else
-            str = [str '               0'];
-        end
+        [str,flag]=get_print_string(str,x,value_format_zero,value_format_float,flag,options_);
     end
     if flag
         disp(str)
@@ -127,15 +145,10 @@ end
 %
 for k=1:nu
     flag = 0;
-    str = sprintf('%-20s',M_.exo_names(k,:));
+    str = sprintf(label_format,M_.exo_names(k,:));
     for i=1:nvar
         x = dr.ghu(ivar(i),k);
-        if abs(x) > 1e-6
-            flag = 1;
-            str = [str sprintf('%16.6f',x)];
-        else
-            str = [str '               0'];
-        end
+        [str,flag]=get_print_string(str,x,value_format_zero,value_format_float,flag,options_);
     end
     if flag
         disp(str)
@@ -149,19 +162,14 @@ if order > 1
             flag = 0;
             str1 = sprintf('%s,%s',subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2), ...
                            subst_auxvar(k1(klag(j,1)),klag(j,2)-M_.maximum_lag-2));
-            str = sprintf('%-20s',str1);
+            str = sprintf(label_format,str1);
             for i=1:nvar
                 if k == j
                     x = dr.ghxx(ivar(i),(k-1)*nx+j)/2;
                 else
                     x = dr.ghxx(ivar(i),(k-1)*nx+j);
                 end
-                if abs(x) > 1e-6
-                    flag = 1;
-                    str = [str sprintf('%16.6f',x)];
-                else
-                    str = [str '               0'];
-                end
+                [str,flag]=get_print_string(str,x,value_format_zero,value_format_float,flag,options_);
             end
             if flag
                 disp(str)
@@ -174,19 +182,14 @@ if order > 1
     for k = 1:nu
         for j = 1:k
             flag = 0;
-            str = sprintf('%-20s',[M_.exo_names(k,:) ',' M_.exo_names(j,:)] );
+            str = sprintf(label_format,[deblank(M_.exo_names(k,:)) ',' deblank(M_.exo_names(j,:))] );
             for i=1:nvar
                 if k == j
                     x = dr.ghuu(ivar(i),(k-1)*nu+j)/2;
                 else
                     x = dr.ghuu(ivar(i),(k-1)*nu+j);
                 end
-                if abs(x) > 1e-6
-                    flag = 1;
-                    str = [str sprintf('%16.6f',x)];
-                else
-                    str = [str '               0'];
-                end
+                [str,flag]=get_print_string(str,x,value_format_zero,value_format_float,flag,options_);
             end
             if flag
                 disp(str)
@@ -200,16 +203,11 @@ if order > 1
         for j = 1:nu
             flag = 0;
             str1 = sprintf('%s,%s',subst_auxvar(k1(klag(k,1)),klag(k,2)-M_.maximum_lag-2), ...
-                           M_.exo_names(j,:));
-            str = sprintf('%-20s',str1);
+                           deblank(M_.exo_names(j,:)));
+            str = sprintf(label_format,str1);
             for i=1:nvar
                 x = dr.ghxu(ivar(i),(k-1)*nu+j);
-                if abs(x) > 1e-6
-                    flag = 1;
-                    str = [str sprintf('%16.6f',x)];
-                else
-                    str = [str '               0'];
-                end
+                [str,flag]=get_print_string(str,x,value_format_zero,value_format_float,flag,options_);
             end
             if flag
                 disp(str)
@@ -253,3 +251,12 @@ for i = 1:length(M_.aux_vars)
 end
 error(sprintf('Could not find aux var: %s', M_.endo_names(aux_index, :)))
 end
+
+function [str,flag]=get_print_string(str,x,value_format_zero,value_format_float,flag,options_)
+    if abs(x) > options_.dr_display_tol
+        flag = 1;
+        str = [str sprintf(value_format_float,x)];
+    else
+        str = [str sprintf(value_format_zero,0)];
+    end
+end
\ No newline at end of file
diff --git a/matlab/distributions/rand_multivariate_student.m b/matlab/distributions/rand_multivariate_student.m
index 6d9b52df6159400b2bc2687415312bc830dcf993..eca1d05852c76a88788811e4412ae3c070238128 100644
--- a/matlab/distributions/rand_multivariate_student.m
+++ b/matlab/distributions/rand_multivariate_student.m
@@ -1,4 +1,5 @@
 function draw = rand_multivariate_student(Mean,Sigma_upper_chol,df)
+% function draw = rand_multivariate_student(Mean,Sigma_upper_chol,df)
 % Pseudo random draws from a multivariate student distribution,
 % with expectation Mean, variance Sigma*df/(df-2) and degrees of freedom df>0.
 %
@@ -13,10 +14,14 @@ function draw = rand_multivariate_student(Mean,Sigma_upper_chol,df)
 %    draw               [double]    1*n vector drawn from a multivariate normal distribution with expectation Mean and
 %                                   covariance Sigma.
 %        
-% REMARK This is certainly not the most efficient way...
 %
 % NOTE See Zellner (appendix B.2, 1971) for a definition.     
-%    
+%    Computes the t-distributed random numbers from 
+%       X = \mu + Y\sqrt{\frac{\nu}{U}}
+%   where 
+%       Y~N(0,Sigma) with Sigma=Sigma_upper_chol'*Sigma_upper_chol
+%       U~\Chi^2_{\nu}
+%   The latter is constructed as the sum of \nu standard normals.
 
 % Copyright (C) 2003-2009 Dynare Team
 %
diff --git a/matlab/dr_block.m b/matlab/dr_block.m
index 2bca7bbe333f02df77a6d454b7bf21159146d5a0..7eee88acd9a7e37f84ebcf641ab81b6e9fded7ad 100644
--- a/matlab/dr_block.m
+++ b/matlab/dr_block.m
@@ -1,4 +1,4 @@
-function [dr,info,M_,options_,oo_] = dr_block(dr,task,M_,options_,oo_)
+function [dr,info,M_,options_,oo_] = dr_block(dr,task,M_,options_,oo_,varargin)
 % function [dr,info,M_,options_,oo_] = dr_block(dr,task,M_,options_,oo_)
 % computes the reduced form solution of a rational expectation model (first
 % approximation of the stochastic model around the deterministic steady state). 
@@ -33,7 +33,7 @@ function [dr,info,M_,options_,oo_] = dr_block(dr,task,M_,options_,oo_)
 %   none.
 %  
 
-% Copyright (C) 2010-2013 Dynare Team
+% Copyright (C) 2010-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -51,7 +51,11 @@ function [dr,info,M_,options_,oo_] = dr_block(dr,task,M_,options_,oo_)
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 info = 0;
-verbose = options_.verbosity;
+verbose = 0;
+if nargin > 5
+  verbose = varargin{1};
+end
+%verbose = options_.verbosity;
 if options_.order > 1
     error('2nd and 3rd order approximation not implemented with block option')
 end
@@ -68,7 +72,7 @@ end;
 if (options_.bytecode)
     [chck, zz, data]= bytecode('dynamic','evaluate', z, zx, M_.params, dr.ys, 1, data);
 else
-    [r, data] = feval([M_.fname '_dynamic'], z', zx, M_.params, dr.ys, M_.maximum_lag+1, data);
+    [r, data] = feval([M_.fname '_dynamic'], options_, M_, oo_, z', zx, M_.params, dr.ys, M_.maximum_lag+1, data);
     chck = 0;
 end;
 mexErrCheck('bytecode', chck);
@@ -311,13 +315,17 @@ for i = 1:Size;
         dr.eigval = [dr.eigval ; data(i).eigval];
       case 6
       %% ------------------------------------------------------------------
-        %Solve Forward complete
+      %Solve Forward complete
+        if (maximum_lag > 0)
+            ghx = - jacob(: , n_pred + 1 : n_pred + n_static ...
+                        + n_pred + n_both) \ jacob(: , 1 : n_pred);
+        else
+            ghx = 0;
+        end;
         if maximum_lag > 0 && n_pred > 0
-            data(i).eigval = eig(- jacob(: , 1 : n_pred) / ...
-                                 jacob(: , (n_pred + n_static + 1 : n_pred + n_static + n_pred )));
+            data(i).eigval = -eig(ghx(n_static+1:end,:));
             data(i).rank = 0;
-            full_rank = (rcond(jacob(: , (n_pred + n_static + 1 : n_pred ...
-                                          + n_static + n_pred ))) > 1e-9);
+            full_rank = (rcond(ghx(n_static+1:end,:)) > 1e-9);
         else
             data(i).eigval = [];
             data(i).rank = 0;
@@ -326,11 +334,6 @@ for i = 1:Size;
         dr.eigval = [dr.eigval ; data(i).eigval];
         dr.full_rank = dr.full_rank && full_rank;
         if task ~= 1
-            if (maximum_lag > 0)
-                 ghx = - jacob(: , 1 : n_pred) / jacob(: , n_pred + n_static + 1 : n_pred + n_static + n_pred + n_both);
-            else
-                 ghx = 0;
-            end;
             if other_endo_nbr
                 fx = data(i).g1_o;
                 % retrieves the derivatives with respect to endogenous
diff --git a/matlab/dsge_likelihood.m b/matlab/dsge_likelihood.m
index 585b7e97a2bf01bd74225b996e133a7d23ce9f84..56c8dc2fae476ace6ac33eaba146950a19d99304 100644
--- a/matlab/dsge_likelihood.m
+++ b/matlab/dsge_likelihood.m
@@ -70,6 +70,8 @@ function [fval,DLIK,Hess,exit_flag,SteadyState,trend_coeff,info,Model,DynareOpti
 %! M_.params has been updated in the steadystate routine and has complex valued scalars.
 %! @item info==24
 %! M_.params has been updated in the steadystate routine and has some NaNs.
+%! @item info==26
+%! M_.params has been updated in the steadystate routine and has negative/0 values in loglinear model.
 %! @item info==30
 %! Ergodic variance can't be computed.
 %! @item info==41
@@ -266,7 +268,7 @@ if info(1) == 1 || info(1) == 2 || info(1) == 5 || info(1) == 7 || info(1) == 8
         DLIK=ones(length(xparam1),1);
     end
     return
-elseif info(1) == 3 || info(1) == 4 || info(1)==6 || info(1) == 20 || info(1) == 21  || info(1) == 23
+elseif info(1) == 3 || info(1) == 4 || info(1)==6 || info(1) == 20 || info(1) == 21  || info(1) == 23 || info(1)==26
     fval = objective_function_penalty_base+info(2);
     info = info(1);
     exit_flag = 0;
@@ -326,6 +328,7 @@ mm = length(T);
 pp = DynareDataset.vobs;
 rr = length(Q);
 kalman_tol = DynareOptions.kalman_tol;
+diffuse_kalman_tol = DynareOptions.diffuse_kalman_tol;
 riccati_tol = DynareOptions.riccati_tol;
 Y = transpose(DynareDataset.data)-trend;
 
@@ -403,13 +406,13 @@ switch DynareOptions.lik_init
         if no_missing_data_flag
             [dLIK,dlik,a,Pstar] = kalman_filter_d(Y, 1, size(Y,2), ...
                                                        zeros(mm,1), Pinf, Pstar, ...
-                                                       kalman_tol, riccati_tol, DynareOptions.presample, ...
+                                                       kalman_tol, diffuse_kalman_tol, riccati_tol, DynareOptions.presample, ...
                                                        T,R,Q,H,Z,mm,pp,rr);
         else
             [dLIK,dlik,a,Pstar] = missing_observations_kalman_filter_d(DatasetInfo.missing.aindex,DatasetInfo.missing.number_of_observations,DatasetInfo.missing.no_more_missing_observations, ...
                                                               Y, 1, size(Y,2), ...
                                                               zeros(mm,1), Pinf, Pstar, ...
-                                                              kalman_tol, riccati_tol, DynareOptions.presample, ...
+                                                              kalman_tol, diffuse_kalman_tol, riccati_tol, DynareOptions.presample, ...
                                                               T,R,Q,H,Z,mm,pp,rr);
         end
         diffuse_periods = length(dlik);
@@ -446,7 +449,7 @@ switch DynareOptions.lik_init
                                                         DatasetInfo.missing.no_more_missing_observations, ...
                                                         Y, 1, size(Y,2), ...
                                                         zeros(mmm,1), Pinf, Pstar, ...
-                                                        kalman_tol, riccati_tol, DynareOptions.presample, ...
+                                                        kalman_tol, diffuse_kalman_tol, riccati_tol, DynareOptions.presample, ...
                                                         T,R,Q,H1,Z,mmm,pp,rr);
         diffuse_periods = size(dlik,1);
     end
@@ -629,7 +632,7 @@ if analytic_derivation,
         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};
-        clear DT DYss DOm DH DP D2T D2Yss D2Om D2H D2P,
+        clear DT DYss DOm DP D2T D2Yss D2Om D2H D2P,
     end
 else
     analytic_deriv_info={0};
diff --git a/matlab/dsge_simulated_theoretical_conditional_variance_decomposition.m b/matlab/dsge_simulated_theoretical_conditional_variance_decomposition.m
index 7ef623b81652b67970544a99567564b62901b99f..1c04413615b23a5df75876b1f1a35ee25bc2736e 100644
--- a/matlab/dsge_simulated_theoretical_conditional_variance_decomposition.m
+++ b/matlab/dsge_simulated_theoretical_conditional_variance_decomposition.m
@@ -1,10 +1,13 @@
 function [nvar,vartan,NumberOfConditionalDecompFiles] = ...
     dsge_simulated_theoretical_conditional_variance_decomposition(SampleSize,Steps,M_,options_,oo_,type)
+% function [nvar,vartan,NumberOfConditionalDecompFiles] = ...
+%     dsge_simulated_theoretical_conditional_variance_decomposition(SampleSize,Steps,M_,options_,oo_,type)
 % This function computes the posterior or prior distribution of the conditional variance
 % decomposition of the endogenous variables (or a subset of the endogenous variables).
 %
 % INPUTS
 %   SampleSize   [integer]       scalar, number of simulations.
+%   Steps        [integers]      horizons at which to conduct decomposition
 %   M_           [structure]     Dynare structure describing the model.
 %   options_     [structure]     Dynare structure defining global options.
 %   oo_          [structure]     Dynare structure where the results are saved.
@@ -16,7 +19,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-2012 Dynare Team
+% Copyright (C) 2009-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -47,6 +50,13 @@ else
     error()
 end
 
+%delete old stale files before creating new ones
+if posterior
+    delete_stale_file([M_.dname '/metropolis/' M_.fname '_PosteriorConditionalVarianceDecomposition*'])
+else
+    delete_stale_file([M_.dname '/prior/moments/' M_.fname '_PriorConditionalVarianceDecomposition*'])
+end
+
 % Set varlist (vartan)
 if ~posterior
     if isfield(options_,'varlist')
diff --git a/matlab/dsge_simulated_theoretical_correlation.m b/matlab/dsge_simulated_theoretical_correlation.m
index 59ffa4e4ea8f0de648ffb19c055d5c145f4e6ce4..265336dbb05bb1f2f9342aecbdc1b616eda0d734 100644
--- a/matlab/dsge_simulated_theoretical_correlation.m
+++ b/matlab/dsge_simulated_theoretical_correlation.m
@@ -1,21 +1,23 @@
 function [nvar,vartan,CorrFileNumber] = dsge_simulated_theoretical_correlation(SampleSize,nar,M_,options_,oo_,type)
+% function [nvar,vartan,CorrFileNumber] = dsge_simulated_theoretical_correlation(SampleSize,nar,M_,options_,oo_,type)
 % This function computes the posterior or prior distribution of the endogenous
-% variables second order moments.
+% variables' second order moments.
 %
 % INPUTS
-%   SampleSize   [integer]
-%   nar          [integer]
-%   M_           [structure]
-%   options_     [structure]
-%   oo_          [structure]
-%   type         [string]
+%   SampleSize   [integer]          scalar, number of simulations.
+%   nar          [integer]          maximum number of autocorrelations to
+%                                   consider
+%   M_           [structure]        Dynare structure describing the model.
+%   options_     [structure]        Dynare structure defining global options
+%   oo_          [structure]        Dynare structure where the results are saved.
+%   type         [string]           'prior' or 'posterior'
 %
 % OUTPUTS
-%   nvar           [integer]
-%   vartan         [char]
-%   CorrFileNumber [integer]
-
-% Copyright (C) 2007-2012 Dynare Team
+%   nvar           [integer]        nvar is the number of stationary variables.
+%   vartan         [char]           array of characters (with nvar rows).
+%   CorrFileNumber [integer]        scalar, number of prior or posterior data files (for correlation).
+ 
+% Copyright (C) 2007-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -48,6 +50,13 @@ else
 end
 NumberOfDrawsFiles = length(DrawsFiles);
 
+%delete old stale files before creating new ones
+if posterior
+    delete_stale_file([M_.dname '/metropolis/' M_.fname '_PosteriorCorrelations*']);
+else
+    delete_stale_file([M_.dname '/prior/moments/' M_.fname '_PriorCorrelations*']);
+end
+
 % Set varlist (vartan)
 if ~posterior
     if isfield(options_,'varlist')
diff --git a/matlab/dsge_simulated_theoretical_covariance.m b/matlab/dsge_simulated_theoretical_covariance.m
index 5d39e77fb72343d4f284b132223bcd187b6ea9f3..38ef7c3b60f20266c395e8b791e03ec6a085fa31 100644
--- a/matlab/dsge_simulated_theoretical_covariance.m
+++ b/matlab/dsge_simulated_theoretical_covariance.m
@@ -1,4 +1,5 @@
 function [nvar,vartan,CovarFileNumber] = dsge_simulated_theoretical_covariance(SampleSize,M_,options_,oo_,type)
+% function [nvar,vartan,CovarFileNumber] = dsge_simulated_theoretical_covariance(SampleSize,M_,options_,oo_,type)
 % This function computes the posterior or prior distribution of the endogenous
 % variables second order moments.
 %
@@ -15,7 +16,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-2012 Dynare Team
+% Copyright (C) 2007-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -48,6 +49,13 @@ else
 end
 NumberOfDrawsFiles = length(DrawsFiles);
 
+%delete old stale files before creating new ones
+if posterior
+    delete_stale_file([M_.dname '/metropolis/' M_.fname '_Posterior2ndOrderMoments*'])
+else
+    delete_stale_file([M_.dname '/prior/moments/' M_.fname '_Prior2ndOrderMoments*'])
+end
+
 % Set varlist (vartan)
 if ~posterior
     if isfield(options_,'varlist')
diff --git a/matlab/dsge_simulated_theoretical_variance_decomposition.m b/matlab/dsge_simulated_theoretical_variance_decomposition.m
index 7059e6d134e2dd1582d8e896b33c092e1d3f6366..74335840e37b7723c92d039aff8bdba0aface89b 100644
--- a/matlab/dsge_simulated_theoretical_variance_decomposition.m
+++ b/matlab/dsge_simulated_theoretical_variance_decomposition.m
@@ -1,5 +1,7 @@
 function [nvar,vartan,NumberOfDecompFiles] = ...
     dsge_simulated_theoretical_variance_decomposition(SampleSize,M_,options_,oo_,type)
+% function [nvar,vartan,NumberOfDecompFiles] = ...
+%     dsge_simulated_theoretical_variance_decomposition(SampleSize,M_,options_,oo_,type)
 % This function computes the posterior or prior distribution of the variance
 % decomposition of the observed endogenous variables.
 %
@@ -16,7 +18,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-2012 Dynare Team
+% Copyright (C) 2007-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -47,7 +49,13 @@ else
     disp('dsge_simulated_theoretical_variance_decomposition:: Unknown type!')
     error()
 end
-NumberOfDrawsFiles = length(DrawsFiles);
+
+%delete old stale files before creating new ones
+if posterior
+    delete_stale_file([M_.dname '/metropolis/' M_.fname '_PosteriorVarianceDecomposition*']);
+else
+    delete_stale_file([M_.dname '/prior/moments/' M_.fname '_PosteriorVarianceDecomposition*']);
+end
 
 % Set varlist (vartan)
 if ~posterior
diff --git a/matlab/dsge_var_likelihood.m b/matlab/dsge_var_likelihood.m
index 07b5d1b735ec3048f5d5afc4e3d9cb6f1573a8e6..a8a9e871051b51ffd059c85b1e55822b787ba5d8 100644
--- a/matlab/dsge_var_likelihood.m
+++ b/matlab/dsge_var_likelihood.m
@@ -239,10 +239,38 @@ else% Evaluation of the likelihood of the dsge-var model when the dsge prior wei
     lik = .5*lik;% Minus likelihood
 end
 
+if isnan(lik)
+    info = 45;
+    fval = objective_function_penalty_base + 100;
+    exit_flag = 0;
+    return
+end
+
+if imag(lik)~=0
+    info = 46;
+    fval = objective_function_penalty_base + 100;
+    exit_flag = 0;
+    return
+end
+
 % Add the (logged) prior density for the dsge-parameters.
 lnprior = priordens(xparam1,BayesInfo.pshape,BayesInfo.p6,BayesInfo.p7,BayesInfo.p3,BayesInfo.p4);
 fval = (lik-lnprior);
 
+if isnan(fval)
+    info = 47;
+    fval = objective_function_penalty_base + 100;
+    exit_flag = 0;
+    return
+end
+
+if imag(fval)~=0
+    info = 48;
+    fval = objective_function_penalty_base + 100;
+    exit_flag = 0;
+    return
+end
+
 if (nargout == 8)
     if isinf(dsge_prior_weight)
         iXX = iGXX;
diff --git a/matlab/dyn_forecast.m b/matlab/dyn_forecast.m
index 5df0edbf80d1e62ea262ddaf1559952f4b2593f4..b6ad8c9601bf40559fb9bc8c55dd1b27b6e5c814 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-2013 Dynare Team
+% Copyright (C) 2003-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -37,6 +37,8 @@ global options_ oo_ M_
 
 info = 0;
 
+make_ex_;
+
 maximum_lag = M_.maximum_lag;
 
 endo_names = M_.endo_names;
@@ -122,15 +124,15 @@ if ~isscalar(trend)
 end
 
 for i=1:n_var
-    eval(['oo_.forecast.Mean.' var_list(i,:) '= yf(' int2str(i) ',maximum_lag+1:end)'';']);
-    eval(['oo_.forecast.HPDinf.' var_list(i,:) '= yf(' int2str(i) ',maximum_lag+1:end)''-' ...
-          ' int_width(:,' int2str(i) ');']);
-    eval(['oo_.forecast.HPDsup.' var_list(i,:) '= yf(' int2str(i) ',maximum_lag+1:end)''+' ...
-          ' int_width(:,' int2str(i) ');']);
+    eval(['oo_.forecast.Mean.' var_list(i,:) '= yf(' int2str(i) ',maximum_lag+(1:horizon))'';']);
+    eval(['oo_.forecast.HPDinf.' var_list(i,:) '= yf(' int2str(i) ',maximum_lag+(1:horizon))''-' ...
+          ' int_width(1:horizon,' int2str(i) ');']);
+    eval(['oo_.forecast.HPDsup.' var_list(i,:) '= yf(' int2str(i) ',maximum_lag+(1:horizon))''+' ...
+          ' int_width(1:horizon,' int2str(i) ');']);
 end
 
 for i=1:M_.exo_det_nbr
-    eval(['oo_.forecast.Exogenous.' M_.exo_det_names(i,:) '= oo_.exo_det_simul(:,' int2str(i) ');']);
+    eval(['oo_.forecast.Exogenous.' M_.exo_det_names(i,:) '= oo_.exo_det_simul(maximum_lag+(1:horizon),' int2str(i) ');']);
 end
 
 if options_.nograph == 0
diff --git a/matlab/dyn_ramsey_static.m b/matlab/dyn_ramsey_static.m
index 99d5e09397024f7c3256fa807bbcb1bbd14d5c19..c2b619b3f8b04735b1fb88d32d834acc816be270 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(ys_init,M,options_,oo)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2014 Dynare Team
+% Copyright (C) 2003-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -50,9 +50,15 @@ elseif options_.steadystate_flag
                                    M.endo_names,'exact')];
     end
     if inst_nbr == 1
-        inst_val = csolve(nl_func,ys_init(k_inst),'',options_.solve_tolf,100); %solve for instrument, using univariate solver, starting at initial value for instrument
+        %solve for instrument, using univariate solver, starting at initial value for instrument
+        inst_val = csolve(nl_func,ys_init(k_inst),'',options_.solve_tolf,100); 
     else
-        [inst_val,info1] = dynare_solve(nl_func,ys_init(k_inst),0); %solve for instrument, using multivariate solver, starting at initial value for instrument
+        %solve for instrument, using multivariate solver, starting at
+        %initial value for instrument
+        opt = options_;
+        opt.jacobian_flag = 0;
+        [inst_val,info1] = dynare_solve(nl_func,ys_init(k_inst), ...
+                                        opt);
     end
     ys_init(k_inst) = inst_val;
     exo_ss = [oo.exo_steady_state oo.exo_det_steady_state];
@@ -61,7 +67,9 @@ elseif options_.steadystate_flag
 else
     n_var = M.orig_endo_nbr;
     xx = oo.steady_state(1:n_var);
-    [xx,check] = dynare_solve(nl_func,xx,0);
+    opt = options_;
+    opt.jacobian_flag = 0;
+    [xx,check] = dynare_solve(nl_func,xx,opt);
     [junk,junk,steady_state] = nl_func(xx);
 end
 
@@ -124,11 +132,11 @@ Uyy = reshape(Uyy,endo_nbr,endo_nbr);
 % set multipliers and auxiliary variables that
 % depends on multipliers to 0 to compute residuals
 if (options_.bytecode)
-   [chck, res, junk] = bytecode('static',xx,[oo.exo_simul oo.exo_det_simul], ...
+   [chck, res, junk] = bytecode('static',xx,[oo.exo_steady_state oo.exo_det_steady_state], ...
                params, 'evaluate');
    fJ = junk.g1;
 else
-   [res,fJ] = feval([fname '_static'],xx,[oo.exo_simul oo.exo_det_simul], ...
+   [res,fJ] = feval([fname '_static'],xx,[oo.exo_steady_state oo.exo_det_steady_state], ...
                params);
 end
 % index of multipliers and corresponding equations
@@ -162,10 +170,10 @@ end
 function result = check_static_model(ys,M,options_,oo)
 result = false;
 if (options_.bytecode)
-    [chck, res, junk] = bytecode('static',ys,[oo.exo_simul oo.exo_det_simul], ...
+    [chck, res, junk] = bytecode('static',ys,[oo.exo_steady_state oo.exo_det_steady_state], ...
                                  M.params, 'evaluate'); 
 else
-    res = feval([M.fname '_static'],ys,[oo.exo_simul oo.exo_det_simul], ...
+    res = feval([M.fname '_static'],ys,[oo.exo_steady_state oo.exo_det_steady_state], ...
                 M.params);
 end
 if norm(res) < options_.solve_tolf
diff --git a/matlab/dyn_second_order_solver.m b/matlab/dyn_second_order_solver.m
index f4f1f85193588a7b6218f2cb6772e0653eb95640..dd2d2bfb8ee849ba80fc47f28ffbf509ddad68c4 100644
--- a/matlab/dyn_second_order_solver.m
+++ b/matlab/dyn_second_order_solver.m
@@ -1,7 +1,7 @@
-function dr = dyn_second_order_solver(jacobia,hessian,dr,M_,threads_ABC,threads_BC)
+function dr = dyn_second_order_solver(jacobia,hessian_mat,dr,M_,threads_ABC,threads_BC)
 
 %@info:
-%! @deftypefn {Function File} {@var{dr} =} dyn_second_order_solver (@var{jacobia},@var{hessian},@var{dr},@var{M_},@var{threads_ABC},@var{threads_BC})
+%! @deftypefn {Function File} {@var{dr} =} dyn_second_order_solver (@var{jacobia},@var{hessian_mat},@var{dr},@var{M_},@var{threads_ABC},@var{threads_BC})
 %! @anchor{dyn_second_order_solver}
 %! @sp 1
 %! Computes the second order reduced form of the DSGE model
@@ -11,7 +11,7 @@ function dr = dyn_second_order_solver(jacobia,hessian,dr,M_,threads_ABC,threads_
 %! @table @ @var
 %! @item jacobia
 %! Matrix containing the Jacobian of the model
-%! @item hessian
+%! @item hessian_mat
 %! Matrix containing the second order derivatives of the model
 %! @item dr
 %! Matlab's structure describing the reduced form solution of the model.
@@ -73,7 +73,7 @@ function dr = dyn_second_order_solver(jacobia,hessian,dr,M_,threads_ABC,threads_
     kk1 = reshape([1:nk^2],nk,nk);
     kk1 = kk1(kk,kk);
     % reordering second order derivatives
-    hessian = hessian(:,kk1(:));
+    hessian_mat = hessian_mat(:,kk1(:));
 
     zx = zeros(np,np);
     zu=zeros(np,M_.exo_nbr);
@@ -91,7 +91,7 @@ function dr = dyn_second_order_solver(jacobia,hessian,dr,M_,threads_ABC,threads_
     zu=[zu; eye(M_.exo_nbr);zeros(M_.exo_det_nbr,M_.exo_nbr)];
     [nrzx,nczx] = size(zx);
 
-    [rhs, err] = sparse_hessian_times_B_kronecker_C(hessian,zx,threads_BC);
+    [rhs, err] = sparse_hessian_times_B_kronecker_C(hessian_mat,zx,threads_BC);
     mexErrCheck('sparse_hessian_times_B_kronecker_C', err);
     rhs = -rhs;
 
@@ -118,7 +118,7 @@ function dr = dyn_second_order_solver(jacobia,hessian,dr,M_,threads_ABC,threads_
     %ghxu
     %rhs
     hu = dr.ghu(nstatic+1:nstatic+nspred,:);
-    [rhs, err] = sparse_hessian_times_B_kronecker_C(hessian,zx,zu,threads_BC);
+    [rhs, err] = sparse_hessian_times_B_kronecker_C(hessian_mat,zx,zu,threads_BC);
     mexErrCheck('sparse_hessian_times_B_kronecker_C', err);
 
     hu1 = [hu;zeros(np-nspred,M_.exo_nbr)];
@@ -136,7 +136,7 @@ function dr = dyn_second_order_solver(jacobia,hessian,dr,M_,threads_ABC,threads_
 
     %ghuu
     %rhs
-    [rhs, err] = sparse_hessian_times_B_kronecker_C(hessian,zu,threads_BC);
+    [rhs, err] = sparse_hessian_times_B_kronecker_C(hessian_mat,zu,threads_BC);
     mexErrCheck('sparse_hessian_times_B_kronecker_C', err);
 
     [B1, err] = A_times_B_kronecker_C(B*dr.ghxx,hu1,threads_ABC);
@@ -164,7 +164,7 @@ function dr = dyn_second_order_solver(jacobia,hessian,dr,M_,threads_ABC,threads_
     hxx = dr.ghxx(nstatic+[1:nspred],:);
     [junk,k2a,k2] = find(M_.lead_lag_incidence(M_.maximum_endo_lag+2,order_var));
     k3 = nnz(M_.lead_lag_incidence(1:M_.maximum_endo_lag+1,:))+(1:M_.nsfwrd)';
-    [B1, err] = sparse_hessian_times_B_kronecker_C(hessian(:,kh(k3,k3)),gu(k2a,:),threads_BC);
+    [B1, err] = sparse_hessian_times_B_kronecker_C(hessian_mat(:,kh(k3,k3)),gu(k2a,:),threads_BC);
     mexErrCheck('sparse_hessian_times_B_kronecker_C', err);
     RHS = RHS + jacobia(:,k2)*guu(k2a,:)+B1;
 
diff --git a/matlab/dynare.m b/matlab/dynare.m
index d72d20787dcdc50583fe54a9eeb700b6785ae82e..3ab08aef485d2c5e24db3be395a02e7c024bd848 100644
--- a/matlab/dynare.m
+++ b/matlab/dynare.m
@@ -16,7 +16,7 @@ function dynare(fname, varargin)
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2001-2014 Dynare Team
+% Copyright (C) 2001-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -44,7 +44,22 @@ if strcmpi(fname,'help')
     return
 end
 
-% detect if MEX files are present; if not, use alternative M-files
+% Set default local options
+change_path_flag = true;
+
+% Filter out some options.
+if nargin>1
+    id = strfind(varargin,'nopathchange');
+    if ~isempty(id)
+        change_path_flag = false;
+        varargin(id{1}) = [];
+    end
+end
+
+% Check matlab path
+check_matlab_path(change_path_flag);
+
+% Detect if MEX files are present; if not, use alternative M-files
 dynareroot = dynare_config;
 
 warning_config()
@@ -81,6 +96,10 @@ end
 
 % Testing if file have extension
 % If no extension default .mod is added
+dot_location=(strfind(fname,'.'));
+if length(dot_location)>1
+    error('DYNARE: Periods in filenames are only allowed for .mod or .dyn extensions')
+end
 if isempty(strfind(fname,'.'))
     fnamelength = length(fname);
     fname1 = [fname '.dyn'];
@@ -91,9 +110,10 @@ if isempty(strfind(fname,'.'))
     fname = fname1;
     % Checking file extension
 else
-    if ~strcmp(upper(fname(size(fname,2)-3:size(fname,2))),'.MOD') ...
+    if dot_location~=length(fname)-3 ... %if the file name has fewer than 4 characters and there is a period
+        || ~strcmp(upper(fname(size(fname,2)-3:size(fname,2))),'.MOD') ...
             && ~strcmp(upper(fname(size(fname,2)-3:size(fname,2))),'.DYN')
-        error('DYNARE: argument must be a filename with .mod or .dyn extension')
+        error('DYNARE: argument must be a filename with .mod or .dyn extension and must not include any other periods')
     end;
     fnamelength = length(fname) - 4;
 end;
@@ -140,14 +160,32 @@ if ~exist(fname,'file') || isequal(fname,'dir')
     error(['dynare:: can''t open ' fname])
 end
 
+if ~isvarname(fname(1:end-4))
+    error('DYNARE: argument of dynare must conform to Matlab''s convention for naming functions, i.e. start with a letter and not contain special characters. Please rename your MOD-file.')
+end
+
 % pre-dynare-preprocessor-hook
 if exist(fname(1:end-4),'dir') && exist([fname(1:end-4) filesep 'hooks'],'dir') && exist([fname(1:end-4) filesep 'hooks/priorprocessing.m'],'file')
     run([fname(1:end-4) filesep 'hooks/priorprocessing'])
 end
 
-command = ['"' dynareroot 'dynare_m" ' fname] ;
-for i=2:nargin
-    command = [command ' ' varargin{i-1}];
+if ispc
+    arch = getenv('PROCESSOR_ARCHITECTURE');
+else
+    [junk, arch] = system('uname -m');
+end
+
+if isempty(strfind(arch, '64'))
+  arch_ext = '32';
+  disp('Using 32-bit preprocessor');
+else
+  arch_ext = '64';
+  disp('Using 64-bit preprocessor');
+end
+
+command = ['"' dynareroot 'preprocessor' arch_ext filesep 'dynare_m" ' fname] ;
+for i=1:length(varargin)
+    command = [command ' ' varargin{i}];
 end
 
 [status, result] = system(command);
@@ -164,8 +202,8 @@ end
 
 % Save preprocessor result in logfile (if `no_log' option not present)
 no_log = 0;
-for i=2:nargin
-    no_log = no_log || strcmp(varargin{i-1}, 'nolog');
+for i=1:length(varargin)
+    no_log = no_log || strcmp(varargin{i}, 'nolog');
 end
 if ~no_log
     logname = [fname(1:end-4) '.log'];
diff --git a/matlab/dynare_config.m b/matlab/dynare_config.m
index 78f4e23c9a99bab823fa24ffb34182c49b365f3e..ee9804e08f54f2b8b6b14fa43bc1ba8b9fa4313b 100644
--- a/matlab/dynare_config.m
+++ b/matlab/dynare_config.m
@@ -15,7 +15,7 @@ function dynareroot = dynare_config(path_to_dynare,verbose)
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2001-2014 Dynare Team
+% Copyright (C) 2001-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -35,6 +35,7 @@ function dynareroot = dynare_config(path_to_dynare,verbose)
 if nargin && ~isempty(path_to_dynare)
     addpath(path_to_dynare);
 end
+
 dynareroot = strrep(which('dynare'),'dynare.m','');
 
 origin = pwd();
@@ -49,6 +50,7 @@ addpath([dynareroot '/kalman/'])
 addpath([dynareroot '/kalman/likelihood'])
 addpath([dynareroot '/AIM/'])
 addpath([dynareroot '/partial_information/'])
+addpath([dynareroot '/perfect-foresight-models/'])
 addpath([dynareroot '/ms-sbvar/'])
 addpath([dynareroot '/ms-sbvar/identification/'])
 addpath([dynareroot '../contrib/ms-sbvar/TZcode/MatlabFiles/'])
@@ -56,14 +58,17 @@ addpath([dynareroot '/parallel/'])
 addpath([dynareroot '/particles/src'])
 addpath([dynareroot '/gsa/'])
 addpath([dynareroot '/ep/'])
+addpath([dynareroot '/cli/'])
 addpath([dynareroot '/lmmcp/'])
+addpath([dynareroot '/optimization/'])
 addpath([dynareroot '/modules/dates/src/'])
 addpath([dynareroot '/modules/dseries/src/'])
+addpath([dynareroot '/modules/dseries/src/read'])
 addpath([dynareroot '/utilities/doc/'])
 addpath([dynareroot '/utilities/tests/src/'])
 addpath([dynareroot '/utilities/dataset/'])
 addpath([dynareroot '/utilities/general/'])
-addpath([dynareroot '/reports/'])
+addpath([dynareroot '/modules/reporting/src/'])
 
 % For functions that exist only under some Octave versions
 % or some MATLAB versions, and for which we provide some replacement functions
@@ -85,8 +90,8 @@ if isoctave
     addpath([dynareroot '/missing/ordeig'])
 end
 
-% ilu is missing in Octave
-if isoctave
+% ilu is missing in Octave < 4.0
+if isoctave && octave_ver_less_than('4.0')
     addpath([dynareroot '/missing/ilu'])
 end
 
@@ -109,49 +114,7 @@ if (isoctave && ~user_has_octave_forge_package('statistics')) ...
 end
 
 % Add path to MEX files
-if isoctave
-    addpath([dynareroot '../mex/octave/']);
-else
-    % Add win32 specific paths for Dynare Windows package
-    if strcmp(computer, 'PCWIN')
-        mexpath = [dynareroot '../mex/matlab/win32-7.5-8.4'];
-        if exist(mexpath, 'dir')
-            addpath(mexpath)
-        end
-    end
-
-    % Add win64 specific paths for Dynare Windows package
-    if strcmp(computer, 'PCWIN64')
-        if matlab_ver_less_than('7.8')
-            mexpath = [dynareroot '../mex/matlab/win64-7.5-7.7'];
-            if exist(mexpath, 'dir')
-                addpath(mexpath)
-            end
-        else
-            mexpath = [dynareroot '../mex/matlab/win64-7.8-8.4'];
-            if exist(mexpath, 'dir')
-                addpath(mexpath)
-            end
-        end
-    end
-
-    if strcmp(computer, 'MACI')
-        mexpath = [dynareroot '../mex/matlab/osx32-7.5-7.11'];
-        if exist(mexpath, 'dir')
-            addpath(mexpath)
-        end
-    end
-
-    if strcmp(computer, 'MACI64')
-        mexpath = [dynareroot '../mex/matlab/osx64'];
-        if exist(mexpath, 'dir')
-            addpath(mexpath)
-        end
-    end
-
-    % Add generic MATLAB path (with higher priority than the previous ones)
-    addpath([dynareroot '../mex/matlab/']);
-end
+add_path_to_mex_files(dynareroot);
 
 %% Set mex routine names
 mex_status = cell(1,3);
diff --git a/matlab/dynare_estimation.m b/matlab/dynare_estimation.m
index 07b8c50a65e0413823e1349a97f68e34f57db9e3..7bb49f38038222a859a2cecf17015140a96e4d82 100644
--- a/matlab/dynare_estimation.m
+++ b/matlab/dynare_estimation.m
@@ -1,17 +1,18 @@
-function dynare_estimation(var_list,dname)
-% function dynare_estimation(var_list)
+function oo_recursive_=dynare_estimation(var_list,dname)
+% function dynare_estimation(var_list, dname)
 % runs the estimation of the model
 %
 % INPUTS
 %   var_list:  selected endogenous variables vector
+%   dname:     alternative directory name
 %
 % OUTPUTS
-%   none
+%   oo_recursive_: cell array containing the results structures from recursive estimation
 %
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2003-2013 Dynare Team
+% Copyright (C) 2003-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -28,7 +29,9 @@ function dynare_estimation(var_list,dname)
 % 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_ M_ oo_recursive_
+global options_ oo_ M_ dataset_
+
+oo_recursive_={};
 
 % Test if the order of approximation is nonzero (the preprocessor tests if order is non negative).
 if isequal(options_.order,0)
@@ -53,7 +56,7 @@ nnobs = length(nobs);
 horizon = options_.forecast;
 
 if nargin<2 || ~exist(dname) || isempty(dname)
-    dname = M_.fname;
+    dname = options_.dirname;
 end
 
 M_.dname = dname;
@@ -89,20 +92,12 @@ else
     dynare_estimation_1(var_list,dname);
 end
 
-if options_.mode_compute && options_.analytic_derivation,
+if isnumeric(options_.mode_compute) && options_.mode_compute && options_.analytic_derivation,
     options_.analytic_derivation=analytic_derivation0;
 end
 
 if nnobs > 1 && horizon > 0
     mh_replic = options_.mh_replic;
-    rawdata = read_variables(options_.datafile,options_.varobs,[],options_.xls_sheet,options_.xls_range);
-    gend = options_.nobs;
-    data_plot_end_point=min(options_.first_obs+gend-1+horizon,size(rawdata,1)); %compute last observation that can be plotted
-    rawdata = rawdata(options_.first_obs:data_plot_end_point,:);
-    % Take the log of the variables if needed
-    if options_.loglinear && ~options_.logdata   % and if the data are not in logs, then...
-        rawdata = log(rawdata);
-    end
 
     endo_names = M_.endo_names;
     n_varobs = length(options_.varobs);
@@ -130,11 +125,12 @@ if nnobs > 1 && horizon > 0
             IdObs(j,1) = iobs;
         end
     end
-
+    
+    gend = dataset_.nobs;
     time_offset=min(3,gend-1); %for observables, plot 3 previous periods unless data is shorter
     k = time_offset+min(nobs(end)-nobs(1)+horizon, ...
-              size(rawdata,1)-nobs(1));
-    data2 = rawdata(end-k+1:end,:);
+              size(dataset_.data,1)-nobs(1));
+    data2 = dataset_.data(end-k+1:end,:);
     [nbplt,nr,nc,lr,lc,nstar] = pltorg(nvar);
     m = 1;
     plot_index=0;
diff --git a/matlab/dynare_estimation_1.m b/matlab/dynare_estimation_1.m
index 111a1181431a8764da2dbcdf45d14e8fdf908be6..eba52ea289a107368114de7406c269713decbc4c 100644
--- a/matlab/dynare_estimation_1.m
+++ b/matlab/dynare_estimation_1.m
@@ -12,7 +12,7 @@ function dynare_estimation_1(var_list_,dname)
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2003-2013 Dynare Team
+% Copyright (C) 2003-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -71,26 +71,18 @@ end
 if ~options_.dsge_var
     if options_.particle.status
         objective_function = str2func('non_linear_dsge_likelihood');
-        if options_.particle.filter_algorithm.sis == 1
+        if strcmpi(options_.particle.filter_algorithm, 'sis')
             options_.particle.algorithm = 'sequential_importance_particle_filter';
+        elseif strcmpi(options_.particle.filter_algorithm, 'apf')
+            options_.particle.algorithm = 'auxiliary_particle_filter';
+        elseif strcmpi(options_.particle.filter_algorithm, 'gf')
+            options_.particle.algorithm = 'gaussian_filter';
+        elseif strcmpi(options_.particle.filter_algorithm,  'gmf')
+            options_.particle.algorithm = 'gaussian_mixture_filter';
+        elseif strcmpi(options_.particle.filter_algorithm, 'cpf')
+            options_.particle.algorithm = 'conditional_particle_filter';
         else
-            if options_.particle.filter_algorithm.apf == 1
-                options_.particle.algorithm = 'auxiliary_particle_filter';
-            else
-                if options_.particle.filter_algorithm.gf == 1
-                    options_.particle.algorithm = 'gaussian_filter';
-                else
-                    if options_.particle.filter_algorithm.gmf == 1
-                        options_.particle.algorithm = 'gaussian_mixture_filter';
-                    else
-                        if options_.particle.filter_algorithm.cpf == 1
-                            options_.particle.algorithm = 'conditional_particle_filter';
-                        else
-                            error('Estimation: Unknown filter!')
-                        end
-                    end
-                end
-            end
+            error(['Estimation: Unknown filter ' options_.particle.filter_algorithm])
         end
     else
         objective_function = str2func('dsge_likelihood');
@@ -201,7 +193,7 @@ end
 
 if isequal(options_.mode_compute,0) && isempty(options_.mode_file) && options_.mh_posterior_mode_estimation==0
     if options_.smoother == 1
-        [atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,T,R,P,PK,decomp] = DsgeSmoother(xparam1,gend,data,data_index,missing_value);
+        [atT,innov,measurement_error,updated_variables,ys,trend_coeff,aK,T,R,P,PK,decomp] = DsgeSmoother(xparam1,gend,transpose(data),data_index,missing_value);
         oo_.Smoother.SteadyState = ys;
         oo_.Smoother.TrendCoeffs = trend_coeff;
         if options_.filter_covariance
@@ -239,433 +231,95 @@ end
 
 % Estimation of the posterior mode or likelihood mode
 if ~isequal(options_.mode_compute,0) && ~options_.mh_posterior_mode_estimation
-    switch options_.mode_compute
-      case 1
-        if isoctave
-            error('Option mode_compute=1 is not available under Octave')
-        elseif ~user_has_matlab_license('optimization_toolbox')
-            error('Option mode_compute=1 requires the Optimization Toolbox')
-        end
-        % Set default optimization options for fmincon.
-        optim_options = optimset('display','iter', 'LargeScale','off', 'MaxFunEvals',100000, 'TolFun',1e-8, 'TolX',1e-6);
-        if isfield(options_,'optim_opt')
-            eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']);
-        end
-        if options_.analytic_derivation,
-            optim_options = optimset(optim_options,'GradObj','on','TolX',1e-7);
-        end
-        [xparam1,fval,exitflag,output,lamdba,grad,hessian_fmincon] = ...
-            fmincon(objective_function,xparam1,[],[],[],[],bounds.lb,bounds.ub,[],optim_options,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
-        fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
-      case 2
-        error('ESTIMATION: mode_compute=2 option (Lester Ingber''s Adaptive Simulated Annealing) is no longer available')
-      case 3
-        if isoctave && ~user_has_octave_forge_package('optim')
-            error('Option mode_compute=3 requires the optim package')
-        elseif ~isoctave && ~user_has_matlab_license('optimization_toolbox')
-            error('Option mode_compute=3 requires the Optimization Toolbox')
-        end
-        % Set default optimization options for fminunc.
-        optim_options = optimset('display','iter','MaxFunEvals',100000,'TolFun',1e-8,'TolX',1e-6);
-        if isfield(options_,'optim_opt')
-            eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']);
-        end
-        if options_.analytic_derivation,
-            optim_options = optimset(optim_options,'GradObj','on');
-        end
-        if ~isoctave
-            [xparam1,fval,exitflag] = fminunc(objective_function,xparam1,optim_options,dataset_,dataset_info_,options_,M_,estim_params_,bayestopt_,bounds,oo_);
-        else
-            % Under Octave, use a wrapper, since fminunc() does not have a 4th arg
-            func = @(x) objective_function(x, dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
-            [xparam1,fval,exitflag] = fminunc(func,xparam1,optim_options);
-        end
-        fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
-      case 4
-        % Set default options.
-        H0 = 1e-4*eye(nx);
-        crit = 1e-7;
-        nit = 1000;
-        numgrad = options_.gradient_method;
-        epsilon = options_.gradient_epsilon;
-        % Change some options.
-        if isfield(options_,'optim_opt')
+    %prepare settings for newrat
+    if options_.mode_compute==5
+        %get whether outer product Hessian is requested
+        newratflag=[];
+        if ~isempty(options_.optim_opt)
             options_list = read_key_value_string(options_.optim_opt);
             for i=1:rows(options_list)
-                switch options_list{i,1}
-                  case 'MaxIter'
-                    nit = options_list{i,2};
-                  case 'InitialInverseHessian'
-                    H0 = eval(options_list{i,2});
-                  case 'TolFun'
-                    crit = options_list{i,2};
-                  case 'NumgradAlgorithm'
-                    numgrad = options_list{i,2};
-                  case 'NumgradEpsilon'
-                    epsilon = options_list{i,2};
-                  otherwise
-                    warning(['csminwel: Unknown option (' options_list{i,1} ')!'])
+                if strcmp(options_list{i,1},'Hessian')
+                    newratflag=options_list{i,2};
                 end
             end
         end
-        % Set flag for analytical gradient.
-        if options_.analytic_derivation
-            analytic_grad=1;
-        else
-            analytic_grad=[];
-        end
-        % Call csminwell.
-        [fval,xparam1,grad,hessian_csminwel,itct,fcount,retcodehat] = ...
-            csminwel1(objective_function, xparam1, H0, analytic_grad, crit, nit, numgrad, epsilon, dataset_, dataset_info, options_, M_, estim_params_, bayestopt_,bounds, oo_);
-        % Disp value at the mode.
-        fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
-      case 5
-        if isfield(options_,'hess')
-            flag = options_.hess;
-        else
-            flag = 1;
-        end
-        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_old = 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,analytic_grad,crit,nit,0,dataset_, dataset_info, options_,M_,estim_params_,bayestopt_,bounds,oo_);
-        if options_.analytic_derivation,
-            options_.analytic_derivation = ana_deriv;
-        else
-            if flag ==0,
-                options_.cova_compute = 1;
-                kalman_algo0 = options_.kalman_algo;
-                if ~((options_.kalman_algo == 2) || (options_.kalman_algo == 4)),
-                    options_.kalman_algo=2;
-                    if options_.lik_init == 3,
-                        options_.kalman_algo=4;
-                    end
-                end
-                hh = reshape(mr_hessian(0,xparam1,objective_function,1,crit,dataset_, dataset_info, options_,M_,estim_params_,bayestopt_,bounds,oo_), nx, nx);
-                options_.kalman_algo = kalman_algo0;
+            if ~isempty(newratflag) && newratflag~=0 %numerical hessian explicitly specified
+                error('newrat: analytic_derivation is incompatible with numerical Hessian.')
+            else %use default
+                newratflag=0; %exclude DYNARE numerical hessian
             end
-        end
-        parameter_names = bayestopt_.name;
-        save([M_.fname '_mode.mat'],'xparam1','hh','parameter_names');
-        fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
-      case 6
-        % Set default options
-        gmhmaxlikOptions = options_.gmhmaxlik;
-        if ~isempty(hh);
-            gmhmaxlikOptions.varinit = 'previous';
-        else
-            gmhmaxlikOptions.varinit = 'prior';
-        end
-        if isfield(options_,'optim_opt')
-            options_list = read_key_value_string(options_.optim_opt);
-            for i=1:rows(options_list)
-                switch options_list{i,1}
-                  case 'NumberOfMh'
-                    gmhmaxlikOptions.iterations = options_list{i,2};
-                  case 'ncov-mh'
-                    gmhmaxlikOptions.number = options_list{i,2};
-                  case 'nscale'
-                    gmhmaxlikOptions.nscale = options_list{i,2};
-                  case 'nclimb'
-                    gmhmaxlikOptions.nclimb = options_list{i,2};
-                  case 'InitialCovarianceMatrix'
-                    switch options_list{i,2}
-                      case 'previous'
-                        if isempty(hh)
-                            error('gmhmaxlik: No previous estimate of the Hessian matrix available!')
-                        else
-                            gmhmaxlikOptions.varinit = 'previous'
-                        end
-                      case {'prior', 'identity'}
-                        gmhmaxlikOptions.varinit = options_list{i,2};
-                      otherwise
-                        error('gmhmaxlik: Unknown value for option ''InitialCovarianceMatrix''!')
-                    end
-                  case 'AcceptanceRateTarget'
-                    gmhmaxlikOptions.target = options_list{i,2};
-                    if gmhmaxlikOptions.target>1 || gmhmaxlikOptions.target<eps
-                        error('gmhmaxlik: The value of option AcceptanceRateTarget should be a double between 0 and 1!')
-                    end
-                  otherwise
-                    warning(['gmhmaxlik: Unknown option (' options_list{i,1}  ')!'])
-                end
+        elseif ~options_.analytic_derivation 
+            if isempty(newratflag) 
+                newratflag=options_.newrat.hess; %use default numerical dynare hessian                
             end
         end
-        % Evaluate the objective function.
-        fval = feval(objective_function,xparam1,dataset_, dataset_info, options_,M_,estim_params_,bayestopt_,bounds,oo_);
-        OldMode = fval;
-        if ~exist('MeanPar','var')
-            MeanPar = xparam1;
-        end
-        switch gmhmaxlikOptions.varinit
-          case 'previous'
-            CovJump = inv(hh);
-          case 'prior'
-            % The covariance matrix is initialized with the prior
-            % covariance (a diagonal matrix) %%Except for infinite variances ;-)
-            stdev = bayestopt_.p2;
-            indx = find(isinf(stdev));
-            stdev(indx) = ones(length(indx),1)*sqrt(10);
-            vars = stdev.^2;
-            CovJump = diag(vars);
-          case 'identity'
-            vars = ones(length(bayestopt_.p2),1)*0.1;
-            CovJump = diag(vars);
-          otherwise
-            error('gmhmaxlik: This is a bug! Please contact the developers.')
-        end
-        OldPostVar = CovJump;
-        Scale = options_.mh_jscale;
-        for i=1:gmhmaxlikOptions.iterations
-            if i == 1
-                if gmhmaxlikOptions.iterations>1
-                    flag = '';
-                else
-                    flag = 'LastCall';
-                end
-                [xparam1,PostVar,Scale,PostMean] = ...
-                    gmhmaxlik(objective_function,xparam1,[bounds.lb bounds.ub],gmhmaxlikOptions,Scale,flag,MeanPar,CovJump,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
-                fval = feval(objective_function,xparam1,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
-                options_.mh_jscale = Scale;
-                mouvement = max(max(abs(PostVar-OldPostVar)));
-                skipline()
-                disp('========================================================== ')
-                disp(['   Change in the covariance matrix = ' num2str(mouvement) '.'])
-                disp(['   Mode improvement = ' num2str(abs(OldMode-fval))])
-                disp(['   New value of jscale = ' num2str(Scale)])
-                disp('========================================================== ')
-                OldMode = fval;
-            else
-                OldPostVar = PostVar;
-                if i<gmhmaxlikOptions.iterations
-                    flag = '';
-                else
-                    flag = 'LastCall';
-                end
-                [xparam1,PostVar,Scale,PostMean] = ...
-                    gmhmaxlik(objective_function,xparam1,[bounds.lb bounds.ub],...
-                              gmhmaxlikOptions,Scale,flag,PostMean,PostVar,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
-                fval = feval(objective_function,xparam1,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
-                options_.mh_jscale = Scale;
-                mouvement = max(max(abs(PostVar-OldPostVar)));
-                fval = feval(objective_function,xparam1,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
-                skipline()
-                disp('========================================================== ')
-                disp(['   Change in the covariance matrix = ' num2str(mouvement) '.'])
-                disp(['   Mode improvement = ' num2str(abs(OldMode-fval))])
-                disp(['   New value of jscale = ' num2str(Scale)])
-                disp('========================================================== ')
-                OldMode = fval;
-            end
-            hh = inv(PostVar);
-            parameter_names = bayestopt_.name;
-            save([M_.fname '_mode.mat'],'xparam1','hh','parameter_names');
-            save([M_.fname '_optimal_mh_scale_parameter.mat'],'Scale');
-            bayestopt_.jscale = ones(length(xparam1),1)*Scale;
-        end
-        skipline()
-        disp(['Optimal value of the scale parameter = ' num2str(Scale)])
-        skipline()
-        fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
-        skipline()
-        parameter_names = bayestopt_.name;
-        save([M_.fname '_mode.mat'],'xparam1','hh','parameter_names');
-      case 7
-        % Matlab's simplex (Optimization toolbox needed).
-        if isoctave && ~user_has_octave_forge_package('optim')
-            error('Option mode_compute=7 requires the optim package')
-        elseif ~isoctave && ~user_has_matlab_license('optimization_toolbox')
-            error('Option mode_compute=7 requires the Optimization Toolbox')
-        end
-        optim_options = optimset('display','iter','MaxFunEvals',1000000,'MaxIter',6000,'TolFun',1e-8,'TolX',1e-6);
-        if isfield(options_,'optim_opt')
-            eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']);
-        end
-        [xparam1,fval,exitflag] = fminsearch(objective_function,xparam1,optim_options,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
-        fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
-      case 8
-        % Dynare implementation of the simplex algorithm.
-        simplexOptions = options_.simplex;
-        if isfield(options_,'optim_opt')
-            options_list = read_key_value_string(options_.optim_opt);
-            for i=1:rows(options_list)
-                switch options_list{i,1}
-                  case 'MaxIter'
-                    simplexOptions.maxiter = options_list{i,2};
-                  case 'TolFun'
-                    simplexOptions.tolerance.f = options_list{i,2};
-                  case 'TolX'
-                    simplexOptions.tolerance.x = options_list{i,2};
-                  case 'MaxFunEvals'
-                    simplexOptions.maxfcall = options_list{i,2};
-                  case 'MaxFunEvalFactor'
-                    simplexOptions.maxfcallfactor = options_list{i,2};
-                  case 'InitialSimplexSize'
-                    simplexOptions.delta_factor = options_list{i,2};
-                  otherwise
-                    warning(['simplex: Unknown option (' options_list{i,1} ')!'])
-                end
-            end
-        end
-        [xparam1,fval,exitflag] = simplex_optimization_routine(objective_function,xparam1,simplexOptions,bayestopt_.name,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
-        fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
-      case 9
-        % Set defaults
-        H0 = 1e-4*ones(nx,1);
-        cmaesOptions = options_.cmaes;
-        % Modify defaults
-        if isfield(options_,'optim_opt')
-            options_list = read_key_value_string(options_.optim_opt);
-            for i=1:rows(options_list)
-                switch options_list{i,1}
-                  case 'MaxIter'
-                    cmaesOptions.MaxIter = options_list{i,2};
-                  case 'TolFun'
-                    cmaesOptions.TolFun = options_list{i,2};
-                  case 'TolX'
-                    cmaesOptions.TolX = options_list{i,2};
-                  case 'MaxFunEvals'
-                    cmaesOptions.MaxFunEvals = options_list{i,2};
-                  otherwise
-                    warning(['cmaes: Unknown option (' options_list{i,1}  ')!'])
-                end
-            end
-        end
-        warning('off','CMAES:NonfinitenessRange');
-        warning('off','CMAES:InitialSigma');
-        [x, fval, COUNTEVAL, STOPFLAG, OUT, BESTEVER] = cmaes(func2str(objective_function),xparam1,H0,cmaesOptions,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
-        xparam1=BESTEVER.x;
-        fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', BESTEVER.f);
-      case 10
-        simpsaOptions = options_.simpsa;
-        if isfield(options_,'optim_opt')
-            options_list = read_key_value_string(options_.optim_opt);
-            for i=1:rows(options_list)
-                switch options_list{i,1}
-                  case 'MaxIter'
-                    simpsaOptions.MAX_ITER_TOTAL = options_list{i,2};
-                  case 'TolFun'
-                    simpsaOptions.TOLFUN = options_list{i,2};
-                  case 'TolX'
-                    tolx = options_list{i,2};
-                    if tolx<0
-                        simpsaOptions = rmfield(simpsaOptions,'TOLX'); % Let simpsa choose the default.
-                    else
-                        simpsaOptions.TOLX = tolx;
-                    end
-                  case 'EndTemparature'
-                    simpsaOptions.TEMP_END = options_list{i,2};
-                  case 'MaxFunEvals'
-                    simpsaOptions.MAX_FUN_EVALS = options_list{i,2};
-                  otherwise
-                    warning(['simpsa: Unknown option (' options_list{i,1}  ')!'])
-                end
-            end
-        end
-        simpsaOptionsList = options2cell(simpsaOptions);
-        simpsaOptions = simpsaset(simpsaOptionsList{:});
-        [xparam1, fval, exitflag] = simpsa(func2str(objective_function),xparam1,bounds.lb,bounds.ub,simpsaOptions,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
-        fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
-      case 11
-         options_.cova_compute = 0 ;
-         [xparam1,stdh,lb_95,ub_95,med_param] = online_auxiliary_filter(xparam1,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_) ;
-      case 101
-        myoptions=soptions;
-        myoptions(2)=1e-6; %accuracy of argument
-        myoptions(3)=1e-6; %accuracy of function (see Solvopt p.29)
-        myoptions(5)= 1.0;
-        [xparam1,fval]=solvopt(xparam1,objective_function,[],myoptions,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
-        fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
-      case 102
-        %simulating annealing
-        %        LB=zeros(size(xparam1))-20;
-        % UB=zeros(size(xparam1))+20;
-        LB = xparam1 - 1;
-        UB = xparam1 + 1;
-        neps=10;
-        %  Set input parameters.
-        maxy=0;
-        epsilon=1.0e-9;
-        rt_=.10;
-        t=15.0;
-        ns=10;
-        nt=10;
-        maxevl=100000000;
-        idisp =1;
-        npar=length(xparam1);
-
-        disp(['size of param',num2str(length(xparam1))])
-        c=.1*ones(npar,1);
-        %*  Set input values of the input/output parameters.*
-
-        vm=1*ones(npar,1);
-        disp(['number of parameters= ' num2str(npar) 'max= '  num2str(maxy) 't=  ' num2str(t)]);
-        disp(['rt_=  '  num2str(rt_) 'eps=  '  num2str(epsilon) 'ns=  '  num2str(ns)]);
-        disp(['nt=  '  num2str(nt) 'neps= '   num2str(neps) 'maxevl=  '  num2str(maxevl)]);
-        %      disp(['iprint=   '   num2str(iprint) 'seed=   '   num2str(seed)]);
-        disp '  ';
-        disp '  ';
-        disp(['starting values(x)  ' num2str(xparam1')]);
-        disp(['initial step length(vm)  '  num2str(vm')]);
-        disp(['lower bound(lb)', 'initial conditions', 'upper bound(ub)' ]);
-        disp([LB xparam1 UB]);
-        disp(['c vector   ' num2str(c')]);
-
-        [xparam1, fval, nacc, nfcnev, nobds, ier, t, vm] = sa(objective_function,xparam1,maxy,rt_,epsilon,ns,nt ...
-                                                              ,neps,maxevl,LB,UB,c,idisp ,t,vm,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
-        fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
-      otherwise
-        if ischar(options_.mode_compute)
-            [xparam1, fval, retcode ] = feval(options_.mode_compute,objective_function,xparam1,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
-            fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
-        else
-            error(['dynare_estimation:: mode_compute = ' int2str(options_.mode_compute) ' option is unknown!'])
-        end
     end
-    if ~isequal(options_.mode_compute,6) %always already computes covariance matrix
+    
+    [xparam1, fval, exitflag, hh, options_, Scale] = dynare_minimize_objective(objective_function,xparam1,options_.mode_compute,options_,[bounds.lb bounds.ub],bayestopt_.name,bayestopt_,hh,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
+    fprintf('\nFinal value of minus the log posterior (or likelihood):%f \n', fval);
+
+    if isnumeric(options_.mode_compute) && options_.mode_compute==5 && options_.analytic_derivation==-1 %reset options changed by newrat
+            options_.analytic_derivation = options_analytic_derivation_old; %reset      
+    elseif isnumeric(options_.mode_compute) && options_.mode_compute==6 %save scaling factor
+        save([M_.fname '_optimal_mh_scale_parameter.mat'],'Scale');
+        options_.mh_jscale = Scale;
+        bayestopt_.jscale = ones(length(xparam1),1)*Scale;
+    end       
+    if ~isnumeric(options_.mode_compute) || ~isequal(options_.mode_compute,6) %always already computes covariance matrix
         if options_.cova_compute == 1 %user did not request covariance not to be computed
             if options_.analytic_derivation && strcmp(func2str(objective_function),'dsge_likelihood'),
-                ana_deriv = options_.analytic_derivation;
+                ana_deriv_old = options_.analytic_derivation;
                 options_.analytic_derivation = 2;
                 [junk1, junk2, hh] = feval(objective_function,xparam1, ...
                     dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
-                options_.analytic_derivation = ana_deriv;
-            elseif ~(isequal(options_.mode_compute,5) && flag==0), 
+                options_.analytic_derivation = ana_deriv_old;
+            elseif ~isnumeric(options_.mode_compute) || ~(isequal(options_.mode_compute,5) && newratflag~=1), 
                 % with flag==0, we force to use the hessian from outer
                 % product gradient of optimizer 5
                 hh = reshape(hessian(objective_function,xparam1, ...
                     options_.gstep,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_),nx,nx);
+            elseif isnumeric(options_.mode_compute) && isequal(options_.mode_compute,5)
+                % other numerical hessian options available with optimizer 5
+                %
+                % if newratflag == 0
+                % compute outer product gradient of optimizer 5
+                %
+                % if newratflag == 2
+                % compute 'mixed' outer product gradient of optimizer 5
+                % with diagonal elements computed with numerical second order derivatives
+                %
+                % uses univariate filters, so to get max # of available
+                % densitities for outer product gradient
+                kalman_algo0 = options_.kalman_algo;
+                compute_hessian = 1;
+                if ~((options_.kalman_algo == 2) || (options_.kalman_algo == 4)),
+                    options_.kalman_algo=2;
+                    if options_.lik_init == 3,
+                        options_.kalman_algo=4;
+                    end
+                elseif newratflag==0, % hh already contains outer product gradient with univariate filter
+                    compute_hessian = 0;                                            
+                end
+                if compute_hessian,
+                    crit = options_.newrat.tolerance.f;
+                    newratflag = newratflag>0;
+                    hh = reshape(mr_hessian(0,xparam1,objective_function,newratflag,crit,dataset_, dataset_info, options_,M_,estim_params_,bayestopt_,bounds,oo_), nx, nx);
+                end
+                options_.kalman_algo = kalman_algo0;
             end
         end
     end
     parameter_names = bayestopt_.name;
-    if options_.cova_compute
+    if options_.cova_compute || options_.mode_compute==5 || options_.mode_compute==6
         save([M_.fname '_mode.mat'],'xparam1','hh','parameter_names');
     else
         save([M_.fname '_mode.mat'],'xparam1','parameter_names');
     end
 end
 
-if options_.cova_compute == 0
-    hh = [];%NaN(length(xparam1),length(xparam1));
-end
-
 switch options_.MCMC_jumping_covariance
     case 'hessian' %Baseline
         %do nothing and use hessian from mode_compute
@@ -729,10 +383,10 @@ if ~options_.mh_posterior_mode_estimation && options_.cova_compute
 end
 
 if options_.mode_check.status == 1 && ~options_.mh_posterior_mode_estimation
-    ana_deriv = options_.analytic_derivation;
+    ana_deriv_old = options_.analytic_derivation;
     options_.analytic_derivation = 0;
     mode_check(objective_function,xparam1,hh,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,bounds,oo_);
-    options_.analytic_derivation = ana_deriv;
+    options_.analytic_derivation = ana_deriv_old;
 end
 
 oo_.posterior.optimization.mode = xparam1;
@@ -775,8 +429,6 @@ elseif ~any(bayestopt_.pshape > 0) && ~options_.mh_posterior_mode_estimation
     oo_=display_estimation_results_table(xparam1,stdh,M_,options_,estim_params_,bayestopt_,oo_,pnames,'Maximum Likelihood','mle');
 end
 
-OutputDirectoryName = CheckPath('Output',M_.dname);
-
 if np > 0
     pindx = estim_params_.param_vals(:,1);
     save([M_.fname '_params.mat'],'pindx');
@@ -805,14 +457,14 @@ if (any(bayestopt_.pshape  >0 ) && options_.mh_replic) || ...
         if options_.load_mh_file && options_.use_mh_covariance_matrix
             invhess = compute_mh_covariance_matrix;
         end
-        ana_deriv = options_.analytic_derivation;
+        ana_deriv_old = options_.analytic_derivation;
         options_.analytic_derivation = 0;
         if options_.cova_compute
             feval(options_.posterior_sampling_method,objective_function,options_.proposal_distribution,xparam1,invhess,bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_);
         else
             error('I Cannot start the MCMC because the Hessian of the posterior kernel at the mode was not computed.')
         end
-        options_.analytic_derivation = ana_deriv;
+        options_.analytic_derivation = ana_deriv_old;
     end
     if options_.mh_posterior_mode_estimation
         CutSample(M_, options_, estim_params_);
diff --git a/matlab/dynare_estimation_init.m b/matlab/dynare_estimation_init.m
index 454375def536e073143fbde73b86569eca04b52d..eab7b8b7e1c2abfcba31630ef90b0cc0447fc9f9 100644
--- a/matlab/dynare_estimation_init.m
+++ b/matlab/dynare_estimation_init.m
@@ -321,6 +321,8 @@ if isempty(estim_params_)% If estim_params_ is empty (e.g. when running the smoo
     estim_params_.ncx = 0;
     estim_params_.ncn = 0;
     estim_params_.np = 0;
+    bounds.lb = [];
+    bounds.ub = [];
 end
 
 % storing prior parameters in results
@@ -440,6 +442,9 @@ else
 end;
 
 if options_.analytic_derivation,
+    if options_.lik_init == 3,
+        error('analytic derivation is incompatible with diffuse filter')
+    end
     options_.analytic_derivation = 1;
     if ~(exist('sylvester3','file')==2),
         dynareroot = strrep(which('dynare'),'dynare.m','');
diff --git a/matlab/dynare_sensitivity.m b/matlab/dynare_sensitivity.m
index 9d4a5085d398682c04c567681738e3a173f89762..0a4aa0035cd65a395d41e258dadace2bb4c58c2e 100644
--- a/matlab/dynare_sensitivity.m
+++ b/matlab/dynare_sensitivity.m
@@ -163,6 +163,11 @@ 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',1.e-5);
 
+if options_gsa.neighborhood_width,
+    options_gsa.pprior=0;
+    options_gsa.ppost=0;
+end
+
 if options_gsa.redform && options_gsa.neighborhood_width==0 && isempty(options_gsa.threshold_redform),
     options_gsa.pprior=1;
     options_gsa.ppost=0;
diff --git a/matlab/dynare_solve.m b/matlab/dynare_solve.m
index a4b9db9ab8697642f9d759be04770aad7b75a651..4cedaf5f9bed347116c6a93951f2fd3dee0f3d78 100644
--- a/matlab/dynare_solve.m
+++ b/matlab/dynare_solve.m
@@ -1,12 +1,11 @@
-function [x,info] = dynare_solve(func,x,jacobian_flag,varargin)
-% function [x,info] = dynare_solve(func,x,jacobian_flag,varargin)
+function [x,info] = dynare_solve(func,x,options,varargin)
+% function [x,info] = dynare_solve(func,x,options,varargin)
 % proposes different solvers
 %
 % INPUTS
 %    func:             name of the function to be solved
 %    x:                guess values
-%    jacobian_flag=1:  jacobian given by the 'func' function
-%    jacobian_flag=0:  jacobian obtained numerically
+%    options:          struct of Dynare options
 %    varargin:         list of arguments following jacobian_flag
 %
 % OUTPUTS
@@ -16,7 +15,7 @@ function [x,info] = dynare_solve(func,x,jacobian_flag,varargin)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2001-2014 Dynare Team
+% Copyright (C) 2001-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -33,9 +32,18 @@ function [x,info] = dynare_solve(func,x,jacobian_flag,varargin)
 % 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_
+% jacobian_flag=1:  jacobian given by the 'func' function
+% jacobian_flag=0:  jacobian obtained numerically
+jacobian_flag = options.jacobian_flag;
+
+% Set tolerance parameter depending the the caller function.
+stack = dbstack;
+if strcmp(stack(2).file,'simulation_core.m')
+    tolf = options.dynatol.f;
+else
+    tolf = options.solve_tolf;
+end
 
-tolf = options_.solve_tolf ;
 info = 0;
 nn = size(x,1);
 
@@ -72,7 +80,7 @@ if max(abs(fvec)) < tolf
     return ;
 end
 
-if options_.solve_algo == 0
+if options.solve_algo == 0
     if ~isoctave
         if ~user_has_matlab_license('optimization_toolbox')
             error('You can''t use solve_algo=0 since you don''t have MATLAB''s Optimization Toolbox')
@@ -80,7 +88,7 @@ if options_.solve_algo == 0
     end
     options=optimset('fsolve');
     options.MaxFunEvals = 50000;
-    options.MaxIter = options_.steady.maxit;
+    options.MaxIter = options.steady.maxit;
     options.TolFun = tolf;
     options.Display = 'iter';
     if jacobian_flag
@@ -108,17 +116,17 @@ if options_.solve_algo == 0
     else
         info = 1;
     end
-elseif options_.solve_algo == 1
-        [x,info]=solve1(func,x,1:nn,1:nn,jacobian_flag,options_.gstep, ...
-                    tolf,options_.solve_tolx, ...
-                    options_.steady.maxit,options_.debug,varargin{:});
-elseif options_.solve_algo == 9
-        [x,info]=trust_region(func,x,1:nn,1:nn,jacobian_flag,options_.gstep, ...
-                    tolf,options_.solve_tolx, ...
-                    options_.steady.maxit,options_.debug,varargin{:});
-elseif options_.solve_algo == 2 || options_.solve_algo == 4
+elseif options.solve_algo == 1
+        [x,info]=solve1(func,x,1:nn,1:nn,jacobian_flag,options.gstep, ...
+                    tolf,options.solve_tolx, ...
+                    options.steady.maxit,options.debug,varargin{:});
+elseif options.solve_algo == 9
+        [x,info]=trust_region(func,x,1:nn,1:nn,jacobian_flag,options.gstep, ...
+                    tolf,options.solve_tolx, ...
+                    options.steady.maxit,options.debug,varargin{:});
+elseif options.solve_algo == 2 || options.solve_algo == 4
 
-    if options_.solve_algo == 2
+    if options.solve_algo == 2
         solver = @solve1;
     else
         solver = @trust_region;
@@ -126,7 +134,7 @@ elseif options_.solve_algo == 2 || options_.solve_algo == 4
 
     if ~jacobian_flag
         fjac = zeros(nn,nn) ;
-        dh = max(abs(x),options_.gstep(1)*ones(nn,1))*eps^(1/3);
+        dh = max(abs(x),options.gstep(1)*ones(nn,1))*eps^(1/3);
         for j = 1:nn
             xdh = x ;
             xdh(j) = xdh(j)+dh(j) ;
@@ -136,18 +144,18 @@ elseif options_.solve_algo == 2 || options_.solve_algo == 4
 
     [j1,j2,r,s] = dmperm(fjac);
 
-    if options_.debug
+    if options.debug
         disp(['DYNARE_SOLVE (solve_algo=2|4): number of blocks = ' num2str(length(r))]);
     end
 
     for i=length(r)-1:-1:1
-        if options_.debug
+        if options.debug
             disp(['DYNARE_SOLVE (solve_algo=2|4): solving block ' num2str(i) ', of size ' num2str(r(i+1)-r(i)) ]);
         end
         [x,info]=solver(func,x,j1(r(i):r(i+1)-1),j2(r(i):r(i+1)-1),jacobian_flag, ...
-                        options_.gstep, ...
-                        tolf,options_.solve_tolx, ...
-                        options_.steady.maxit,options_.debug,varargin{:});
+                        options.gstep, ...
+                        tolf,options.solve_tolx, ...
+                        options.steady.maxit,options.debug,varargin{:});
         if info
             return
         end
@@ -155,17 +163,17 @@ elseif options_.solve_algo == 2 || options_.solve_algo == 4
     fvec = feval(func,x,varargin{:});
     if max(abs(fvec)) > tolf
         [x,info]=solver(func,x,1:nn,1:nn,jacobian_flag, ...
-                        options_.gstep, tolf,options_.solve_tolx, ...
-                        options_.steady.maxit,options_.debug,varargin{:});
+                        options.gstep, tolf,options.solve_tolx, ...
+                        options.steady.maxit,options.debug,varargin{:});
     end
-elseif options_.solve_algo == 3
+elseif options.solve_algo == 3
     if jacobian_flag
         [x,info] = csolve(func,x,func,1e-6,500,varargin{:});
     else
         [x,info] = csolve(func,x,[],1e-6,500,varargin{:});
     end
-elseif options_.solve_algo == 10
-    olmmcp = options_.lmmcp;
+elseif options.solve_algo == 10
+    olmmcp = options.lmmcp;
     [x,fval,exitflag] = lmmcp(func,x,olmmcp.lb,olmmcp.ub,olmmcp,varargin{:});
     if exitflag == 1
         info = 0;
diff --git a/matlab/dynare_solve_block_or_bytecode.m b/matlab/dynare_solve_block_or_bytecode.m
index ce82bc5dfd547748e854c0ce22598781bd27e62e..1032d0921ecdc0246beb172fc23dbecdeadac6f9 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-2012 Dynare Team
+% Copyright (C) 2010-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -26,7 +26,7 @@ if options.block && ~options.bytecode
             if options.solve_algo <= 4
                 [y, check] = dynare_solve('block_mfs_steadystate', ...
                                           ss(M.block_structure_stat.block(b).variable), ...
-                                          options.jacobian_flag, b, ss, exo, params, M);
+                                          options, b, ss, exo, params, M);
                 if check ~= 0
                     %                    error(['STEADY: convergence
                     %                    problems in block ' int2str(b)])
@@ -62,18 +62,20 @@ elseif options.bytecode
             if M.block_structure_stat.block(b).Simulation_Type ~= 1 && ...
                M.block_structure_stat.block(b).Simulation_Type ~= 2
                 [y, check] = dynare_solve('block_bytecode_mfs_steadystate', ...
-                                          x(M.block_structure_stat.block(b).variable), ...
-                                          options.jacobian_flag, b, x, exo, params, M);
+                                          x(M.block_structure_stat ...
+                                            .block(b).variable), ...
+                                          options, b, x, exo, params, M);
                 if check
-                    %                    error(['STEADY: convergence
-                    %                    problems in block ' int2str(b)])
+                    %                    error(['STEADY: convergence problems in block '
+                    %                    int2str(b)])
                     info = 1;
                     return
                 end
                 x(M.block_structure_stat.block(b).variable) = y;
             else
                 [chk, nulldev, nulldev1, x] = bytecode( x, exo, params, ...
-                                                        x, 1, x, 'evaluate', 'static', ['block = ' int2str(b)]);
+                                                        x, 1, x, 'evaluate', 'static', ...
+                                                        ['block = ' int2str(b)]);
                 if chk
                     info = 1;
                     return
@@ -81,9 +83,8 @@ elseif options.bytecode
             end;
         end
     else
-        [x, check] = dynare_solve('bytecode_steadystate', ...
-                                  y, ...
-                                  options.jacobian_flag, exo, params);
+        [x, check] = dynare_solve('bytecode_steadystate', y, ...
+                                  options, exo, params);
         if check
             %            error('STEADY: convergence problems')
             info = 1;
diff --git a/matlab/dynasave.m b/matlab/dynasave.m
index 748b2e789e527db7d0a0859bc8535f4cb03e3158..f2cc991ca02d60cd5566892ad9f71fab90aba210 100644
--- a/matlab/dynasave.m
+++ b/matlab/dynasave.m
@@ -35,6 +35,10 @@ if size(var_list,1) == 0
     var_list = M_.endo_names(1:M_.orig_endo_nbr, :);
 end
 
+if ~isfield(oo_,'endo_simul') || isempty(oo_.endo_simul)
+    error('dynasave:: The results structure does not contain simulated series. Maybe the periods option has not been set.')
+end
+
 n = size(var_list,1);
 ivar=zeros(n,1);
 for i=1:n
diff --git a/matlab/dyntable.m b/matlab/dyntable.m
index 181d7e3ab35c225ffc5f34a58034914f2046d6b6..2330dc3babdbf56ad3f855e4587270650e464c88 100644
--- a/matlab/dyntable.m
+++ b/matlab/dyntable.m
@@ -1,7 +1,16 @@
-function dyntable(title,headers,labels,values,label_width,val_width, ...
-                  val_precis)
-
-% Copyright (C) 2002-2013 Dynare Team
+function dyntable(title,headers,labels,values,label_width,val_width,val_precis)
+% function dyntable(title,headers,labels,values,label_width,val_width,val_precis)
+% Inputs:
+%   title       [string]            Table title
+%   headers     [n by nchar]        character array of labels for header row
+%   labels      [n by nchar]        character array of labels for label column
+%   values      [matrix]            matrix of values to display
+%   label_width [scalar]            Width of the label
+%   val_width   [scalar]            Width of value column    
+%   val_precis  [integer]           precision of displayed values
+% 
+% 
+% Copyright (C) 2002-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -24,48 +33,46 @@ if options_.noprint
     return
 end
 
-%label_width = max(size(deblank(char(headers(1,:),labels)),2)+2, ...
-%                  label_width);
-label_width = max(size(deblank(char(headers(1,:),labels)),2))+2;
-
-label_fmt = sprintf('%%-%ds',label_width);
+%% get width of label column
+if ~isempty(label_width) 
+    label_width = max(size(deblank(char(headers(1,:),labels)),2)+2, ...
+                     label_width);
+else %use default length
+    label_width = max(size(deblank(char(headers(1,:),labels)),2))+2;
+end
+label_format_leftbound  = sprintf('%%-%ds',label_width);
 
+%% get width of label column
 if all(~isfinite(values))
     values_length = 4;
 else
     values_length = max(ceil(max(max(log10(abs(values(isfinite(values))))))),1)+val_precis+1;
 end
-if any(values) < 0
+if any(values) < 0 %add one character for minus sign
     values_length = values_length+1;
 end
-headers_length = max(size(deblank(headers(2:end,:)),2));
-%val_width = max(values_length,val_width);
-val_width = max(headers_length,values_length)+2;
-%header_fmt = sprintf('%%-%ds',val_width);
-val_fmt = sprintf('%%%d.%df',val_width,val_precis);
 
-headers_offset = 0;
-values_offset = 0;
-if headers_length > values_length
-    %    values_offset = ceil((val_width-values_length)/2);
+%% get width of header strings 
+headers_length = max(size(deblank(headers(2:end,:)),2));
+if ~isempty(val_width)
+    val_width = max(max(headers_length,values_length)+2,val_width);
+else
+    val_width = max(headers_length,values_length)+2;
 end
+value_format  = sprintf('%%%d.%df',val_width,val_precis);
+header_string_format  = sprintf('%%%ds',val_width);
 
 if length(title) > 0
-    disp(sprintf('\n\n%s\n',title));
+    fprintf('\n\n%s\n',title);
 end
+%Create and print header string
 if length(headers) > 0
-    hh = sprintf(label_fmt,headers(1,:));
+    hh = sprintf(label_format_leftbound ,deblank(headers(1,:)));
     for i=2:size(headers,1)
-        hla = size(deblank(headers(i,:)),2);
-        hlb = ceil((val_width - hla)/2);
-        hla = val_width - hla - hlb;
-        hh  = [hh char(32*ones(1,hlb)) deblank(headers(i,:)) ...
-              char(32*ones(1,hla))];
+        hh  = [hh sprintf(header_string_format,deblank(headers(i,:)))];
     end
     disp(hh);
 end
 for i=1:size(values,1)
-    disp([sprintf(label_fmt,deblank(labels(i,:))) char(32*ones(1,values_offset)) sprintf(val_fmt,values(i,:))]);
-end
-
-% 10/30/02 MJ
\ No newline at end of file
+    disp([sprintf(label_format_leftbound ,deblank(labels(i,:))) sprintf(value_format ,values(i,:))]);
+end
\ No newline at end of file
diff --git a/matlab/ep/extended_path.m b/matlab/ep/extended_path.m
index c17a66c21884b134fb1567420c1f68e684a0144f..bdfbf754e74e4179e08f0c824511d668780ef18f 100644
--- a/matlab/ep/extended_path.m
+++ b/matlab/ep/extended_path.m
@@ -14,7 +14,7 @@ function ts = extended_path(initial_conditions,sample_size)
 %
 % SPECIAL REQUIREMENTS
 
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -42,7 +42,6 @@ options_.simul.maxit = options_.ep.maxit;
 pfm = setup_stochastic_perfect_foresight_model_solver(M_,options_,oo_);
 
 exo_nbr = M_.exo_nbr;
-periods = options_.periods;
 ep = options_.ep;
 steady_state = oo_.steady_state;
 dynatol = options_.dynatol;
@@ -86,6 +85,8 @@ end
 options_.minimal_solving_period = 100;%options_.ep.periods;
 
 % Initialize the exogenous variables.
+% !!!!!!!! Needs to fixed
+options_.periods = periods;
 make_ex_;
 
 % Initialize the endogenous variables.
@@ -116,7 +117,7 @@ bytecode_flag = options_.ep.use_bytecode;
 % Simulate shocks.
 switch options_.ep.innovation_distribution
   case 'gaussian'
-      oo_.ep.shocks = transpose(transpose(covariance_matrix_upper_cholesky)*randn(effective_number_of_shocks,sample_size));
+    oo_.ep.shocks = transpose(transpose(covariance_matrix_upper_cholesky)*randn(effective_number_of_shocks,sample_size));
   otherwise
     error(['extended_path:: ' options_.ep.innovation_distribution ' distribution for the structural innovations is not (yet) implemented!'])
 end
@@ -148,7 +149,7 @@ if options_.ep.stochastic.order > 0
     pfm.nnodes = nnodes;
 
     % compute number of blocks
-    [block_nbr,pfm.world_nbr] = get_block_world_nbr(options_.ep.stochastic.algo,nnodes,options_.ep.ut.k,options_.ep.periods);
+    [block_nbr,pfm.world_nbr] = get_block_world_nbr(options_.ep.stochastic.algo,nnodes,options_.ep.stochastic.order,options_.ep.periods);
 else
     block_nbr = options_.ep.periods
 end
@@ -175,217 +176,51 @@ while (t<sample_size)
     end
     % Set period index.
     t = t+1;
-    shocks = oo_.ep.shocks(t,:);
-    % Put it in oo_.exo_simul (second line).
-    oo_.exo_simul(2,positive_var_indx) = shocks;
-    periods1 = periods;
-    exo_simul_1 = zeros(periods1+2,exo_nbr);
-    exo_simul_1(2,:) = oo_.exo_simul(2,:);
-    pfm1 = pfm;
-    info_convergence = 0;
+    % Put shocks in oo_.exo_simul (second line).
+    exo_simul_1 = zeros(periods+2,exo_nbr);
+    exo_simul_1(2,positive_var_indx) = oo_.exo_simul(2,positive_var_indx) + oo_.ep.shocks(t,:);
     if ep.init% Compute first order solution (Perturbation)...
-        ex = zeros(size(endo_simul_1,2),size(exo_simul_1,2));
-        ex(1:size(exo_simul_1,1),:) = exo_simul_1;
-        exo_simul_1 = ex;
         initial_path = simult_(initial_conditions,dr,exo_simul_1(2:end,:),1);
         endo_simul_1(:,1:end-1) = initial_path(:,1:end-1)*ep.init+endo_simul_1(:,1:end-1)*(1-ep.init);
     else
         if t==1
-            endo_simul_1 = repmat(steady_state,1,periods1+2);
+            endo_simul_1 = repmat(steady_state,1,periods+2);
         end
     end
     % Solve a perfect foresight model.
-    increase_periods = 0;
     % Keep a copy of endo_simul_1
     endo_simul = endo_simul_1;
     if verbosity
         save ep_test_1 endo_simul_1 exo_simul_1
     end
-    while 1
-        if ~increase_periods
-            if bytecode_flag && ~options_.ep.stochastic.order
-                [flag,tmp] = bytecode('dynamic',endo_simul_1,exo_simul_1);
-            else
-                flag = 1;
-            end
-            if flag
-                if options_.ep.stochastic.order == 0
-                    [flag,tmp,err] = solve_perfect_foresight_model(endo_simul_1,exo_simul_1,pfm1);
-                else
-                    switch(options_.ep.stochastic.algo)
-                        case 0
-                        [flag,tmp] = ...
-                            solve_stochastic_perfect_foresight_model(endo_simul_1,exo_simul_1,pfm1,options_.ep.stochastic.quadrature.nodes,options_.ep.stochastic.order);
-                        case 1
-                          [flag,tmp] = ...
-                              solve_stochastic_perfect_foresight_model_1(endo_simul_1,exo_simul_1,options_,pfm1,options_.ep.stochastic.order);
-                    end
-                end
-            end
-            info_convergence = ~flag;
-        end
-        if verbosity
-            if info_convergence
-                if t<10
-                    disp(['Time:    ' int2str(t)  '. Convergence of the perfect foresight model solver!'])
-                elseif t<100
-                    disp(['Time:   ' int2str(t)  '. Convergence of the perfect foresight model solver!'])
-                elseif t<1000
-                    disp(['Time:  ' int2str(t)  '. Convergence of the perfect foresight model solver!'])
-                else
-                    disp(['Time: ' int2str(t)  '. Convergence of the perfect foresight model solver!'])
-                end
-            else
-                if t<10
-                    disp(['Time:    ' int2str(t)  '. No convergence of the perfect foresight model solver!'])
-                elseif t<100
-                    disp(['Time:   ' int2str(t)  '. No convergence of the perfect foresight model solver!'])
-                elseif t<1000
-                    disp(['Time:  ' int2str(t)  '. No convergence of the perfect foresight model solver!'])
-                else
-                    disp(['Time: ' int2str(t)  '. No convergence of the perfect foresight model solver!'])
-                end
-            end
-        end
-        if do_not_check_stability_flag
-            % Exit from the while loop.
-            endo_simul_1 = tmp;
-            break
+    if bytecode_flag && ~options_.ep.stochastic.order
+        [flag,tmp] = bytecode('dynamic',endo_simul_1,exo_simul_1, M_.params, endo_simul_1, options_.ep.periods);
+    else
+        flag = 1;
+    end
+    if flag
+        if options_.ep.stochastic.order == 0
+            [flag,tmp,err] = solve_perfect_foresight_model(endo_simul_1,exo_simul_1,pfm);
         else
-            % Test if periods is big enough.
-            % Increase the number of periods.
-            periods1 = periods1 + ep.step;
-            pfm1.periods = periods1;
-            pfm1.i_upd = pfm1.ny+(1:pfm1.periods*pfm1.ny);
-            % Increment the counter.
-            increase_periods = increase_periods + 1;
-            if verbosity
-                if t<10
-                    disp(['Time:    ' int2str(t)  '. I increase the number of periods to ' int2str(periods1) '.'])
-                elseif t<100
-                    disp(['Time:   ' int2str(t) '. I increase the number of periods to ' int2str(periods1) '.'])
-                elseif t<1000
-                    disp(['Time:  ' int2str(t)  '. I increase the number of periods to ' int2str(periods1) '.'])
-                else
-                    disp(['Time: ' int2str(t)  '. I increase the number of periods to ' int2str(periods1) '.'])
-                end
-            end
-            if info_convergence
-                % If the previous call to the perfect foresight model solver exited
-                % announcing that the routine converged, adapt the size of endo_simul_1
-                % and exo_simul_1.
-                endo_simul_1 = [ tmp , repmat(steady_state,1,ep.step) ];
-                exo_simul_1  = [ exo_simul_1 ; zeros(ep.step,exo_nbr)];
-                tmp_old = tmp;
-            else
-                % If the previous call to the perfect foresight model solver exited
-                % announcing that the routine did not converge, then tmp=1... Maybe
-                % should change that, because in some circonstances it may usefull
-                % to know where the routine did stop, even if convergence was not
-                % achieved.
-                endo_simul_1 = [ endo_simul_1 , repmat(steady_state,1,ep.step) ];
-                exo_simul_1  = [ exo_simul_1 ; zeros(ep.step,exo_nbr)];
-            end
-            % Solve the perfect foresight model with an increased number of periods.
-            if bytecode_flag && ~options_.ep.stochastic.order
-                [flag,tmp] = bytecode('dynamic',endo_simul_1,exo_simul_1);
-            else
-                flag = 1;
+            switch(options_.ep.stochastic.algo)
+              case 0
+                [flag,tmp] = ...
+                    solve_stochastic_perfect_foresight_model(endo_simul_1,exo_simul_1,pfm,options_.ep.stochastic.quadrature.nodes,options_.ep.stochastic.order);
+              case 1
+                [flag,tmp] = ...
+                    solve_stochastic_perfect_foresight_model_1(endo_simul_1,exo_simul_1,options_,pfm,options_.ep.stochastic.order);
             end
-            if flag
-                if options_.ep.stochastic.order == 0
-                    [flag,tmp,err] = solve_perfect_foresight_model(endo_simul_1,exo_simul_1,pfm1);
-                else
-                    switch(options_.ep.stochastic.algo)
-                        case 0
-                        [flag,tmp] = ...
-                            solve_stochastic_perfect_foresight_model(endo_simul_1,exo_simul_1,pfm1,options_.ep.stochastic.quadrature.nodes,options_.ep.stochastic.order);
-                        case 1
-                          [flag,tmp] = ...
-                              solve_stochastic_perfect_foresight_model_1(endo_simul_1,exo_simul_1,options_,pfm1,options_.ep.stochastic.order);
-                    end
-                end
-            end
-            info_convergence = ~flag;
-            if info_convergence
-                % If the solver achieved convergence, check that simulated paths did not
-                % change during the first periods.
-                % Compute the maximum deviation between old path and new path over the
-                % first periods
-                delta = max(max(abs(tmp(:,2)-tmp_old(:,2))));
-                if delta < dynatol.x
-                    % If the maximum deviation is close enough to zero, reset the number
-                    % of periods to ep.periods
-                    periods1 = ep.periods;
-                    pfm1.periods = periods1;
-                    pfm1.i_upd = pfm1.ny+(1:pfm1.periods*pfm1.ny);
-                    % Cut exo_simul_1 and endo_simul_1 consistently with the resetted
-                    % number of periods and exit from the while loop.
-                    exo_simul_1 = exo_simul_1(1:(periods1+2),:);
-                    endo_simul_1 = endo_simul_1(:,1:(periods1+2));
-                    break
-                end
-            else
-                % The solver did not converge... Try to solve the model again with a bigger
-                % number of periods, except if the number of periods has been increased more
-                % than 10 times.
-                if increase_periods==10;
-                    if verbosity
-                        if t<10
-                            disp(['Time:    ' int2str(t)  '. Even with ' int2str(periods1) ', I am not able to solve the perfect foresight model. Use homotopy instead...'])
-                        elseif t<100
-                            disp(['Time:   ' int2str(t)  '. Even with ' int2str(periods1) ', I am not able to solve the perfect foresight model. Use homotopy instead...'])
-                        elseif t<1000
-                            disp(['Time:  ' int2str(t)  '. Even with ' int2str(periods1) ', I am not able to solve the perfect foresight model. Use homotopy instead...'])
-                        else
-                            disp(['Time: ' int2str(t)  '. Even with ' int2str(periods1) ', I am not able to solve the perfect foresight model. Use homotopy instead...'])
-                        end
-                    end
-                    % Exit from the while loop.
-                    break
-                end
-            end% if info_convergence
-        end
-    end% while
-    if ~info_convergence && ep.homotopic_steps % If exited from the while loop without achieving
-                                               % convergence use an homotopic approach
-        if ~do_not_check_stability_flag
-            periods1 = ep.periods;
-            pfm1.periods = periods1;
-            pfm1.i_upd = i_upd;
-            exo_simul_1 = exo_simul_1(1:(periods1+2),:);
-            endo_simul_1 = endo_simul_1(:,1:(periods1+2));
         end
-        [INFO,tmp] = homotopic_steps(endo_simul,exo_simul_1,.5,.01,pfm1);
-        if isstruct(INFO)
-            info_convergence = INFO.convergence;
-        else
-            info_convergence = 0;
-        end
-        if ~info_convergence
-            [INFO,tmp] = homotopic_steps(endo_simul,exo_simul_1,0,.01,pfm1);
-            if isstruct(INFO)
-                info_convergence = INFO.convergence;
-            else
-                info_convergence = 0;
-            end
-            if ~info_convergence
-                disp('Homotopy:: No convergence of the perfect foresight model solver!')
-                error('I am not able to simulate this model!');
-            else
-                endo_simul_1 = tmp;
-                if verbosity && info_convergence
-                    disp('Homotopy:: Convergence of the perfect foresight model solver!')
-                end
-            end
+    end
+    info_convergence = ~flag;
+    if verbosity
+        if info_convergence
+                disp(['Time: ' int2str(t)  '. Convergence of the perfect foresight model solver!'])
         else
-            info_convergence = 1;
-            endo_simul_1 = tmp;
-            if verbosity && info_convergence
-                disp('Homotopy:: Convergence of the perfect foresight model solver!')
-            end
+                disp(['Time: ' int2str(t)  '. No convergence of the perfect foresight model solver!'])
         end
     end
+    endo_simul_1 = tmp;
     if info_convergence
         % Save results of the perfect foresight model solver.
         time_series(:,tsimul) = endo_simul_1(:,2);
@@ -397,7 +232,7 @@ while (t<sample_size)
         oo_.ep.failures.periods = [oo_.ep.failures.periods t];
         oo_.ep.failures.previous_period = [oo_.ep.failures.previous_period  endo_simul_1(:,1)];
         oo_.ep.failures.shocks = [oo_.ep.failures.shocks  shocks];
-        endo_simul_1 = repmat(steady_state,1,periods1+2);
+        endo_simul_1 = repmat(steady_state,1,periods+2);
         endo_simul_1(:,1) = time_series(:,tsimul-1);
     end
 end% (while) loop over t
@@ -417,4 +252,4 @@ else
     dyn2vec;
 end
 
- assignin('base', 'Simulated_time_series', ts);
\ No newline at end of file
+ assignin('base', 'Simulated_time_series', ts);
diff --git a/matlab/ep/setup_stochastic_perfect_foresight_model_solver.m b/matlab/ep/setup_stochastic_perfect_foresight_model_solver.m
index f6c455d3292353f50f50c3654c6e24ee76a59b4a..3df0a788b6c45fe99b970d9c5b7c39561d5b2ce0 100644
--- a/matlab/ep/setup_stochastic_perfect_foresight_model_solver.m
+++ b/matlab/ep/setup_stochastic_perfect_foresight_model_solver.m
@@ -68,4 +68,5 @@ pfm.dynamic_model = str2func([DynareModel.fname,'_dynamic']);
 pfm.verbose = DynareOptions.ep.verbosity;
 pfm.maxit_ = DynareOptions.simul.maxit;
 pfm.tolerance = DynareOptions.dynatol.f;
+pfm.use_bytecode = DynareOptions.ep.use_bytecode ;
 
diff --git a/matlab/ep/solve_stochastic_perfect_foresight_model.m b/matlab/ep/solve_stochastic_perfect_foresight_model.m
index 683a6cec6d216d295c7adce1c60713d3f2ec8ae2..ab13e3043ac6c89cd30f80aff549f6fb7f3b57b6 100644
--- a/matlab/ep/solve_stochastic_perfect_foresight_model.m
+++ b/matlab/ep/solve_stochastic_perfect_foresight_model.m
@@ -1,6 +1,6 @@
 function [flag,endo_simul,err] = solve_stochastic_perfect_foresight_model(endo_simul,exo_simul,pfm,nnodes,order)
 
-% Copyright (C) 2012-2013 Dynare Team
+% Copyright (C) 2012-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -177,7 +177,7 @@ function [flag,endo_simul,err] = solve_stochastic_perfect_foresight_model(endo_s
             i_cols_f = i_cols_f + ny;
         end
         nzA = cell(periods,world_nbr);
-        parfor j=1:world_nbr
+        for j=1:world_nbr
             i_rows_y = find(lead_lag_incidence')+(order+1)*ny;
             offset_c = ny*(sum(nnodes.^(0:order-1),2)+j-1);
             offset_r = (j-1)*ny;
@@ -232,4 +232,4 @@ function [flag,endo_simul,err] = solve_stochastic_perfect_foresight_model(endo_s
     end
     if verbose
         disp (['-----------------------------------------------------']) ;
-    end
\ No newline at end of file
+    end
diff --git a/matlab/ep/solve_stochastic_perfect_foresight_model_1.m b/matlab/ep/solve_stochastic_perfect_foresight_model_1.m
index 56249d3c6758c88754d94bbe8b625bdefc83d1a7..e9aa577aaccd2ebf7d53e38b252ab0d0f52763d2 100644
--- a/matlab/ep/solve_stochastic_perfect_foresight_model_1.m
+++ b/matlab/ep/solve_stochastic_perfect_foresight_model_1.m
@@ -146,7 +146,7 @@ y = repmat(steady_state,block_nbr,1);
 old_options = options_;
 options_.solve_algo = options_.ep.solve_algo;
 options_.steady.maxit = options_.ep.maxit;
-[y,info] = dynare_solve(@ep_problem_2,y,1,exo_simul,pfm);
+[y,info] = dynare_solve(@ep_problem_2,y,options_,exo_simul,pfm);
 options_ = old_options;
 if info
     flag = 1;
diff --git a/matlab/evaluate_steady_state.m b/matlab/evaluate_steady_state.m
index c55d570124a70593cffcaba6419c8f4273a55e4c..208f665bff0e7be2ced3c85ff7b3a2e7926894f8 100644
--- a/matlab/evaluate_steady_state.m
+++ b/matlab/evaluate_steady_state.m
@@ -193,8 +193,7 @@ function [ys,params,info] = evaluate_steady_state(ys_init,M,options,oo,steadysta
             % non linear model
             [ys,check] = dynare_solve([M.fname '_static'],...
                                       ys_init,...
-                                      options.jacobian_flag, ...
-                                      exo_ss, params);
+                                      options, exo_ss, params);
         else
             % linear model
             fh_static = str2func([M.fname '_static']);
diff --git a/matlab/evaluate_steady_state_file.m b/matlab/evaluate_steady_state_file.m
index 0ad19bee95695c4aa706ab0868764948c314baa4..12d361a371d040c310da496f3bcdc79161049c18 100644
--- a/matlab/evaluate_steady_state_file.m
+++ b/matlab/evaluate_steady_state_file.m
@@ -63,7 +63,7 @@ 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
     else
-        updated_params_flag = 0
+        updated_params_flag = 0;
     end
 
     h_set_auxiliary_variables = str2func([M.fname '_set_auxiliary_variables']);
@@ -117,8 +117,7 @@ function [ys,params,info] = evaluate_steady_state_file(ys_init,exo_ss,M,options)
         end
         [ys,check] = dynare_solve('restricted_steadystate',...
                                   ys(indv),...
-                                  options.jacobian_flag, ...
-                                  exo_ss,indv);
+                                  options, exo_ss,indv);
     end
 
     
diff --git a/matlab/forcst_unc.m b/matlab/forcst_unc.m
deleted file mode 100644
index 139b09f915402fd67270c3d5f7c744af1e04bed0..0000000000000000000000000000000000000000
--- a/matlab/forcst_unc.m
+++ /dev/null
@@ -1,152 +0,0 @@
-function forcst_unc(y0,var_list)
-% function [mean,intval1,intval2]=forcst_unc(y0,var_list)
-% computes forecasts with parameter uncertainty
-%
-% INPUTS
-%   y0: matrix of initial values
-%   var_list: list of variables to be forecasted
-%
-% OUTPUTS
-%   none
-%
-% ALGORITHM
-%   uses antithetic draws for the shocks
-%
-% SPECIAL REQUIREMENTS
-%   None.
-
-% Copyright (C) 2006-2013 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_ estim_params_ bayestopt_
-
-% setting up estim_params_
-[xparam1,estim_params_,bayestopt_,lb,ub] = set_prior(estim_params_,M_);
-
-options_.TeX = 0;
-options_.nograph = 0;
-plot_priors(bayestopt_,M_,options_);
-
-% workspace initialization
-if isempty(var_list)
-    var_list = M_.endo_names(1:M_.orig_endo_nbr,:);
-end
-n = size(var_list,1);
-
-periods = options_.forecast;
-exo_nbr = M_.exo_nbr;
-replic = options_.replic;
-order = options_.order;
-maximum_lag = M_.maximum_lag;
-%  params = prior_draw(1);
-params = rndprior(bayestopt_);
-set_parameters(params);
-% eliminate shocks with 0 variance
-i_exo_var = setdiff([1:exo_nbr],find(diag(M_.Sigma_e) == 0));
-nx = length(i_exo_var);
-
-ex0 = zeros(periods,exo_nbr);
-yf1 = zeros(periods+M_.maximum_lag,n,replic);
-
-% loops on parameter values
-m1 = 0;
-m2 = 0;
-for i=1:replic
-    % draw parameter values from the prior
-    % params = prior_draw(0);
-    params = rndprior(bayestopt_);
-    set_parameters(params);
-    % solve the model
-    [dr,info,M_,options_,oo_] = resol(0,M_,options_,oo_);
-    % discard problematic cases
-    if info
-        continue
-    end
-    % compute forecast with zero shocks
-    m1 = m1+1;
-    yf1(:,:,m1) = simult_(y0,dr,ex0,order)';
-    % compute forecast with antithetic shocks
-    chol_S = chol(M_.Sigma_e(i_exo_var,i_exo_var));
-    ex(:,i_exo_var) = randn(periods,nx)*chol_S;
-    m2 = m2+1;
-    yf2(:,:,m2) = simult_(y0,dr,ex,order)';
-    m2 = m2+1;
-    yf2(:,:,m2) = simult_(y0,dr,-ex,order)';
-end
-
-oo_.forecast.accept_rate = (replic-m1)/replic;
-
-if options_.noprint == 0 && m1 < replic
-    skipline(2)
-    disp('FORECASTING WITH PARAMETER UNCERTAINTY:')
-    disp(sprintf(['The model  couldn''t be solved for %f%% of the parameter' ...
-                  ' values'],100*oo_.forecast.accept_rate))
-    skipline(2)
-end
-
-% compute moments
-yf1 = yf1(:,:,1:m1);
-yf2 = yf2(:,:,1:m2);
-
-yf_mean = mean(yf1,3);
-
-yf1 = sort(yf1,3);
-yf2 = sort(yf2,3);
-
-sig_lev = options_.conf_sig;
-k1 = round((0.5+[-sig_lev, sig_lev]/2)*replic);
-% make sure that lower bound is at least the first element
-if k1(2) == 0
-    k1(2) = 1;
-end
-k2 = round((1+[-sig_lev, sig_lev])*replic);
-% make sure that lower bound is at least the first element
-if k2(2) == 0
-    k2(2) = 1;
-end
-
-% compute shock uncertainty around forecast with mean prior
-set_parameters(bayestopt_.p1);
-[dr,info,M_,options_,oo_] = resol(0,M_,options_,oo_);
-[yf3,yf3_intv] = forcst(dr,y0,periods,var_list);
-yf3_1 = yf3'-[zeros(maximum_lag,n); yf3_intv];
-yf3_2 = yf3'+[zeros(maximum_lag,n); yf3_intv];
-
-% graphs
-OutputDirectoryName = CheckPath('graphs',M_.fname);
-
-dyn_graph=dynare_graph_init('Forecasts type I',n,{'b-' 'g-' 'g-' 'r-' 'r-'});
-for i=1:n
-    dynare_graph(dyn_graph,[yf_mean(:,i) squeeze(yf1(:,i,k1)) squeeze(yf2(:,i,k2))],...
-                 var_list(i,:));
-end
-dyn_saveas(dyn_graph.fh,[OutputDirectoryName '/' M_.fname '_forecast_param_uncert_',num2str(nlags)],options_)
-
-dyn_graph=dynare_graph_init('Forecasts type II',n,{'b-' 'k-' 'k-' 'r-' 'r-'});
-for i=1:n
-    dynare_graph(dyn_graph,[yf_mean(:,i) yf3_1(:,i) yf3_2(:,i) squeeze(yf2(:,i,k2))],...
-                 var_list(i,:));
-end
-dyn_saveas(dyn_graph.fh,[OutputDirectoryName '/' M_.fname '_forecast_param_shock_uncert_',num2str(nlags)],options_)
-
-
-% saving results
-save_results(yf_mean,'oo_.forecast.Mean.',var_list);
-save_results(yf1(:,:,k1(1)),'oo_.forecast.HPDinf.',var_list);
-save_results(yf1(:,:,k1(2)),'oo_.forecast.HPDsup.',var_list);
-save_results(yf2(:,:,k2(1)),'oo_.forecast.HPDTotalinf.',var_list);
-save_results(yf2(:,:,k2(2)),'oo_.forecast.HPDTotalsup.',var_list);
\ No newline at end of file
diff --git a/matlab/get_prior_info.m b/matlab/get_prior_info.m
deleted file mode 100644
index cea8ffe4658378f40365231662e93b1cd2735c6c..0000000000000000000000000000000000000000
--- a/matlab/get_prior_info.m
+++ /dev/null
@@ -1,252 +0,0 @@
-function results = get_prior_info(info,plt_flag)
-% Computes various prior statistics.
-%
-% INPUTS
-%   info     [integer]   scalar specifying what has to be done.
-%
-% OUTPUTS
-%   none
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2009-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_ M_ estim_params_ oo_ objective_function_penalty_base
-
-if ~nargin
-    info = 0;
-    plt_flag = 0;
-end
-
-if nargin==1
-    plt_flag = 1;
-end
-
-% Initialize returned variable.
-results = [];
-
-changed_qz_criterium_flag  = 0;
-if isempty(options_.qz_criterium)
-    options_.qz_criterium = 1+1e-9;
-    changed_qz_criterium_flag  = 1;
-end
-
-M_.dname = M_.fname;
-
-% Temporarly set options_.order equal to one
-order = options_.order;
-options_.order = 1;
-
-[xparam1,estim_params_,bayestopt_,lb,ub,M_] = set_prior(estim_params_,M_,options_);
-if plt_flag
-    plot_priors(bayestopt_,M_,estim_params_,options_)
-end
-
-PriorNames = { 'Beta' , 'Gamma' , 'Gaussian' , 'Inverted Gamma' , 'Uniform' , 'Inverted Gamma -- 2' };
-
-if size(M_.param_names,1)==size(M_.param_names_tex,1)% All the parameters have a TeX name.
-    fidTeX = fopen('priors_data.tex','w+');
-    fprintf(fidTeX,'%% TeX-table generated by get_prior_info (Dynare).\n');
-    fprintf(fidTeX,'%% Prior Information\n');
-    fprintf(fidTeX,['%% ' datestr(now,0)]);
-    fprintf(fidTeX,' \n');
-    fprintf(fidTeX,' \n');
-    fprintf(fidTeX,'\\begin{center}\n');
-    fprintf(fidTeX,'\\begin{longtable}{l|ccccccc} \n');
-    fprintf(fidTeX,'\\caption{Prior information (parameters)}\\\\\n ');
-    fprintf(fidTeX,'\\label{Table:Prior}\\\\\n');
-    fprintf(fidTeX,'\\hline\\hline \\\\ \n');
-    fprintf(fidTeX,'  & Prior distribution & Prior mean  & Prior s.d. & Lower Bound & Upper Bound & LB Untrunc. 80\\%% HPDI & UB Untrunc. 80\\%% HPDI  \\\\ \n');
-    fprintf(fidTeX,'\\hline \\endfirsthead \n');
-    fprintf(fidTeX,'\\caption{(continued)}\\\\\n ');
-    fprintf(fidTeX,'\\hline\\hline \\\\ \n');
-    fprintf(fidTeX,'  & Prior distribution & Prior mean  & Prior s.d. & Lower Bound & Upper Bound & LB Untrunc.  80\\%% HPDI & UB Untrunc. 80\\%% HPDI  \\\\ \n');
-    fprintf(fidTeX,'\\hline \\endhead \n');
-    fprintf(fidTeX,'\\hline \\multicolumn{8}{r}{(Continued on next page)} \\\\ \\hline \\endfoot \n');
-    fprintf(fidTeX,'\\hline \\hline \\endlastfoot \n');
-
-    % Column 1: a string for the name of the prior distribution.
-    % Column 2: the prior mean.
-    % Column 3: the prior standard deviation.
-    % Column 4: the lower bound of the prior density support.
-    % Column 5: the upper bound of the prior density support.
-    % Column 6: the lower bound of the interval containing 80% of the prior mass.
-    % Column 7: the upper bound of the interval containing 80% of the prior mass.
-    prior_trunc_backup = options_.prior_trunc ;
-    options_.prior_trunc = (1-options_.prior_interval)/2 ;
-    PriorIntervals = prior_bounds(bayestopt_,options_) ;
-    options_.prior_trunc = prior_trunc_backup ;
-    for i=1:size(bayestopt_.name,1)
-        [tmp,TexName] = get_the_name(i,1,M_,estim_params_,options_);
-        PriorShape = PriorNames{ bayestopt_.pshape(i) };
-        PriorMean = bayestopt_.p1(i);
-        PriorStandardDeviation = bayestopt_.p2(i);
-        switch bayestopt_.pshape(i)
-          case { 1 , 5 }
-            LowerBound = bayestopt_.p3(i);
-            UpperBound = bayestopt_.p4(i);
-            if ~isinf(bayestopt_.lb(i))
-                LowerBound=max(LowerBound,bayestopt_.lb(i));
-            end
-            if ~isinf(bayestopt_.ub(i))
-                UpperBound=min(UpperBound,bayestopt_.ub(i));
-            end
-            case { 2 , 4 , 6 }
-            LowerBound = bayestopt_.p3(i);
-            if ~isinf(bayestopt_.lb(i))
-                LowerBound=max(LowerBound,bayestopt_.lb(i));
-            end
-            if ~isinf(bayestopt_.ub(i))
-                UpperBound=bayestopt_.ub(i);
-            else
-                UpperBound = '$\infty$';
-            end
-          case 3
-            if isinf(bayestopt_.p3(i)) && isinf(bayestopt_.lb(i))
-                LowerBound = '$-\infty$';
-            else
-                LowerBound = bayestopt_.p3(i);
-                if ~isinf(bayestopt_.lb(i))
-                    LowerBound=max(LowerBound,bayestopt_.lb(i));
-                end
-            end
-            if isinf(bayestopt_.p4(i)) && isinf(bayestopt_.ub(i))
-                UpperBound = '$\infty$';
-            else
-                UpperBound = bayestopt_.p4(i);
-                if ~isinf(bayestopt_.ub(i))
-                    UpperBound=min(UpperBound,bayestopt_.ub(i));
-                end
-            end
-          otherwise
-            error('get_prior_info:: Dynare bug!')
-        end
-        format_string = build_format_string(PriorStandardDeviation,LowerBound,UpperBound);
-        fprintf(fidTeX,format_string, ...
-                TexName, ...
-                PriorShape, ...
-                PriorMean, ...
-                PriorStandardDeviation, ...
-                LowerBound, ...
-                UpperBound, ...
-                PriorIntervals.lb(i), ...
-                PriorIntervals.ub(i) );
-    end
-    fprintf(fidTeX,'\\end{longtable}\n ');    
-    fprintf(fidTeX,'\\end{center}\n');
-    fprintf(fidTeX,'%% End of TeX file.\n');
-    fclose(fidTeX);
-end
-
-M_.dname = M_.fname;
-
-if info==1% Prior simulations (BK).
-    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)])
-    disp(['BK unstability share                  = ' num2str(results.bk.unstability_share)])
-    disp(['BK singularity share                  = ' num2str(results.bk.singularity_share)])
-    disp(['Complex jacobian share                = ' num2str(results.jacobian.problem_share)])
-    disp(['mjdgges crash share                   = ' num2str(results.dll.problem_share)])
-    disp(['Steady state problem share            = ' num2str(results.ss.problem_share)])
-    disp(['Complex steady state  share           = ' num2str(results.ss.complex_share)])
-    disp(['Analytical steady state problem share = ' num2str(results.ass.problem_share)])
-end
-
-if info==2% Prior optimization.
-          % Initialize to the prior mode if possible
-    oo_.dr=set_state_space(oo_.dr,M_,options_);
-    k = find(~isnan(bayestopt_.p5));
-    xparam1(k) = bayestopt_.p5(k);
-    % Pertubation of the initial condition.
-    look_for_admissible_initial_condition = 1;
-    scale = 1.0;
-    iter  = 0;
-    while look_for_admissible_initial_condition
-        xinit = xparam1+scale*randn(size(xparam1));
-        if all(xinit(:)>bayestopt_.p3) && all(xinit(:)<bayestopt_.p4)
-            M_ = set_all_parameters(xinit,estim_params_,M_);
-            [dr,INFO,M_,options_,oo_] = resol(0,M_,options_,oo_);
-            if ~INFO(1)
-                look_for_admissible_initial_condition = 0;
-            end
-        else
-            if iter == 2000;
-                scale = scale/1.1;
-                iter  = 0;
-            else
-                iter = iter+1;
-            end
-        end
-    end
-    objective_function_penalty_base = minus_logged_prior_density(xinit, bayestopt_.pshape, ...
-                               bayestopt_.p6, ...
-                               bayestopt_.p7, ...
-                               bayestopt_.p3, ...
-                               bayestopt_.p4,options_,M_,estim_params_,oo_);
-    % Maximization
-    [xparams,lpd,hessian] = ...
-        maximize_prior_density(xinit, bayestopt_.pshape, ...
-                               bayestopt_.p6, ...
-                               bayestopt_.p7, ...
-                               bayestopt_.p3, ...
-                               bayestopt_.p4,options_,M_,estim_params_,oo_);
-    % Display the results.
-    skipline(2)
-    disp('------------------')
-    disp('PRIOR OPTIMIZATION')
-    disp('------------------')
-    skipline()
-    for i = 1:length(xparams)
-        disp(['deep parameter ' int2str(i) ': ' get_the_name(i,0,M_,estim_params_,options_) '.'])
-        disp(['  Initial condition ....... ' num2str(xinit(i)) '.'])
-        disp(['  Prior mode .............. ' num2str(bayestopt_.p5(i)) '.'])
-        disp(['  Optimized prior mode .... ' num2str(xparams(i)) '.'])
-        skipline()
-    end
-end
-
-if info==3% Prior simulations (2nd order moments).
-    oo_ = compute_moments_varendo('prior',options_,M_,oo_);
-end
-
-if changed_qz_criterium_flag
-    options_.qz_criterium = [];
-end
-
-options_.order = order;
-
-function format_string = build_format_string(PriorStandardDeviation,LowerBound,UpperBound)
-format_string = ['%s & %s & %6.4f &'];
-if ~isnumeric(PriorStandardDeviation)
-    format_string = [ format_string , ' %s &'];
-else
-    format_string = [ format_string , ' %6.4f &'];
-end
-if ~isnumeric(LowerBound)
-    format_string = [ format_string , ' %s &'];
-else
-    format_string = [ format_string , ' %6.4f &'];
-end
-if ~isnumeric(UpperBound)
-    format_string = [ format_string , ' %s &'];
-else
-    format_string = [ format_string , ' %6.4f &'];
-end
-format_string = [ format_string , ' %6.4f & %6.4f \\\\ \n'];
\ No newline at end of file
diff --git a/matlab/global_initialization.m b/matlab/global_initialization.m
index ebe2a04d2a65a4938c28315f4f22d59c395066bb..690a3021249f2632fcd8919e2165671a714007e7 100644
--- a/matlab/global_initialization.m
+++ b/matlab/global_initialization.m
@@ -11,7 +11,7 @@ function global_initialization()
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2014 Dynare Team
+% Copyright (C) 2003-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -33,6 +33,7 @@ global oo_ M_ options_ estim_params_ bayestopt_ estimation_info ex0_ ys0_
 estim_params_ = [];
 bayestopt_ = [];
 options_.datafile = '';
+options_.dirname = M_.fname;
 options_.dataset = [];
 options_.verbosity = 1;
 options_.terminal_condition = 0;
@@ -55,6 +56,7 @@ options_.qz_zero_threshold = 1e-6;
 options_.lyapunov_complex_threshold = 1e-15;
 options_.solve_tolf = eps^(1/3);
 options_.solve_tolx = eps^(2/3);
+options_.dr_display_tol=1e-6;
 
 options_.dp.maxit = 3000;
 options_.steady.maxit = 50;
@@ -66,6 +68,8 @@ options_.mode_check.symmetric_plots = 1;
 options_.mode_check.number_of_points = 20;
 options_.mode_check.nolik = 0;
 
+options_.huge_number = 1e7;
+
 % Default number of threads for parallelized mex files.
 options_.threads.kronecker.A_times_B_kronecker_C = 1;
 options_.threads.kronecker.sparse_hessian_times_B_kronecker_C = 1;
@@ -103,6 +107,10 @@ options_.bvar_prior_omega = 1;
 options_.bvar_prior_flat = 0;
 options_.bvar_prior_train = 0;
 
+% Initialize the field that will contain the optimization algorigthm's options declared in the
+% estimation command (if anny).
+options_.optim_opt = [];
+
 % Optimization algorithm [6] gmhmaxlik
 gmhmaxlik.iterations = 3;
 gmhmaxlik.number = 20000;
@@ -241,11 +249,7 @@ particle.resampling.method.kitagawa = 1;
 particle.resampling.method.smooth = 0;
 particle.resampling.method.stratified = 0;
 % Set default algorithm
-particle.filter_algorithm.sis = 1;
-particle.filter_algorithm.apf = 0;
-particle.filter_algorithm.gf = 0;
-particle.filter_algorithm.gmf = 0;
-particle.filter_algorithm.cpf = 0;
+particle.filter_algorithm = 'sis';
 % Approximation of the proposal distribution
 particle.proposal_approximation.cubature = 1;
 particle.proposal_approximation.unscented = 0;
@@ -362,6 +366,8 @@ estimation_info.measurement_error_corr.range_index = {};
 estimation_info.structural_innovation_corr_prior_index = {};
 estimation_info.structural_innovation_corr_options_index = {};
 estimation_info.structural_innovation_corr.range_index = {};
+estimation_info.joint_parameter_prior_index = {};
+estimation_info.joint_parameter = {'index','domain','interval','mean','median','mode','shape','shift','stdev','truncate','variance'};
 options_.initial_period = NaN; %dates(1,1);
 options_.dataset.file = [];
 options_.dataset.series = [];
@@ -385,6 +391,7 @@ options_.nobs = NaN;
 options_.kalman_algo = 0;
 options_.fast_kalman = 0;
 options_.kalman_tol = 1e-10;
+options_.diffuse_kalman_tol = 1e-6;
 options_.use_univariate_filters_if_singularity_is_detected = 1;
 options_.riccati_tol = 1e-6;
 options_.lik_algo = 1;
@@ -406,6 +413,7 @@ options_.recursive_estimation_restart = 0;
 options_.MCMC_jumping_covariance='hessian';
 options_.use_calibration_initialization = 0;
 options_.endo_vars_for_moment_computations_in_estimation=[];
+options_.TaRB.use_TaRB = 0;
 
 % Prior restrictions
 options_.prior_restrictions.status = 0;
@@ -426,8 +434,8 @@ options_.student_degrees_of_freedom = 3;
 options_.posterior_max_subsample_draws = 1200;
 options_.sub_draws = [];
 options_.use_mh_covariance_matrix = 0;
-options_.gradient_method = 2;
-options_.gradient_epsilon = 1e-6;
+options_.gradient_method = 2; %used by csminwel and newrat
+options_.gradient_epsilon = 1e-6; %used by csminwel and newrat
 options_.posterior_sampling_method = 'random_walk_metropolis_hastings';
 options_.proposal_distribution = 'rand_multivariate_normal';
 options_.student_degrees_of_freedom = 3;
@@ -473,6 +481,18 @@ options_.homotopy_mode = 0;
 options_.homotopy_steps = 1;
 options_.homotopy_force_continue = 0;
 
+%csminwel optimization routine
+csminwel.tolerance.f=1e-7;
+csminwel.maxiter=1000;
+options_.csminwel=csminwel;
+
+%newrat optimization routine
+newrat.hess=1; % dynare numerical hessian
+newrat.tolerance.f=1e-5;
+newrat.tolerance.f_analytic=1e-7;
+newrat.maxiter=1000;
+options_.newrat=newrat;
+
 % Simplex optimization routine (variation on Nelder Mead algorithm).
 simplex.tolerance.x = 1e-4;
 simplex.tolerance.f = 1e-4;
@@ -510,6 +530,30 @@ simpsa.MAX_FUN_EVALS = 20000;
 simpsa.DISPLAY = 'iter';
 options_.simpsa = simpsa;
 
+%solveopt optimizer
+solveopt.minimizer_indicator=-1; %use minimizer
+solveopt.TolX=1e-6; %accuracy of argument
+solveopt.TolFun=1e-6; %accuracy of function 
+solveopt.MaxIter=15000;
+solveopt.verbosity=1;
+solveopt.TolXConstraint=1.e-8;
+solveopt.SpaceDilation=2.5;
+solveopt.LBGradientStep=1.e-11;
+options_.solveopt=solveopt;
+
+%simulated annealing
+options_.saopt.neps=10;
+options_.saopt.maximizer_indicator=0;
+options_.saopt.rt=0.10;
+options_.saopt.MaxIter=100000;
+options_.saopt.verbosity=1;
+options_.saopt.TolFun=1.0e-8;
+options_.saopt.initial_temperature=15;
+options_.saopt.ns=10;
+options_.saopt.nt=10;
+options_.saopt.step_length_c=0.1;
+options_.saopt.initial_step_length=1;
+
 % prior analysis
 options_.prior_mc = 20000;
 options_.prior_analysis_endo_var_list = [];
@@ -627,8 +671,7 @@ options_.endogenous_prior_restrictions.irf={};
 options_.endogenous_prior_restrictions.moment={};
 
 % OSR Optimal Simple Rules
-options_.osr.tolf=1e-7;
-options_.osr.maxit=1000;
+options_.osr.opt_algo=4;
 
 % use GPU
 options_.gpu = 0;
diff --git a/matlab/gsa/filt_mc_.m b/matlab/gsa/filt_mc_.m
index 329c6919d5ebac6a8edc359103efa597c804ea5f..4724801352dc653769b735bfe603c406b15adb04 100644
--- a/matlab/gsa/filt_mc_.m
+++ b/matlab/gsa/filt_mc_.m
@@ -43,7 +43,7 @@ alpha    = options_gsa_.alpha_rmse;
 % alpha2   = options_gsa_.alpha2_rmse;
 alpha2 = 0;
 pvalue   = options_gsa_.alpha2_rmse;
-istart   = options_gsa_.istart_rmse;
+istart   = max(2,options_gsa_.istart_rmse);
 alphaPC  = 0.5;
 
 fname_ = M_.fname;
@@ -242,41 +242,66 @@ end
 if ~options_.opt_gsa.ppost && options_.opt_gsa.lik_only
     if options_.opt_gsa.pprior
         anam='rmse_prior_post';
+        atitle='RMSE prior: Log Posterior Kernel';
     else
         anam='rmse_mc_post';
+        atitle='RMSE MC: Log Posterior Kernel';
     end
-    stab_map_1(x, ipost(1:nfilt), ipost(nfilt+1:end), anam, 1,[],OutDir);
-    stab_map_2(x(ipost(1:nfilt),:),alpha2,pvalue,anam, OutDir);
+
+    options_mcf.pvalue_ks = alpha;
+    options_mcf.pvalue_corr = pvalue;
+    options_mcf.alpha2 = alpha2;
+    options_mcf.param_names = char(bayestopt_.name);
+    options_mcf.fname_ = fname_;
+    options_mcf.OutputDirectoryName = OutDir;
+    options_mcf.amcf_name = anam;
+    options_mcf.amcf_title = atitle;
+    options_mcf.title = atitle;
+    options_mcf.beha_title = 'better posterior kernel';
+    options_mcf.nobeha_title = 'worse posterior kernel';
+    mcf_analysis(x, ipost(1:nfilt), ipost(nfilt+1:end), options_mcf, options_);
+    
     if options_.opt_gsa.pprior
-        anam='rmse_prior_lik';
+        anam = 'rmse_prior_lik';
+        atitle = 'RMSE prior: Log Likelihood Kernel';
     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,pvalue,anam, OutDir);
+        atitle = 'RMSE MC: Log Likelihood Kernel';
+    end
+    options_mcf.amcf_name = anam;
+    options_mcf.amcf_title = atitle;
+    options_mcf.title = atitle;
+    options_mcf.beha_title = 'better likelihood';
+    options_mcf.nobeha_title = 'worse likelihood';
+    mcf_analysis(x, ilik(1:nfilt), ilik(nfilt+1:end), options_mcf, options_);
+
 else
-    for i=1:size(vvarvecm,1),
-        [dum, ixx(:,i)]=sort(rmse_MC(:,i));
-        if options_.opt_gsa.ppost,
+    if options_.opt_gsa.ppost,
+        rmse_txt=rmse_pmean;
+        r2_txt=r2_pmean;
+    else
+        if options_.opt_gsa.pprior || ~exist('rmse_pmean'),
+            if exist('rmse_mode'),
+                rmse_txt=rmse_mode;
+                r2_txt=r2_mode;
+            else
+                rmse_txt=NaN(1,size(rmse_MC,2));
+                r2_txt=NaN(1,size(r2_MC,2));
+            end
+        else
             %nfilt0(i)=length(find(rmse_MC(:,i)<rmse_pmean(i)));
             rmse_txt=rmse_pmean;
             r2_txt=r2_pmean;
-        else
-            if options_.opt_gsa.pprior || ~exist('rmse_pmean'),
-                if exist('rmse_mode'),
-                    rmse_txt=rmse_mode;
-                    r2_txt=r2_mode;
-                else
-                    rmse_txt=NaN(1,size(rmse_MC,2));
-                    r2_txt=NaN(1,size(r2_MC,2));
-                end
-            else
-                %nfilt0(i)=length(find(rmse_MC(:,i)<rmse_pmean(i)));
-                rmse_txt=rmse_pmean;
-                r2_txt=r2_pmean;
-            end
         end
-        for j=1:npar+nshock,
+    end
+    for i=1:size(vvarvecm,1),
+        [dum, ixx(:,i)]=sort(rmse_MC(:,i));
+    end
+    PP=ones(npar+nshock,size(vvarvecm,1));
+    PPV=ones(size(vvarvecm,1),size(vvarvecm,1),npar+nshock);
+    SS=zeros(npar+nshock,size(vvarvecm,1));
+    for j=1:npar+nshock,
+        for i=1:size(vvarvecm,1),
             [H,P,KSSTAT] = smirnov(x(ixx(nfilt0(i)+1:end,i),j),x(ixx(1:nfilt0(i),i),j), alpha);
             [H1,P1,KSSTAT1] = smirnov(x(ixx(nfilt0(i)+1:end,i),j),x(ixx(1:nfilt0(i),i),j),alpha,1);
             [H2,P2,KSSTAT2] = smirnov(x(ixx(nfilt0(i)+1:end,i),j),x(ixx(1:nfilt0(i),i),j),alpha,-1);
@@ -289,6 +314,22 @@ else
             end
             PP(j,i)=P;
         end
+        for i=1:size(vvarvecm,1),
+            for l=1:size(vvarvecm,1),
+                if l~=i && PP(j,i)<alpha && PP(j,l)<alpha
+                    [H,P,KSSTAT] = smirnov(x(ixx(1:nfilt0(i),i),j),x(ixx(1:nfilt0(l),l),j), alpha);
+                    %[H1,P1,KSSTAT1] = smirnov(x(ixx(1:nfilt0(i),i),j),x(:,j), alpha);
+                    %                 PP(j,i)=min(P,PP(j,i));
+                    %                 PP(j,l)=min(P,PP(j,l));
+                    %if P<P1
+%                     if SS(j,i)*SS(j,l)
+                        PPV(i,l,j) = P;
+%                     end
+                elseif l==i
+                    PPV(i,l,j) = PP(j,i);
+                end
+            end
+        end
     end
     if ~options_.nograph,
     ifig=0;
@@ -308,12 +349,17 @@ else
         end
         subplot(3,3,i-9*(ifig-1))
         h=cumplot(lnprior(ixx(1:nfilt0(i),i)));
-        set(h,'color','red')
-        hold on, cumplot(lnprior)
+        set(h,'color','blue','linewidth',2)
+        hold on, h=cumplot(lnprior);
+        set(h,'color','k','linewidth',1)
         h=cumplot(lnprior(ixx(nfilt0(i)+1:end,i)));
-        set(h,'color','green')
+        set(h,'color','red','linewidth',2)
         title(vvarvecm(i,:),'interpreter','none')
         if mod(i,9)==0 || i==size(vvarvecm,1)
+            if ~isoctave
+                annotation('textbox', [0.1,0,0.35,0.05],'String', 'Log-prior for BETTER R2','Color','Blue','horizontalalignment','center');
+                annotation('textbox', [0.55,0,0.35,0.05],'String', 'Log-prior for WORSE R2', 'Color','Red','horizontalalignment','center');
+            end
             if options_.opt_gsa.ppost
                 dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnprior',int2str(ifig)],options_);
             else
@@ -342,15 +388,20 @@ else
         end
         subplot(3,3,i-9*(ifig-1))
         h=cumplot(likelihood(ixx(1:nfilt0(i),i)));
-        set(h,'color','red')
+        set(h,'color','blue','linewidth',2)
         hold on, h=cumplot(likelihood);
+        set(h,'color','k','linewidth',1)
         h=cumplot(likelihood(ixx(nfilt0(i)+1:end,i)));
-        set(h,'color','green')
+        set(h,'color','red','linewidth',2)
         title(vvarvecm(i,:),'interpreter','none')
         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 ~isoctave
+                annotation('textbox', [0.1,0,0.35,0.05],'String', 'Log-likelihood for BETTER R2','Color','Blue','horizontalalignment','center');
+                annotation('textbox', [0.55,0,0.35,0.05],'String', 'Log-likelihood for WORSE R2', 'Color','Red','horizontalalignment','center');
+            end
             if options_.opt_gsa.ppost
                 dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnlik',int2str(ifig) ],options_);
             else
@@ -379,15 +430,20 @@ else
         end
         subplot(3,3,i-9*(ifig-1))
         h=cumplot(logpo2(ixx(1:nfilt0(i),i)));
-        set(h,'color','red')
+        set(h,'color','blue','linewidth',2)
         hold on, h=cumplot(logpo2);
+        set(h,'color','k','linewidth',1)
         h=cumplot(logpo2(ixx(nfilt0(i)+1:end,i)));
-        set(h,'color','green')
+        set(h,'color','red','linewidth',2)
         title(vvarvecm(i,:),'interpreter','none')
         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 ~isoctave
+                annotation('textbox', [0.1,0,0.35,0.05],'String', 'Log-posterior for BETTER R2','Color','Blue','horizontalalignment','center');
+                annotation('textbox', [0.55,0,0.35,0.05],'String', 'Log-posterior for WORSE R2', 'Color','Red','horizontalalignment','center');
+            end
             if options_.opt_gsa.ppost
                 dyn_saveas(hh,[OutDir filesep fname_ '_rmse_post_lnpost',int2str(ifig) ],options_);
             else
@@ -401,11 +457,12 @@ else
     end
     end
     
-    param_names='';
-    for j=1:npar+nshock,
-        param_names=char(param_names, bayestopt_.name{j});
-    end
-    param_names=param_names(2:end,:);
+    param_names=char(bayestopt_.name);
+%     param_names='';
+%     for j=1:npar+nshock,
+%         param_names=char(param_names, bayestopt_.name{j});
+%     end
+%     param_names=param_names(2:end,:);
     
     skipline()
     disp('RMSE over the MC sample:')
@@ -526,15 +583,94 @@ else
     a00=jet(size(vvarvecm,1));
     if options_.opt_gsa.ppost
         temp_name='RMSE Posterior Tradeoffs:';
+        atitle='RMSE Posterior Map:';
+        asname='rmse_post'; 
     else
         if options_.opt_gsa.pprior
             temp_name='RMSE Prior Tradeoffs:';
+            atitle='RMSE Prior Map:';
+            asname='rmse_prior'; 
         else
-            temp_name='RMSE MC Tradeoffs;';
+            temp_name='RMSE MC Tradeoffs:';
+            atitle='RMSE MC Map:';
+            asname='rmse_mc';
         end
     end
+    % now I plot by observed variables
+    options_mcf.pvalue_ks = alpha;
+    options_mcf.pvalue_corr = pvalue;
+    options_mcf.alpha2 = alpha2;
+    options_mcf.param_names = char(bayestopt_.name);
+    options_mcf.fname_ = fname_;
+    options_mcf.OutputDirectoryName = OutDir;
+    for iy=1:size(vvarvecm,1),
+        options_mcf.amcf_name = [asname '_' deblank(vvarvecm(iy,:)) '_map' ];
+        options_mcf.amcf_title = [atitle ' ' deblank(vvarvecm(iy,:))];
+        options_mcf.beha_title = ['better fit of ' deblank(vvarvecm(iy,:))];
+        options_mcf.nobeha_title = ['worse fit of ' deblank(vvarvecm(iy,:))];
+        options_mcf.title = ['the fit of ' deblank(vvarvecm(iy,:))];
+        mcf_analysis(x, ixx(1:nfilt0(iy),iy), ixx(nfilt0(iy)+1:end,iy), options_mcf, options_);
+    end
+    for iy=1:size(vvarvecm,1),
+        ipar = find(any(squeeze(PPV(iy,:,:))<alpha));
+        for ix=1:ceil(length(ipar)/5),
+        hh = dyn_figure(options_,'name',[temp_name,' observed variable ',deblank(vvarvecm(iy,:))]);
+        for j=1+5*(ix-1):min(length(ipar),5*ix),
+            subplot(2,3,j-5*(ix-1))
+            %h0=cumplot(x(:,nsnam(j)+nshock));
+            h0=cumplot(x(:,ipar(j)));
+            set(h0,'color',[0 0 0])
+            hold on,
+            iobs=find(squeeze(PPV(iy,:,ipar(j)))<alpha);
+            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)));
+                if any(iobs==i) || i==iy,
+                    h0=cumplot(x(ixx(1:nfilt0(i),i),ipar(j)));
+                    if ~isoctave
+                        hcmenu = uicontextmenu;
+                        uimenu(hcmenu,'Label',deblank(vvarvecm(i,:)));
+                        set(h0,'uicontextmenu',hcmenu)
+                    end
+                else
+                    h0=cumplot(x(ixx(1:nfilt0(i),i),ipar(j))*NaN);
+                end
+                set(h0,'color',a00(i,:),'linewidth',2)
+            end
+            ydum=get(gca,'ylim');
+            %xdum=xparam1(nshock+nsnam(j));
+            if exist('xparam1')
+                xdum=xparam1(ipar(j));
+                h1=plot([xdum xdum],ydum);
+                set(h1,'color',[0.85 0.85 0.85],'linewidth',2)
+            end
+            xlabel('')
+            title([pnam{ipar(j)}],'interpreter','none')
+        end
+        %subplot(3,2,6)
+        if isoctave
+            legend(char('base',vvarvecm),'location','eastoutside');
+        else
+            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);
+        %set(findobj(get(h0,'children'),'type','text'),'interpreter','none')
+        if options_.opt_gsa.ppost
+            dyn_saveas(hh,[ OutDir filesep fname_ '_rmse_post_' deblank(vvarvecm(iy,:)) '_' int2str(ix)],options_);
+        else
+            if options_.opt_gsa.pprior
+                dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_' deblank(vvarvecm(iy,:)) '_' int2str(ix) ],options_);
+            else
+                dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_' deblank(vvarvecm(iy,:)) '_' int2str(ix)],options_);
+            end
+        end
+        end
+    end
+    
+    % now I plot by individual parameters
     for ix=1:ceil(length(nsnam)/5),
-        hh = dyn_figure(options_,'name',[temp_name,' observed variables ',int2str(ix)]);
+        hh = dyn_figure(options_,'name',[temp_name,' estimated params and shocks ',int2str(ix)]);
         for j=1+5*(ix-1):min(size(snam2,1),5*ix),
             subplot(2,3,j-5*(ix-1))
             %h0=cumplot(x(:,nsnam(j)+nshock));
@@ -551,8 +687,13 @@ else
                     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,:))
+                    if ~isoctave
+                        hcmenu = uicontextmenu;
+                        uimenu(hcmenu,'Label',deblank(vvarvecm(i,:)));
+                        set(h0,'uicontextmenu',hcmenu)
+                    end
+                end
+                set(h0,'color',a00(i,:),'linewidth',2)
             end
             ydum=get(gca,'ylim');
             %xdum=xparam1(nshock+nsnam(j));
@@ -574,74 +715,74 @@ else
         %h0=legend({'base',vnam{np}}',0);
         %set(findobj(get(h0,'children'),'type','text'),'interpreter','none')
         if options_.opt_gsa.ppost
-            dyn_saveas(hh,[ OutDir filesep fname_ '_rmse_post_' int2str(ix)],options_);
+            dyn_saveas(hh,[ OutDir filesep fname_ '_rmse_post_params_' int2str(ix)],options_);
         else
             if options_.opt_gsa.pprior
-                dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_' int2str(ix) ],options_);
+                dyn_saveas(hh,[OutDir filesep fname_ '_rmse_prior_params_' int2str(ix) ],options_);
             else
-                dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_' int2str(ix)],options_);
+                dyn_saveas(hh,[OutDir filesep fname_ '_rmse_mc_params_' int2str(ix)],options_);
             end
         end
     end
     end
     
-    for j=1:size(SP,2),
-        nsx(j)=length(find(SP(:,j)));
-    end
-    
-    skipline(2)
-    disp('Sensitivity table (significance and direction):')
-    vav=char(zeros(1, size(param_names,2)+3 ));
-    ibl = 12-size(vvarvecm,2);
-    for j=1:size(vvarvecm,1),
-        vav = [vav, char(zeros(1,ibl)),vvarvecm(j,:)];
-    end
-    disp(vav)
-    for j=1:npar+nshock, %estim_params_.np,
-        %disp([param_names(j,:), sprintf('%8.5g',SP(j,:))])
-        disp([param_names(j,:),'   ', sprintf('%12.3g',PP(j,:))])
-        disp([char(zeros(1, size(param_names,2)+3 )),sprintf('    (%6g)',SS(j,:))])
-    end
+%     for j=1:size(SP,2),
+%         nsx(j)=length(find(SP(:,j)));
+%     end
     
+%     skipline(2)
+%     disp('Sensitivity table (significance and direction):')
+%     vav=char(zeros(1, size(param_names,2)+3 ));
+%     ibl = 12-size(vvarvecm,2);
+%     for j=1:size(vvarvecm,1),
+%         vav = [vav, char(zeros(1,ibl)),vvarvecm(j,:)];
+%     end
+%     disp(vav)
+%     for j=1:npar+nshock, %estim_params_.np,
+%         %disp([param_names(j,:), sprintf('%8.5g',SP(j,:))])
+%         disp([param_names(j,:),'   ', sprintf('%12.3g',PP(j,:))])
+%         disp([char(zeros(1, size(param_names,2)+3 )),sprintf('    (%6g)',SS(j,:))])
+%     end
     
-    skipline()
-    disp('Starting bivariate analysis:')
     
-    for i=1:size(vvarvecm,1)
-        if options_.opt_gsa.ppost
-            fnam = ['rmse_post_',deblank(vvarvecm(i,:))];
-        else
-            if options_.opt_gsa.pprior
-                fnam = ['rmse_prior_',deblank(vvarvecm(i,:))];
-            else
-                fnam = ['rmse_mc_',deblank(vvarvecm(i,:))];
-            end
-        end
-        stab_map_2(x(ixx(1:nfilt0(i),i),:),alpha2,pvalue,fnam, OutDir,[],[temp_name ' observed variable ' deblank(vvarvecm(i,:))]);
-        
-        %     [pc,latent,explained] = pcacov(c0);
-        %     %figure, bar([explained cumsum(explained)])
-        %     ifig=0;
-        %     j2=0;
-        %     for j=1:npar+nshock,
-        %         i2=find(abs(pc(:,j))>alphaPC);
-        %         if ~isempty(i2),
-        %             j2=j2+1;
-        %             if mod(j2,12)==1,
-        %                 ifig=ifig+1;
-        %                 figure('name',['PCA of the filtered sample ',deblank(vvarvecm(i,:)),' ',num2str(ifig)]),
-        %             end
-        %             subplot(3,4,j2-(ifig-1)*12)
-        %             bar(pc(i2,j)),
-        %             set(gca,'xticklabel',bayestopt_.name(i2)),
-        %             set(gca,'xtick',[1:length(i2)])
-        %             title(['PC ',num2str(j),'. Explained ',num2str(explained(j)),'%'])
-        %         end
-        %         if (mod(j2,12)==0 | j==(npar+nshock)) & j2,
-        %             saveas(gcf,[fname_,'_SA_PCA_',deblank(vvarvecm(i,:)),'_',int2str(ifig)])
-        %         end
-        %     end
-        %     close all
-    end
+%     skipline()
+%     disp('Starting bivariate analysis:')
+%     
+%     for i=1:size(vvarvecm,1)
+%         if options_.opt_gsa.ppost
+%             fnam = ['rmse_post_',deblank(vvarvecm(i,:))];
+%         else
+%             if options_.opt_gsa.pprior
+%                 fnam = ['rmse_prior_',deblank(vvarvecm(i,:))];
+%             else
+%                 fnam = ['rmse_mc_',deblank(vvarvecm(i,:))];
+%             end
+%         end
+%         stab_map_2(x(ixx(1:nfilt0(i),i),:),alpha2,pvalue,fnam, OutDir,[],[temp_name ' observed variable ' deblank(vvarvecm(i,:))]);
+%         
+%         %     [pc,latent,explained] = pcacov(c0);
+%         %     %figure, bar([explained cumsum(explained)])
+%         %     ifig=0;
+%         %     j2=0;
+%         %     for j=1:npar+nshock,
+%         %         i2=find(abs(pc(:,j))>alphaPC);
+%         %         if ~isempty(i2),
+%         %             j2=j2+1;
+%         %             if mod(j2,12)==1,
+%         %                 ifig=ifig+1;
+%         %                 figure('name',['PCA of the filtered sample ',deblank(vvarvecm(i,:)),' ',num2str(ifig)]),
+%         %             end
+%         %             subplot(3,4,j2-(ifig-1)*12)
+%         %             bar(pc(i2,j)),
+%         %             set(gca,'xticklabel',bayestopt_.name(i2)),
+%         %             set(gca,'xtick',[1:length(i2)])
+%         %             title(['PC ',num2str(j),'. Explained ',num2str(explained(j)),'%'])
+%         %         end
+%         %         if (mod(j2,12)==0 | j==(npar+nshock)) & j2,
+%         %             saveas(gcf,[fname_,'_SA_PCA_',deblank(vvarvecm(i,:)),'_',int2str(ifig)])
+%         %         end
+%         %     end
+%         %     close all
+%     end
     
 end
\ No newline at end of file
diff --git a/matlab/gsa/log_trans_.m b/matlab/gsa/log_trans_.m
index d8c726c5ff3d33db26260aad00c3187ae92fbc89..2f48c7156788a8ee1af3b5bb912d4ce96d86f850 100644
--- a/matlab/gsa/log_trans_.m
+++ b/matlab/gsa/log_trans_.m
@@ -1,4 +1,4 @@
-function [yy, xdir, isig, lam]=log_trans_(y0,xdir0)
+function [yy, xdir, isig, lam]=log_trans_(y0,xdir0,isig,lam)
 
 % Copyright (C) 2012 Dynare Team
 %
@@ -17,6 +17,12 @@ function [yy, xdir, isig, lam]=log_trans_(y0,xdir0)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
+if nargin==4,
+    % inverse transformation
+    yy = (exp(y0)-lam)*isig;
+    return
+end
+
 if nargin==1,
   xdir0='';
 end
@@ -67,5 +73,6 @@ else
         lam = -min(y0)+abs(median(y0)); %abs(100*(1+min(y0)));
     end
   end
+  lam = max(lam,0);
   yy = log(y0+lam);
 end
diff --git a/matlab/gsa/map_calibration.m b/matlab/gsa/map_calibration.m
index da933023daef9cbfe4db9616d8936d52ec410451..6dae9fe51cf2ca91fd8d2df44dc14b84bea5f920 100644
--- a/matlab/gsa/map_calibration.m
+++ b/matlab/gsa/map_calibration.m
@@ -55,7 +55,7 @@ else
         load(filetoload,'lpmat','lpmat0','istable','iunstable','iindeterm','iwrong' ,'infox')
         lpmat = [lpmat0 lpmat];
         type = 'mc';
-    end        
+    end
 end
 [Nsam, np] = size(lpmat);
 npar = size(pnames,1);
@@ -65,58 +65,91 @@ nbr_irf_restrictions = size(DynareOptions.endogenous_prior_restrictions.irf,1);
 nbr_moment_restrictions = size(DynareOptions.endogenous_prior_restrictions.moment,1);
 
 if init
-mat_irf=cell(nbr_irf_restrictions,1);
-for ij=1:nbr_irf_restrictions,
-    mat_irf{ij}=NaN(Nsam,length(DynareOptions.endogenous_prior_restrictions.irf{ij,3}));
-end
-
-mat_moment=cell(nbr_moment_restrictions,1);
-for ij=1:nbr_moment_restrictions,
-    mat_moment{ij}=NaN(Nsam,length(DynareOptions.endogenous_prior_restrictions.moment{ij,3}));
-end
-
-irestrictions = [1:Nsam];
-h = dyn_waitbar(0,'Please wait...');
-for j=1:Nsam,
-    Model = set_all_parameters(lpmat(j,:)',EstimatedParameters,Model);
-    [Tt,Rr,SteadyState,info] = dynare_resolve(Model,DynareOptions,DynareResults,'restrict');
-    if info(1)==0,
-        [info, info_irf, info_moment, data_irf, data_moment]=endogenous_prior_restrictions(Tt,Rr,Model,DynareOptions,DynareResults);
-        if ~isempty(info_irf)
-            for ij=1:nbr_irf_restrictions,
-                mat_irf{ij}(j,:)=data_irf{ij}(:,2)';
-            end
-            indx_irf(j,:)=info_irf(:,1);
+    mat_irf=cell(nbr_irf_restrictions,1);
+    for ij=1:nbr_irf_restrictions,
+        mat_irf{ij}=NaN(Nsam,length(DynareOptions.endogenous_prior_restrictions.irf{ij,3}));
+    end
+    
+    mat_moment=cell(nbr_moment_restrictions,1);
+    for ij=1:nbr_moment_restrictions,
+        mat_moment{ij}=NaN(Nsam,length(DynareOptions.endogenous_prior_restrictions.moment{ij,3}));
+    end
+    
+    irestrictions = [1:Nsam];
+    h = dyn_waitbar(0,'Please wait...');
+    for j=1:Nsam,
+        Model = set_all_parameters(lpmat(j,:)',EstimatedParameters,Model);
+        if nbr_moment_restrictions,
+            [Tt,Rr,SteadyState,info,Model,DynareOptions,DynareResults] = dynare_resolve(Model,DynareOptions,DynareResults);
+        else
+            [Tt,Rr,SteadyState,info,Model,DynareOptions,DynareResults] = dynare_resolve(Model,DynareOptions,DynareResults,'restrict');
         end
-        if ~isempty(info_moment)
-            for ij=1:nbr_moment_restrictions,
-                mat_moment{ij}(j,:)=data_moment{ij}(:,2)';
+        if info(1)==0,
+            [info, info_irf, info_moment, data_irf, data_moment]=endogenous_prior_restrictions(Tt,Rr,Model,DynareOptions,DynareResults);
+            if ~isempty(info_irf)
+                for ij=1:nbr_irf_restrictions,
+                    mat_irf{ij}(j,:)=data_irf{ij}(:,2)';
+                end
+                indx_irf(j,:)=info_irf(:,1);
+            end
+            if ~isempty(info_moment)
+                for ij=1:nbr_moment_restrictions,
+                    mat_moment{ij}(j,:)=data_moment{ij}(:,2)';
+                end
+                indx_moment(j,:)=info_moment(:,1);
             end
-            indx_moment(j,:)=info_moment(:,1);
+        else
+            irestrictions(j)=0;
         end
-    else
-        irestrictions(j)=0;
+        dyn_waitbar(j/Nsam,h,['MC iteration ',int2str(j),'/',int2str(Nsam)])
     end
-    dyn_waitbar(j/Nsam,h,['MC iteration ',int2str(j),'/',int2str(Nsam)])
-end
-dyn_waitbar_close(h);
-
-irestrictions=irestrictions(find(irestrictions));
-xmat=lpmat(irestrictions,:);
-skipline()
-endo_prior_restrictions=DynareOptions.endogenous_prior_restrictions;
-save([OutputDirectoryName,filesep,fname_,'_',type,'_restrictions'],'xmat','mat_irf','mat_moment','irestrictions','indx_irf','indx_moment','endo_prior_restrictions');
+    dyn_waitbar_close(h);
+    
+    irestrictions=irestrictions(find(irestrictions));
+    xmat=lpmat(irestrictions,:);
+    skipline()
+    endo_prior_restrictions=DynareOptions.endogenous_prior_restrictions;
+    save([OutputDirectoryName,filesep,fname_,'_',type,'_restrictions'],'xmat','mat_irf','mat_moment','irestrictions','indx_irf','indx_moment','endo_prior_restrictions');
 else
-load([OutputDirectoryName,filesep,fname_,'_',type,'_restrictions'],'xmat','mat_irf','mat_moment','irestrictions','indx_irf','indx_moment','endo_prior_restrictions');
-end    
+    load([OutputDirectoryName,filesep,fname_,'_',type,'_restrictions'],'xmat','mat_irf','mat_moment','irestrictions','indx_irf','indx_moment','endo_prior_restrictions');
+end
 if ~isempty(indx_irf),
-    
-    % For single legend search which has maximum nbr of restrictions 
+    skipline()
+    disp('Deleting old IRF calibration plots ...')
+    a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_irf_calib*.eps']);
+    for j=1:length(a),
+        delete([OutputDirectoryName,filesep,a(j).name]);
+    end
+    a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_irf_calib*.fig']);
+    for j=1:length(a),
+        delete([OutputDirectoryName,filesep,a(j).name]);
+    end
+    a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_irf_calib*.pdf']);
+    for j=1:length(a),
+        delete([OutputDirectoryName,filesep,a(j).name]);
+    end
+    a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions.eps']);
+    for j=1:length(a),
+        delete([OutputDirectoryName,filesep,a(j).name]);
+    end
+    a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions.fig']);
+    for j=1:length(a),
+        delete([OutputDirectoryName,filesep,a(j).name]);
+    end
+    a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions.pdf']);
+    for j=1:length(a),
+        delete([OutputDirectoryName,filesep,a(j).name]);
+    end
+    disp('done !')
+    skipline()
+  
+    % For single legend search which has maximum nbr of restrictions
     all_irf_couples = cellstr([char(endo_prior_restrictions.irf(:,1)) char(endo_prior_restrictions.irf(:,2))]);
     irf_couples = unique(all_irf_couples);
     nbr_irf_couples = size(irf_couples,1);
     plot_indx = NaN(nbr_irf_couples,1);
     time_matrix=cell(nbr_irf_couples,1);
+    indx_irf_matrix=zeros(length(irestrictions),nbr_irf_couples);
     irf_matrix=cell(nbr_irf_couples,1);
     irf_mean=cell(nbr_irf_couples,1);
     irf_median=cell(nbr_irf_couples,1);
@@ -131,17 +164,21 @@ if ~isempty(indx_irf),
         plot_indx(ij) = find(strcmp(irf_couples,all_irf_couples(ij,:)));
         time_matrix{plot_indx(ij)} = [time_matrix{plot_indx(ij)} endo_prior_restrictions.irf{ij,3}];
     end
+    iplot_indx = ones(size(plot_indx));
     
     indx_irf = indx_irf(irestrictions,:);
-    h1=dyn_figure(DynareOptions,'name',[type ' evaluation of irf restrictions']);
-    nrow=ceil(sqrt(nbr_irf_couples));
-    ncol=nrow;
-    if nrow*(nrow-1)>nbr_irf_couples,
-        ncol=nrow-1;
+    if ~DynareOptions.nograph,
+        h1=dyn_figure(DynareOptions,'name',[type ' evaluation of irf restrictions']);
+        nrow=ceil(sqrt(nbr_irf_couples));
+        ncol=nrow;
+        if nrow*(nrow-1)>nbr_irf_couples,
+            ncol=nrow-1;
+        end
     end
     for ij=1:nbr_irf_restrictions,
         mat_irf{ij}=mat_irf{ij}(irestrictions,:);
         irf_matrix{plot_indx(ij)} = [irf_matrix{plot_indx(ij)} mat_irf{ij}];
+        indx_irf_matrix(:,plot_indx(ij)) = indx_irf_matrix(:,plot_indx(ij)) + indx_irf(:,ij);
         for ik=1:size(mat_irf{ij},2),
             [Mean,Median,Var,HPD,Distrib] = ...
                 posterior_moments(mat_irf{ij}(:,ik),0,DynareOptions.mh_conf_sig);
@@ -156,18 +193,21 @@ if ~isempty(indx_irf),
         if size(mat_irf{ij},2)>1,
             leg = [leg,':' ,num2str(endo_prior_restrictions.irf{ij,3}(end))];
             aleg = [aleg,'-' ,num2str(endo_prior_restrictions.irf{ij,3}(end))];
-        end        
-        if length(time_matrix{plot_indx(ij)})==1,
-            figure(h1),
+            iplot_indx(ij)=0;
+        end
+        if ~DynareOptions.nograph && length(time_matrix{plot_indx(ij)})==1,
+            set(0,'currentfigure',h1),
             subplot(nrow,ncol, plot_indx(ij)),
             hc = cumplot(mat_irf{ij}(:,ik));
-            set(hc,'color','k','linewidth',2)
-            hold all,
             a=axis;
+            delete(hc);
             x1val=max(endo_prior_restrictions.irf{ij,4}(1),a(1));
             x2val=min(endo_prior_restrictions.irf{ij,4}(2),a(2));
             hp = patch([x1val x2val x2val x1val],a([3 3 4 4]),'b');
-            set(hp,'FaceAlpha', 0.5)
+            hold all,
+            set(hp,'FaceColor', [0.7 0.8 1])
+            hc = cumplot(mat_irf{ij}(:,ik));
+            set(hc,'color','k','linewidth',2)
             hold off,
             %         hold off,
             title([endo_prior_restrictions.irf{ij,1},' vs ',endo_prior_restrictions.irf{ij,2}, '(', leg,')'],'interpreter','none'),
@@ -185,75 +225,133 @@ if ~isempty(indx_irf),
         indx1 = find(indx_irf(:,ij)==0);
         indx2 = find(indx_irf(:,ij)~=0);
         atitle0=[endo_prior_restrictions.irf{ij,1},' vs ',endo_prior_restrictions.irf{ij,2}, '(', leg,')'];
-        fprintf(['%4.1f%% of the prior support matches IRF ',atitle0,' inside [%4.1f, %4.1f]\n'],length(indx1)/length(irestrictions)*100,endo_prior_restrictions.irf{ij,4})
+        fprintf(['%4.1f%% of the ',type,' support matches IRF ',atitle0,' inside [%4.1f, %4.1f]\n'],length(indx1)/length(irestrictions)*100,endo_prior_restrictions.irf{ij,4})
         % aname=[type '_irf_calib_',int2str(ij)];
         aname=[type '_irf_calib_',endo_prior_restrictions.irf{ij,1},'_vs_',endo_prior_restrictions.irf{ij,2},'_',aleg];
         atitle=[type ' IRF Calib: Parameter(s) driving ',endo_prior_restrictions.irf{ij,1},' vs ',endo_prior_restrictions.irf{ij,2}, '(', leg,')'];
         options_mcf.amcf_name = aname;
         options_mcf.amcf_title = atitle;
-        options_mcf.beha_title = 'IRF prior restriction';
-        options_mcf.nobeha_title = 'NO IRF prior restriction';
+        options_mcf.beha_title = 'IRF restriction';
+        options_mcf.nobeha_title = 'NO IRF restriction';
         options_mcf.title = atitle0;
         if ~isempty(indx1) && ~isempty(indx2)
             mcf_analysis(xmat(:,nshock+1:end), indx1, indx2, options_mcf, DynareOptions);
         end
-
-%         [proba, dproba] = stab_map_1(xmat, indx1, indx2, aname, 0);
-%         indplot=find(proba<pvalue_ks);
-%         if ~isempty(indplot)
-%             stab_map_1(xmat, indx1, indx2, aname, 1, indplot, OutputDirectoryName,[],atitle);
-%         end
+        
+        %         [proba, dproba] = stab_map_1(xmat, indx1, indx2, aname, 0);
+        %         indplot=find(proba<pvalue_ks);
+        %         if ~isempty(indplot)
+        %             stab_map_1(xmat, indx1, indx2, aname, 1, indplot, OutputDirectoryName,[],atitle);
+        %         end
     end
-    figure(h1);
     for ij=1:nbr_irf_couples,
         if length(time_matrix{ij})>1,
-            subplot(nrow,ncol, ij)
-            itmp = (find(plot_indx==ij));
-            plot(time_matrix{ij},[max(irf_matrix{ij})' min(irf_matrix{ij})'],'k--','linewidth',2)
-            hold on,
-            plot(time_matrix{ij},irf_median{ij},'k','linewidth',2)
-            plot(time_matrix{ij},[irf_distrib{ij}],'k-')
-            a=axis;
-            tmp=[];
-            for ir=1:length(itmp),
-                for it=1:length(endo_prior_restrictions.irf{itmp(ir),3})
-                temp_index = find(time_matrix{ij}==endo_prior_restrictions.irf{itmp(ir),3}(it));
-                tmp(temp_index,:) = endo_prior_restrictions.irf{itmp(ir),4};
+            if ~DynareOptions.nograph,
+                set(0,'currentfigure',h1);
+                subplot(nrow,ncol, ij)
+                itmp = (find(plot_indx==ij));
+                htmp = plot(time_matrix{ij},[max(irf_matrix{ij})' min(irf_matrix{ij})'],'k--','linewidth',2);
+                a=axis;
+                delete(htmp);
+                tmp=[];
+                for ir=1:length(itmp),
+                    for it=1:length(endo_prior_restrictions.irf{itmp(ir),3})
+                        temp_index = find(time_matrix{ij}==endo_prior_restrictions.irf{itmp(ir),3}(it));
+                        tmp(temp_index,:) = endo_prior_restrictions.irf{itmp(ir),4};
+                    end
+                end
+                %             tmp = cell2mat(endo_prior_restrictions.irf(itmp,4));
+                tmp(isinf(tmp(:,1)),1)=a(3);
+                tmp(isinf(tmp(:,2)),2)=a(4);
+                hp = patch([time_matrix{ij} time_matrix{ij}(end:-1:1)],[tmp(:,1); tmp(end:-1:1,2)],'c');
+                set(hp,'FaceColor',[0.7 0.8 1])
+                hold on,
+                plot(time_matrix{ij},[max(irf_matrix{ij})' min(irf_matrix{ij})'],'k--','linewidth',2)
+                plot(time_matrix{ij},irf_median{ij},'k','linewidth',2)
+                plot(time_matrix{ij},[irf_distrib{ij}],'k-')
+                plot(a(1:2),[0 0],'r')
+                hold off,
+                axis([max(1,a(1)) a(2:4)])
+                box on,
+                set(gca,'xtick',sort(time_matrix{ij}))
+                itmp = min(itmp);
+                title([endo_prior_restrictions.irf{itmp,1},' vs ',endo_prior_restrictions.irf{itmp,2}],'interpreter','none'),
+            end
+            if any(iplot_indx.*plot_indx==ij),
+                % MCF of the couples with logical AND
+                itmp = min(find(plot_indx==ij));
+                indx1 = find(indx_irf_matrix(:,ij)==0);
+                indx2 = find(indx_irf_matrix(:,ij)~=0);
+                leg = num2str(time_matrix{ij}(1));
+                leg = [leg '...' num2str(time_matrix{ij}(end))];
+                aleg = 'ALL';
+                atitle0=[endo_prior_restrictions.irf{itmp,1},' vs ',endo_prior_restrictions.irf{itmp,2}, '(', leg,')'];
+                fprintf(['%4.1f%% of the ',type,' support matches IRF restrictions ',atitle0,'\n'],length(indx1)/length(irestrictions)*100)
+                % aname=[type '_irf_calib_',int2str(ij)];
+                aname=[type '_irf_calib_',endo_prior_restrictions.irf{itmp,1},'_vs_',endo_prior_restrictions.irf{itmp,2},'_',aleg];
+                atitle=[type ' IRF Calib: Parameter(s) driving ',endo_prior_restrictions.irf{itmp,1},' vs ',endo_prior_restrictions.irf{itmp,2}, '(', leg,')'];
+                options_mcf.amcf_name = aname;
+                options_mcf.amcf_title = atitle;
+                options_mcf.beha_title = 'IRF restriction';
+                options_mcf.nobeha_title = 'NO IRF restriction';
+                options_mcf.title = atitle0;
+                if ~isempty(indx1) && ~isempty(indx2)
+                    mcf_analysis(xmat(:,nshock+1:end), indx1, indx2, options_mcf, DynareOptions);
                 end
             end
-%             tmp = cell2mat(endo_prior_restrictions.irf(itmp,4));
-            tmp(isinf(tmp(:,1)),1)=a(3);
-            tmp(isinf(tmp(:,2)),2)=a(4);
-            hp = patch([time_matrix{ij} time_matrix{ij}(end:-1:1)],tmp(:),'b');
-            set(hp,'FaceAlpha',[0.5])
-            plot(a(1:2),[0 0],'r')
-            hold off,
-            axis([max(1,a(1)) a(2:4)])
-            box on,
-            set(gca,'xtick',sort(time_matrix{ij}))
-            itmp = min(itmp);
-            title([endo_prior_restrictions.irf{itmp,1},' vs ',endo_prior_restrictions.irf{itmp,2}],'interpreter','none'),
         end
     end
-    dyn_saveas(h1,[OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions'],DynareOptions);
-
+    if ~DynareOptions.nograph,
+        dyn_saveas(h1,[OutputDirectoryName,filesep,fname_,'_',type,'_irf_restrictions'],DynareOptions);
+    end
+    
     skipline()
 end
 
 if ~isempty(indx_moment)
+    skipline()
+    disp('Deleting old MOMENT calibration plots ...')
+    a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_moment_calib*.eps']);
+    for j=1:length(a),
+        delete([OutputDirectoryName,filesep,a(j).name]);
+    end
+    a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_moment_calib*.fig']);
+    for j=1:length(a),
+        delete([OutputDirectoryName,filesep,a(j).name]);
+    end
+    a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_moment_calib*.pdf']);
+    for j=1:length(a),
+        delete([OutputDirectoryName,filesep,a(j).name]);
+    end
+    a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions.eps']);
+    for j=1:length(a),
+        delete([OutputDirectoryName,filesep,a(j).name]);
+    end
+    a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions.fig']);
+    for j=1:length(a),
+        delete([OutputDirectoryName,filesep,a(j).name]);
+    end
+    a=dir([OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions.pdf']);
+    for j=1:length(a),
+        delete([OutputDirectoryName,filesep,a(j).name]);
+    end
+    disp('done !')
+    skipline()
+    
     options_mcf.param_names = char(BayesInfo.name);
     all_moment_couples = cellstr([char(endo_prior_restrictions.moment(:,1)) char(endo_prior_restrictions.moment(:,2))]);
     moment_couples = unique(all_moment_couples);
     nbr_moment_couples = size(moment_couples,1);
     plot_indx = NaN(nbr_moment_couples,1);
     time_matrix=cell(nbr_moment_couples,1);
+    indx_moment_matrix=zeros(length(irestrictions),nbr_moment_couples);
     moment_matrix=cell(nbr_moment_couples,1);
     moment_mean=cell(nbr_moment_couples,1);
     moment_median=cell(nbr_moment_couples,1);
     moment_var=cell(nbr_moment_couples,1);
     moment_HPD=cell(nbr_moment_couples,1);
     moment_distrib=cell(nbr_moment_couples,1);
-    % For single legend search which has maximum nbr of restrictions 
+    % For single legend search which has maximum nbr of restrictions
     maxijv=0;
     for ij=1:nbr_moment_restrictions
         if length(endo_prior_restrictions.moment{ij,3})>maxijv
@@ -262,18 +360,22 @@ if ~isempty(indx_moment)
         plot_indx(ij) = find(strcmp(moment_couples,all_moment_couples(ij,:)));
         time_matrix{plot_indx(ij)} = [time_matrix{plot_indx(ij)} endo_prior_restrictions.moment{ij,3}];
     end
+    iplot_indx = ones(size(plot_indx));
     
     indx_moment = indx_moment(irestrictions,:);
-    h2=dyn_figure(DynareOptions,'name',[type ' evaluation of moment restrictions']);
-    nrow=ceil(sqrt(nbr_moment_couples));
-    ncol=nrow;
-    if nrow*(nrow-1)>nbr_moment_couples,
-        ncol=nrow-1;
+    if ~DynareOptions.nograph,
+        h2=dyn_figure(DynareOptions,'name',[type ' evaluation of moment restrictions']);
+        nrow=ceil(sqrt(nbr_moment_couples));
+        ncol=nrow;
+        if nrow*(nrow-1)>nbr_moment_couples,
+            ncol=nrow-1;
+        end
     end
     
     for ij=1:nbr_moment_restrictions,
         mat_moment{ij}=mat_moment{ij}(irestrictions,:);
         moment_matrix{plot_indx(ij)} = [moment_matrix{plot_indx(ij)} mat_moment{ij}];
+        indx_moment_matrix(:,plot_indx(ij)) = indx_moment_matrix(:,plot_indx(ij)) + indx_moment(:,ij);
         for ik=1:size(mat_moment{ij},2),
             [Mean,Median,Var,HPD,Distrib] = ...
                 posterior_moments(mat_moment{ij}(:,ik),0,DynareOptions.mh_conf_sig);
@@ -288,82 +390,113 @@ if ~isempty(indx_moment)
         if size(mat_moment{ij},2)>1,
             leg = [leg,':' ,num2str(endo_prior_restrictions.moment{ij,3}(end))];
             aleg = [aleg,'_' ,num2str(endo_prior_restrictions.moment{ij,3}(end))];
+            iplot_indx(ij)=0;
         end
-        if length(time_matrix{plot_indx(ij)})==1,
-            figure(h2),
+        if ~DynareOptions.nograph && length(time_matrix{plot_indx(ij)})==1,
+            set(0,'currentfigure',h2);
             subplot(nrow,ncol,plot_indx(ij)),
             hc = cumplot(mat_moment{ij}(:,ik));
-            set(hc,'color','k','linewidth',2)
-            hold all,
+            a=axis; delete(hc),
             %     hist(mat_moment{ij}),
-            a=axis;
             x1val=max(endo_prior_restrictions.moment{ij,4}(1),a(1));
             x2val=min(endo_prior_restrictions.moment{ij,4}(2),a(2));
             hp = patch([x1val x2val x2val x1val],a([3 3 4 4]),'b');
-            set(hp,'FaceAlpha', 0.5)
+            set(hp,'FaceColor', [0.7 0.8 1])
+            hold all,
+            hc = cumplot(mat_moment{ij}(:,ik));
+            set(hc,'color','k','linewidth',2)
             hold off,
             title([endo_prior_restrictions.moment{ij,1},' vs ',endo_prior_restrictions.moment{ij,2},'(',leg,')'],'interpreter','none'),
-%         if ij==maxij
-%             leg1 = num2str(endo_prior_restrictions.moment{ij,3}(:));
-%             [legend_h,object_h,plot_h,text_strings]=legend(leg1);
-%             Position=get(legend_h,'Position');Position(1:2)=[-0.055 0.95-Position(4)];
-%             set(legend_h,'Position',Position);
-%         end
+            %         if ij==maxij
+            %             leg1 = num2str(endo_prior_restrictions.moment{ij,3}(:));
+            %             [legend_h,object_h,plot_h,text_strings]=legend(leg1);
+            %             Position=get(legend_h,'Position');Position(1:2)=[-0.055 0.95-Position(4)];
+            %             set(legend_h,'Position',Position);
+            %         end
         end
         indx1 = find(indx_moment(:,ij)==0);
         indx2 = find(indx_moment(:,ij)~=0);
         atitle0=[endo_prior_restrictions.moment{ij,1},' vs ',endo_prior_restrictions.moment{ij,2}, '(', leg,')'];
-        fprintf(['%4.1f%% of the prior support matches MOMENT ',atitle0,' inside [%4.1f, %4.1f]\n'],length(indx1)/length(irestrictions)*100,endo_prior_restrictions.moment{ij,4})
+        fprintf(['%4.1f%% of the ',type,' support matches MOMENT ',atitle0,' inside [%4.1f, %4.1f]\n'],length(indx1)/length(irestrictions)*100,endo_prior_restrictions.moment{ij,4})
         % aname=[type '_moment_calib_',int2str(ij)];
         aname=[type '_moment_calib_',endo_prior_restrictions.moment{ij,1},'_vs_',endo_prior_restrictions.moment{ij,2},'_',aleg];
         atitle=[type ' MOMENT Calib: Parameter(s) driving ',endo_prior_restrictions.moment{ij,1},' vs ',endo_prior_restrictions.moment{ij,2}, '(', leg,')'];
         options_mcf.amcf_name = aname;
         options_mcf.amcf_title = atitle;
-        options_mcf.beha_title = 'moment prior restriction';
-        options_mcf.nobeha_title = 'NO moment prior restriction';
+        options_mcf.beha_title = 'moment restriction';
+        options_mcf.nobeha_title = 'NO moment restriction';
         options_mcf.title = atitle0;
         if ~isempty(indx1) && ~isempty(indx2)
             mcf_analysis(xmat, indx1, indx2, options_mcf, DynareOptions);
         end
         
-%         [proba, dproba] = stab_map_1(xmat, indx1, indx2, aname, 0);
-%         indplot=find(proba<pvalue_ks);
-%         if ~isempty(indplot)
-%             stab_map_1(xmat, indx1, indx2, aname, 1, indplot, OutputDirectoryName,[],atitle);
-%         end
+        %         [proba, dproba] = stab_map_1(xmat, indx1, indx2, aname, 0);
+        %         indplot=find(proba<pvalue_ks);
+        %         if ~isempty(indplot)
+        %             stab_map_1(xmat, indx1, indx2, aname, 1, indplot, OutputDirectoryName,[],atitle);
+        %         end
     end
-    figure(h2);
     for ij=1:nbr_moment_couples,
         if length(time_matrix{ij})>1,
-            subplot(nrow,ncol, ij)
-            itmp = (find(plot_indx==ij));
-            plot(time_matrix{ij},[max(moment_matrix{ij})' min(moment_matrix{ij})'],'k--','linewidth',2)
-            hold on,
-            plot(time_matrix{ij},moment_median{ij},'k','linewidth',2)
-            plot(time_matrix{ij},[moment_distrib{ij}],'k-')
-            a=axis;
-            tmp=[];
-            for ir=1:length(itmp),
-                for it=1:length(endo_prior_restrictions.moment{itmp(ir),3})
-                temp_index = find(time_matrix{ij}==endo_prior_restrictions.moment{itmp(ir),3}(it));
-                tmp(temp_index,:) = endo_prior_restrictions.moment{itmp(ir),4};
+            if ~DynareOptions.nograph
+                itmp = (find(plot_indx==ij));
+                set(0,'currentfigure',h2);
+                subplot(nrow,ncol, ij)
+                htmp = plot(time_matrix{ij},[max(moment_matrix{ij})' min(moment_matrix{ij})'],'k--','linewidth',2);
+                a=axis;
+                delete(htmp);
+                tmp=[];
+                for ir=1:length(itmp),
+                    for it=1:length(endo_prior_restrictions.moment{itmp(ir),3})
+                        temp_index = find(time_matrix{ij}==endo_prior_restrictions.moment{itmp(ir),3}(it));
+                        tmp(temp_index,:) = endo_prior_restrictions.moment{itmp(ir),4};
+                    end
+                end
+                %             tmp = cell2mat(endo_prior_restrictions.moment(itmp,4));
+                tmp(isinf(tmp(:,1)),1)=a(3);
+                tmp(isinf(tmp(:,2)),2)=a(4);
+                hp = patch([time_matrix{ij} time_matrix{ij}(end:-1:1)],[tmp(:,1); tmp(end:-1:1,2)],'b');
+                set(hp,'FaceColor',[0.7 0.8 1])
+                hold on,
+                plot(time_matrix{ij},[max(moment_matrix{ij})' min(moment_matrix{ij})'],'k--','linewidth',2)
+                plot(time_matrix{ij},moment_median{ij},'k','linewidth',2)
+                plot(time_matrix{ij},[moment_distrib{ij}],'k-')
+                plot(a(1:2),[0 0],'r')
+                hold off,
+                axis(a)
+                box on,
+                set(gca,'xtick',sort(time_matrix{ij}))
+                itmp = min(itmp);
+                title([endo_prior_restrictions.moment{itmp,1},' vs ',endo_prior_restrictions.moment{itmp,2}],'interpreter','none'),
+            end
+            if any(iplot_indx.*plot_indx==ij),
+                % MCF of the couples with logical AND
+                itmp = min(find(plot_indx==ij));
+                indx1 = find(indx_moment_matrix(:,ij)==0);
+                indx2 = find(indx_moment_matrix(:,ij)~=0);
+                leg = num2str(time_matrix{ij}(1));
+                leg = [leg '...' num2str(time_matrix{ij}(end))];
+                aleg = 'ALL';
+                atitle0=[endo_prior_restrictions.moment{itmp,1},' vs ',endo_prior_restrictions.moment{itmp,2}, '(', leg,')'];
+                fprintf(['%4.1f%% of the ',type,' support matches MOMENT restrictions ',atitle0,'\n'],length(indx1)/length(irestrictions)*100)
+                % aname=[type '_moment_calib_',int2str(ij)];
+                aname=[type '_moment_calib_',endo_prior_restrictions.moment{itmp,1},'_vs_',endo_prior_restrictions.moment{itmp,2},'_',aleg];
+                atitle=[type ' MOMENT Calib: Parameter(s) driving ',endo_prior_restrictions.moment{itmp,1},' vs ',endo_prior_restrictions.moment{itmp,2}, '(', leg,')'];
+                options_mcf.amcf_name = aname;
+                options_mcf.amcf_title = atitle;
+                options_mcf.beha_title = 'moment restriction';
+                options_mcf.nobeha_title = 'NO moment restriction';
+                options_mcf.title = atitle0;
+                if ~isempty(indx1) && ~isempty(indx2)
+                    mcf_analysis(xmat, indx1, indx2, options_mcf, DynareOptions);
                 end
             end
-%             tmp = cell2mat(endo_prior_restrictions.moment(itmp,4));
-            tmp(isinf(tmp(:,1)),1)=a(3);
-            tmp(isinf(tmp(:,2)),2)=a(4);
-            hp = patch([time_matrix{ij} time_matrix{ij}(end:-1:1)],tmp(:),'b');
-            set(hp,'FaceAlpha',[0.5])
-            plot(a(1:2),[0 0],'r')
-            hold off,
-            axis(a)
-            box on,
-            set(gca,'xtick',sort(time_matrix{ij}))
-            itmp = min(itmp);
-            title([endo_prior_restrictions.moment{itmp,1},' vs ',endo_prior_restrictions.moment{itmp,2}],'interpreter','none'),
         end
     end
-    dyn_saveas(h2,[OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions'],DynareOptions);
+    if ~DynareOptions.nograph,
+        dyn_saveas(h2,[OutputDirectoryName,filesep,fname_,'_',type,'_moment_restrictions'],DynareOptions);
+    end
+    
     skipline()
 end
 return
diff --git a/matlab/gsa/mcf_analysis.m b/matlab/gsa/mcf_analysis.m
index fb46c51bcd4b7c18bd58575d9facaeb489ac39a8..cb7e92a10531e2d1493c34db7f5254652362210b 100644
--- a/matlab/gsa/mcf_analysis.m
+++ b/matlab/gsa/mcf_analysis.m
@@ -1,4 +1,4 @@
-function mcf_analysis(lpmat, ibeha, inobeha, options_mcf, DynareOptions)
+function indmcf = mcf_analysis(lpmat, ibeha, inobeha, options_mcf, DynareOptions)
 %
 % Written by Marco Ratto
 % Joint Research Centre, The European Commission,
@@ -53,7 +53,7 @@ if length(ibeha)>10 && length(inobeha)>10,
     indcorr = indcorr(~ismember(indcorr(:),indmcf));
     indmcf = [indmcf(:); indcorr(:)];
 end
-if ~isempty(indmcf)
+if ~isempty(indmcf) && ~DynareOptions.nograph,
     skipline()
     scatter_mcf(lpmat(ibeha,indmcf),lpmat(inobeha,indmcf), param_names(indmcf,:), ...
         '.', [fname_,'_',amcf_name], OutputDirectoryName, amcf_title,[], DynareOptions, ...
diff --git a/matlab/gsa/redform_map.m b/matlab/gsa/redform_map.m
index 7421e1c923d6efdd079a4223876e4955ebd0dc57..448b1a634d0ab96706aa239efc3adc431c338d82 100644
--- a/matlab/gsa/redform_map.m
+++ b/matlab/gsa/redform_map.m
@@ -53,21 +53,31 @@ 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),:);
+fname_ = M_.fname;
 
 bounds = prior_bounds(bayestopt_,options_);
 
-pnames = M_.param_names(estim_params_.param_vals(:,1),:);
 if nargin==0,
     dirname='';
 end
 
 if pprior
     load([dirname,filesep,M_.fname,'_prior'],'lpmat', 'lpmat0', 'istable','T');
-    adir=[dirname filesep 'redform_stab'];
+    adir=[dirname filesep 'redform_prior'];
+    type = 'prior';
 else
     load([dirname,filesep,M_.fname,'_mc'],'lpmat', 'lpmat0', 'istable','T');
     adir=[dirname filesep 'redform_mc'];
+    type = 'mc';
 end
+options_mcf.pvalue_ks = options_gsa_.ksstat_redform;
+options_mcf.pvalue_corr = options_gsa_.alpha2_redform;
+options_mcf.alpha2 = options_gsa_.alpha2_redform;
+options_mcf.param_names = pnames;
+options_mcf.fname_ = M_.fname;
+options_mcf.OutputDirectoryName = adir;
+
 if ~exist('T')
     stab_map_(dirname,options_gsa_);
     if pprior
@@ -106,6 +116,15 @@ else
     pd =  [bayestopt_.p6(offset+1:end) bayestopt_.p7(offset+1:end) bayestopt_.p3(offset+1:end) bayestopt_.p4(offset+1:end)];
 end
 
+options_map.param_names = pnames;
+options_map.fname_ = M_.fname;
+options_map.OutputDirectoryName = adir;
+options_map.iload = iload;
+options_map.log_trans = ilog;
+options_map.prior_range = options_gsa_.prior_range;
+options_map.pshape = pshape;
+options_map.pd = pd;
+
 nsok = length(find(M_.lead_lag_incidence(M_.maximum_lag,:)));
 lpmat=[];
 lpmat0=[];
@@ -119,7 +138,7 @@ for j=1:size(anamendo,1)
         namexo=deblank(anamexo(jx,:));
         iexo=strmatch(namexo,M_.exo_names,'exact');
         skipline()
-        disp(['[', namendo,' vs. ',namexo,']'])
+        disp(['[', namendo,' vs ',namexo,']'])
 
         
         if ~isempty(iexo),
@@ -128,7 +147,7 @@ for j=1:size(anamendo,1)
             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',['Reduced Form Mapping: ', namendo,' vs. shocks ',int2str(ifig)]);
+                    hfig = dyn_figure(options_,'name',['Reduced Form Mapping: ', namendo,' vs shocks ',int2str(ifig)]);
                     iplo=0;
                 end
                 iplo=iplo+1;
@@ -139,7 +158,15 @@ for j=1:size(anamendo,1)
                         if isempty(dir(xdir0))
                             mkdir(xdir0)
                         end
-                        si(:,js) = redform_private(x0, y0, pshape, pd, iload, pnames, namendo, namexo, xdir0, options_gsa_);
+                        atitle0=['Reduced Form Mapping (ANOVA) for ',namendo,' vs ', namexo];
+                        aname=[type '_' namendo '_vs_' namexo];
+                        atitle=[type ' Reduced Form Mapping (ANOVA): Parameter(s) driving ',namendo,' vs ',namexo];
+                        options_map.amap_name = aname;
+                        options_map.amap_title = atitle;
+                        options_map.figtitle = atitle0;
+                        options_map.title = [namendo,' vs ', namexo];
+                        options_map.OutputDirectoryName = xdir0;
+                        si(:,js) = redform_private(x0, y0, options_map, options_);
                     else
                         iy=find( (y0>threshold(1)) & (y0<threshold(2)));
                         iyc=find( (y0<=threshold(1)) | (y0>=threshold(2)));
@@ -148,41 +175,65 @@ for j=1:size(anamendo,1)
                             mkdir(xdir)
                         end
                         if ~options_.nograph,
-                            hf=dyn_figure(options_,'name',['Reduced Form Mapping: ',namendo,' vs. ', namexo]); hist(y0,30), title([namendo,' vs. ', namexo],'interpreter','none')
-                            dyn_saveas(hf,[xdir,filesep, namendo,'_vs_', namexo],options_);
+                            hf=dyn_figure(options_,'name',['Reduced Form Mapping (Monte Carlo Filtering): ',namendo,' vs ', namexo]); 
+                            hc = cumplot(y0);
+                            a=axis; delete(hc);
+                            %     hist(mat_moment{ij}),
+                            x1val=max(threshold(1),a(1));
+                            x2val=min(threshold(2),a(2));
+                            hp = patch([x1val x2val x2val x1val],a([3 3 4 4]),'b');
+                            set(hp,'FaceColor', [0.7 0.8 1])
+                            hold all,
+                            hc = cumplot(y0);
+                            set(hc,'color','k','linewidth',2)
+                            hold off,
+                            title([namendo,' vs ', namexo ' - threshold [' num2str(threshold(1)) ' ' num2str(threshold(2)) ']'],'interpreter','none')
+                            dyn_saveas(hf,[xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namexo],options_);
                         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 length(iy)>size(x0,2) && length(iyc)>size(x0,2)
-                            delete([xdir, '/*threshold*.*'])
-                            [proba, dproba] = stab_map_1(x0, iy, iyc, 'threshold',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
-                            skipline()
-                            stab_map_1(x0, iy, iyc, 'threshold',pvalue_ks,indsmirnov,xdir,[],['Reduced Form Mapping (Threshold) for ', namendo,' vs. lagged ', namexo]);
-                            stab_map_2(x0(iy,:),alpha2,pvalue_corr,'inside_threshold',xdir,[],['Reduced Form Mapping (Inside Threshold)for ', namendo,' vs. lagged ', namexo])
-                            stab_map_2(x0(iyc,:),alpha2,pvalue_corr,'outside_threshold',xdir,[],['Reduced Form Mapping (Outside Threshold) for ', namendo,' vs. lagged ', namexo])
+                        delete([xdir, '/*threshold*.*'])
+                        
+                        atitle0=['Reduced Form Mapping (Monte Carlo Filtering) for ',namendo,' vs ', namexo];
+                        aname=[type '_' namendo '_vs_' namexo '_threshold'];
+                        atitle=[type ' Reduced Form Mapping (Monte Carlo Filtering): Parameter(s) driving ',namendo,' vs ',namexo];
+                        options_mcf.amcf_name = aname;
+                        options_mcf.amcf_title = atitle;
+                        options_mcf.beha_title = 'inside threshold';
+                        options_mcf.nobeha_title = 'outside threshold';
+                        options_mcf.title = atitle0;
+                        options_mcf.OutputDirectoryName = xdir;
+                        if ~isempty(iy) && ~isempty(iyc)
+                            fprintf(['%4.1f%% of the ',type,' support matches ',atitle0,'\n'],length(iy)/length(y0)*100)
+                            icheck = mcf_analysis(x0, iy, iyc, options_mcf, options_);
+                            
                             lpmat=x0(iy,:);
                             if nshocks,
                                 lpmat0=xx0(iy,:);
                             end
                             istable=[1:length(iy)];
-                            save([xdir,filesep,'threshold.mat'],'lpmat','lpmat0','istable','y0','x0','xx0','iy','iyc')
+                            save([xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namexo '_threshold' ],'lpmat','lpmat0','istable','y0','x0','xx0','iy','iyc')
                             lpmat=[]; lpmat0=[]; istable=[];
+                        else
+                            icheck=[];
+                        end
+                        if isempty(icheck),
+                            atitle0=['Monte Carlo Filtering for ',namendo,' vs ', namexo];
+                            options_mcf.title = atitle0;
+                            indmcf = redform_mcf(y0, x0, options_mcf, options_);
+                            
                         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_);
+                    atitle0=['Reduced Form Mapping (ANOVA) for log-transformed ',namendo,' vs ', namexo];
+                    aname=[type '_' namendo '_vs_' namexo];
+                    atitle=[type ' Reduced Form Mapping (ANOVA): Parameter(s) driving ',namendo,' vs ',namexo];
+                    options_map.amap_name = aname;
+                    options_map.amap_title = atitle;
+                    options_map.figtitle = atitle0;
+                    options_map.title = ['log(' namendo ' vs ' namexo ')'];
+                    options_map.OutputDirectoryName = xdir0;
+                    silog(:,js) = redform_private(x0, y0, options_map, options_);
                 end
                 
                 if isempty(threshold) && ~options_.nograph,
@@ -203,7 +254,7 @@ for j=1:size(anamendo,1)
                     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')
+                    title([logflag,' ',namendo,' vs ',namexo],'interpreter','none')
                     if iplo==9,
                         dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_shocks_',logflag,num2str(ifig)],options_);
                     end
@@ -221,7 +272,7 @@ for j=1:size(anamendo,1)
         namlagendo=deblank(anamlagendo(je,:));
         ilagendo=strmatch(namlagendo,M_.endo_names(oo_.dr.order_var(M_.nstatic+1:M_.nstatic+nsok),:),'exact');
         skipline()
-        disp(['[', namendo,' vs. lagged ',namlagendo,']'])
+        disp(['[', namendo,' vs lagged ',namlagendo,']'])
         
         if ~isempty(ilagendo),
             %y0=squeeze(T(iendo,ilagendo,istable));
@@ -229,7 +280,7 @@ for j=1:size(anamendo,1)
             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',['Reduced Form Mapping: ' namendo,' vs. lags ',int2str(ifig)]);
+                    hfig = dyn_figure(options_,'name',['Reduced Form Mapping: ' namendo,' vs lags ',int2str(ifig)]);
                     iplo=0;
                 end
                 iplo=iplo+1;
@@ -240,7 +291,15 @@ for j=1:size(anamendo,1)
                         if isempty(dir(xdir0))
                             mkdir(xdir0)
                         end
-                        si(:,js) = redform_private(x0, y0, pshape, pd, iload, pnames, namendo, namlagendo, xdir0, options_gsa_);
+                        atitle0=['Reduced Form Mapping (ANOVA) for ',namendo,' vs ', namlagendo];
+                        aname=[type '_' namendo '_vs_' namlagendo];
+                        atitle=[type ' Reduced Form Mapping (ANOVA): Parameter(s) driving ',namendo,' vs ',namlagendo];
+                        options_map.amap_name = aname;
+                        options_map.amap_title = atitle;
+                        options_map.figtitle = atitle0;
+                        options_map.title = [namendo,' vs ', namlagendo];
+                        options_map.OutputDirectoryName = xdir0;
+                        si(:,js) = redform_private(x0, y0, options_map, options_);
                     else
                         iy=find( (y0>threshold(1)) & (y0<threshold(2)));
                         iyc=find( (y0<=threshold(1)) | (y0>=threshold(2)));
@@ -248,41 +307,67 @@ for j=1:size(anamendo,1)
                         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_,'name',['Reduced Form Mapping: ',namendo,' vs. lagged ', namlagendo]); hist(y0,30), title([namendo,' vs. lagged ', namlagendo],'interpreter','none')
-                            dyn_saveas(hf,[xdir,filesep, namendo,'_vs_', namlagendo],options_);
+                            hf=dyn_figure(options_,'name',['Reduced Form Mapping (Monte Carlo Filtering): ',namendo,' vs lagged ', namlagendo]); 
+                            hc = cumplot(y0);
+                            a=axis; delete(hc);
+                            %     hist(mat_moment{ij}),
+                            x1val=max(threshold(1),a(1));
+                            x2val=min(threshold(2),a(2));
+                            hp = patch([x1val x2val x2val x1val],a([3 3 4 4]),'b');
+                            set(hp,'FaceColor', [0.7 0.8 1])
+                            hold all,
+                            hc = cumplot(y0);
+                            set(hc,'color','k','linewidth',2)
+                            hold off,
+                            title([namendo,' vs lagged ', namlagendo ' - threshold [' num2str(threshold(1)) ' ' num2str(threshold(2)) ']'],'interpreter','none')
+                            dyn_saveas(hf,[xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namlagendo],options_);
                         end
-                        if length(iy)>size(x0,2) && length(iyc)>size(x0,2),
-                            delete([xdir, '/*threshold*.*'])
-                            [proba, dproba] = stab_map_1(x0, iy, iyc, 'threshold',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
-                            skipline()
-                            stab_map_1(x0, iy, iyc, 'threshold',pvalue_ks,indsmirnov,xdir,[],['Reduced Form Mapping (Threshold) for ', namendo,' vs. lagged ', namlagendo]);
-                            stab_map_2(x0(iy,:),alpha2,pvalue_corr,'inside_threshold',xdir,[],['Reduced Form Mapping (Inside Threshold) for ', namendo,' vs. lagged ', namlagendo])
-                            stab_map_2(x0(iyc,:),alpha2,pvalue_corr,'outside_threshold',xdir,[],['Reduced Form Mapping (Outside Threshold) for ', namendo,' vs. lagged ', namlagendo])
+                        
+                        delete([xdir, '/*threshold*.*'])
+                        
+                        atitle0=['Reduced Form Mapping (Monte Carlo Filtering) for ',namendo,' vs ', namlagendo];
+                        aname=[type '_' namendo '_vs_' namlagendo '_threshold'];
+                        atitle=[type ' Reduced Form Mapping (Monte Carlo Filtering): Parameter(s) driving ',namendo,' vs ',namlagendo];
+                        options_mcf.amcf_name = aname;
+                        options_mcf.amcf_title = atitle;
+                        options_mcf.beha_title = 'inside threshold';
+                        options_mcf.nobeha_title = 'outside threshold';
+                        options_mcf.title = atitle0;
+                        options_mcf.OutputDirectoryName = xdir;
+                        if ~isempty(iy) && ~isempty(iyc)
+
+                            fprintf(['%4.1f%% of the ',type,' support matches ',atitle0,'\n'],length(iy)/length(y0)*100)
+                            icheck = mcf_analysis(x0, iy, iyc, options_mcf, options_);
+                            
                             lpmat=x0(iy,:);
                             if nshocks,
                                 lpmat0=xx0(iy,:);
                             end
                             istable=[1:length(iy)];
-                            save([xdir,filesep,'threshold.mat'],'lpmat','lpmat0','istable','y0','x0','xx0','iy','iyc')
+                            save([xdir,filesep, fname_ '_' type '_' namendo,'_vs_', namlagendo '_threshold' ],'lpmat','lpmat0','istable','y0','x0','xx0','iy','iyc')
                             lpmat=[]; lpmat0=[]; istable=[];
                             
+                        else
+                            icheck = [];
+                        end
+                        if isempty(icheck),
+                            atitle0=['Monte Carlo Filtering for ',namendo,' vs ', namlagendo];
+                            options_mcf.title = atitle0;
+                            indmcf = redform_mcf(y0, x0, options_mcf, options_);
                         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_);
+                    atitle0=['Reduced Form Mapping (ANOVA) for log-transformed ',namendo,' vs ', namlagendo];
+                    aname=[type '_' namendo '_vs_' namlagendo];
+                    atitle=[type ' Reduced Form Mapping (ANOVA): Parameter(s) driving ',namendo,' vs ',namlagendo];
+                    options_map.amap_name = aname;
+                    options_map.amap_title = atitle;
+                    options_map.figtitle = atitle0;
+                    options_map.title = ['log(' namendo ' vs ' namlagendo ')'];
+                    options_map.OutputDirectoryName = xdir0;
+                    silog(:,js) = redform_private(x0, y0, options_map, options_);
                 end
                 
                 if isempty(threshold) && ~options_.nograph
@@ -303,7 +388,7 @@ for j=1:size(anamendo,1)
                     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')
+                    title([logflag,' ',namendo,' vs ',namlagendo,'(-1)'],'interpreter','none')
                     if iplo==9,
                         dyn_saveas(hfig,[dirname,filesep,M_.fname,'_redform_', namendo,'_vs_lags_',logflag,num2str(ifig)],options_);
                     end
@@ -351,13 +436,17 @@ if isempty(threshold) && ~options_.nograph,
     end
 end
 
-function si  = redform_private(x0, y0, pshape, pd, iload, pnames, namy, namx, xdir, opt_gsa)
-global bayestopt_ options_
+function si  = redform_private(x0, y0, options_map, options_)
 
-% opt_gsa=options_.opt_gsa;
 np=size(x0,2);
 x00=x0;
-if opt_gsa.prior_range,
+ilog = options_map.log_trans;
+iload = options_map.iload;
+pnames = options_map.param_names;
+pd = options_map.pd;
+pshape = options_map.pshape;
+xdir = options_map.OutputDirectoryName;
+if options_map.prior_range,
     for j=1:np,
         x0(:,j)=(x0(:,j)-pd(j,3))./(pd(j,4)-pd(j,3));
     end
@@ -365,61 +454,286 @@ else
     x0=priorcdf(x0,pshape, pd(:,1), pd(:,2), pd(:,3), pd(:,4));
 end
 
-fname=[xdir,'/map'];
+if ilog,
+    fname=[xdir filesep options_map.fname_ '_' options_map.amap_name '_log'];
+else
+    fname=[xdir filesep options_map.fname_ '_' options_map.amap_name];
+end
 if iload==0,
     if isempty(dir(xdir))
         mkdir(xdir)
     end
-    if ~options_.nograph,
-        hfig=dyn_figure(options_,'name',['Reduced Form Mapping: ', namy,' vs. ', namx]); hist(y0,30), title([namy,' vs. ', namx],'interpreter','none')
-        dyn_saveas(hfig,[xdir,filesep, namy,'_vs_', namx],options_);
-    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);
+%     gsa_ = gsa_sdp(y0(1:nest), x0(1:nest,:), 2, [],[-1 -1 -1 -1 -1 0],[],0,[fname,'_est'], pnames);
+    [ys,is] = sort(y0);
+    istep = ceil(nrun/nest);
+    iest = is(floor(istep/2):istep:end);
+    nest = length(iest);
+    irest = is(setdiff([1:nrun],[floor(istep/2):istep:nrun]));
+    istep = ceil(length(irest)/(nfit-nest));
+    ifit = union(iest, irest(1:istep:end));
+    if ~ismember(irest(end),ifit),
+        ifit = union(ifit, irest(end));
+    end
+    nfit=length(ifit);
+%     ifit = union(iest, irest(randperm(nrun-nest,nfit-nest)));
+%     ifit = iest;
+%     nfit=nest;
+    ipred = setdiff([1:nrun],ifit);
+
+    if ilog,
+        [y1, tmp, isig, lam] = log_trans_(y0(iest));
+        y1 = log(y0*isig+lam);
     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)));
-        if options_.nodisplay
-            close(hfig);
+        hfig=dyn_figure(options_,'name',options_map.figtitle); 
+        subplot(221)
+        if ilog,
+            hist(y1,30),
+        else
+            hist(y0,30),
+        end
+        title(options_map.title,'interpreter','none')
+        subplot(222)
+        if ilog,
+            hc = cumplot(y1);
+        else
+            hc = cumplot(y0);
         end
+        set(hc,'color','k','linewidth',2)
+        title([options_map.title ' CDF'],'interpreter','none')
+    end
+
+    gsa0 = ss_anova(y0(iest), x0(iest,:), 1);
+    if ilog,
+        [gsa22, gsa1, gsax] = ss_anova_log(y1(iest), x0(iest,:), isig, lam, gsa0);
+    end
+%     if (gsa1.out.bic-gsa0.out.bic) < 10,
+%         y00=y0;
+%         gsa00=gsa0;
+%         gsa0=gsa1;
+%         y0=y1;
+%         ilog=1;
+%     end
+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);
+    nvr =  gsa0.nvr*nest^3/nfit^3;
+    nvr(gsa0.stat<2) = gsa0.nvr(gsa0.stat<2)*nest^5/nfit^5;
+    gsa_ = ss_anova(y0(ifit), x0(ifit,:), 1, 0, 2, nvr);
+    if ilog
+        gsa0 = gsa_;
+        nvr1 =  gsa1.nvr*nest^3/nfit^3;
+        nvr1(gsa1.stat<2) = gsa1.nvr(gsa1.stat<2)*nest^5/nfit^5;
+        nvrx =  gsax.nvr*nest^3/nfit^3;
+        nvrx(gsax.stat<2) = gsax.nvr(gsax.stat<2)*nest^5/nfit^5;
+        [gsa22, gsa1, gsax] = ss_anova_log(y1(ifit), x0(ifit,:), isig, lam, gsa0, [nvr1' nvrx']);
+%         gsa1 = ss_anova(y1(ifit), x0(ifit,:), 1, 0, 2, nvr);
+%         gsa2=gsa1;
+%         gsa2.y = gsa0.y;
+%         gsa2.fit = (exp(gsa1.fit)-lam)*isig;
+%         gsa2.f0 = mean(gsa2.fit);
+%         gsa2.out.SSE = sum((gsa2.fit-gsa2.y).^2);
+%         gsa2.out.bic = gsa2.out.bic-nest*log(gsa1.out.SSE)+nest*log(gsa2.out.SSE);
+%         gsa2.r2 = 1-cov(gsa2.fit-gsa2.y)/cov(gsa2.y);
+%         for j=1:np,
+%             gsa2.fs(:,j) = exp(gsa1.fs(:,j)).*mean(exp(gsa1.fit-gsa1.f(:,j)))*isig-lam*isig-gsa2.f0;
+%             gsa2.f(:,j) = exp(gsa1.f(:,j)).*mean(exp(gsa1.fit-gsa1.f(:,j)))*isig-lam*isig-gsa2.f0;
+%             gsa2.si(j) = var(gsa2.f(:,j))/var(gsa2.y);
+%         end
+%         nvr =  gsax.nvr*nest^3/nfit^3;
+%         nvr(gsax.stat<2) = gsax.nvr(gsax.stat<2)*nest^5/nfit^5;
+%         gsax = ss_anova([gsa2.y-gsa2.fit], x0(ifit,:), 1, 0, 2, nvr);
+%         gsa22=gsa2;
+%         gsa22.fit = gsa2.fit+gsax.fit;
+%         gsa22.f0 = mean(gsa22.fit);
+%         gsa22.out.SSE = sum((gsa22.fit-gsa22.y).^2);
+%         gsa22.out.bic = nest*log(gsa22.out.SSE/nest) + (gsax.out.df+gsa2.out.df-1)*log(nest);
+%         gsa22.r2 = 1-sum((gsa22.fit-gsa22.y).^2)/sum((gsa22.y-mean(gsa22.y)).^2);
+%         for j=1:np,
+%             gsa22.fs(:,j) = gsa2.fs(:,j)+gsax.fs(:,j);
+%             gsa22.f(:,j) = gsa2.f(:,j)+gsax.f(:,j);
+%             gsa22.si(j) = var(gsa22.f(:,j))/var(gsa22.y);
+%         end
+        gsa_ = gsa22;
+    end
+else
+    if ilog
+        gsa_ = gsa22;
+    else
+        gsa_ = gsa0;
+    end
+end
+    save([fname,'_map.mat'],'gsa_')
+    [sidum, iii]=sort(-gsa_.si);
+    gsa_.x0=x00(ifit,:);
+    if ~options_.nograph,
+        hmap=gsa_sdp_plot(gsa_,[fname '_map'],pnames,iii(1:min(12,np)));
+        set(hmap,'name',options_map.amap_title);
     end
-    gsa_.x0=x0(1:nfit,:);
+    gsa_.x0=x0(ifit,:);
     %   copyfile([fname,'_est.mat'],[fname,'.mat'])
     if ~options_.nograph,
-        hfig=dyn_figure(options_,'name',['Reduced Form Mapping: ' namy,'_vs_', namx,'_fit']);
-        plot(y0(1:nfit),[gsa_.fit y0(1:nfit)],'.'),
-        title([namy,' vs. ', namx,' fit'],'interpreter','none')
-        dyn_saveas(hfig,[xdir,filesep, namy,'_vs_', namx,'_fit'],options_);
+        figure(hfig);
+        subplot(223),
+        plot(y0(ifit),[gsa_.fit y0(ifit)],'.'),
+        r2 = gsa_.r2;
+%         if ilog,
+%             plot(y00(ifit),[log_trans_(gsa_.fit,'',isig,lam) y00(ifit)],'.'),
+%             r2 = 1 - cov(log_trans_(gsa_.fit,'',isig,lam)-y00(ifit))/cov(y00(ifit));
+%         else               
+%             plot(y0(ifit),[gsa_.fit y0(ifit)],'.'),
+%             r2 = gsa_.r2;
+%         end
+        title(['Learning sample fit - R2=' num2str(r2,2)],'interpreter','none')
         if nfit<nrun,
-            npred=[nfit+1:nrun];
-            yf = ss_anova_fcast(x0(npred,:), gsa_);
-            hfig=dyn_figure(options_,'name',['Reduced Form Mapping: ' namy,'_vs_', namx,'_pred']);
-            plot(y0(npred),[yf y0(npred)],'.'),
-            title([namy,' vs. ', namx,' pred'],'interpreter','none')
-            dyn_saveas(hfig,[xdir,filesep, namy,'_vs_', namx,'_pred'],options_);
+            if ilog,
+                yf = ss_anova_fcast(x0(ipred,:), gsa1);
+                yf = log_trans_(yf,'',isig,lam)+ss_anova_fcast(x0(ipred,:), gsax);
+            else
+                yf = ss_anova_fcast(x0(ipred,:), gsa_);
+            end
+            yn = y0(ipred);
+            r2  = 1-cov(yf-yn)/cov(yn);
+            subplot(224),
+            plot(yn,[yf yn],'.'),
+            title(['Out-of-sample prediction - R2=' num2str(r2,2)],'interpreter','none')
         end
+        dyn_saveas(hfig,fname,options_);
         
+        if options_.nodisplay
+            close(hmap);
+        end
     end
 else
     %   gsa_ = gsa_sdp_dyn(y0, x0, 0, [],[],[],0,fname, pnames);
-    gsa_ = gsa_sdp(y0, x0, 0, [],[],[],0,fname, pnames);
+%     gsa_ = gsa_sdp(y0, x0, 0, [],[],[],0,fname, pnames);
+    load([fname,'_map.mat'],'gsa_')
     if ~options_.nograph,
         yf = ss_anova_fcast(x0, gsa_);
-        hfig=dyn_figure(options_,['Reduced Form Mapping: ' namy,'_vs_', namx,'_pred']);
+        hfig=dyn_figure(options_,'name',options_map.title);
         plot(y0,[yf y0],'.'),
-        title([namy,' vs. ', namx,' pred'],'interpreter','none')
-        dyn_saveas(hfig,[xdir,filesep, namy,'_vs_', namx,'_pred'],options_);
+        title([namy,' vs ', namx,' pred'],'interpreter','none')
+        dyn_saveas(hfig,[fname '_pred'],options_);
     end
 end
 % si = gsa_.multivariate.si;
 si = gsa_.si;
 
+return
+
+function gsa2 = log2level_map(gsa1, isig, lam)
+
+nest=length(gsa1.y);
+np = size(gsa1.x0,2);
+gsa2=gsa1;
+gsa2.y = log_trans_(gsa1.y,'',isig,lam);
+gsa2.fit = (exp(gsa1.fit)-lam)*isig;
+gsa2.f0 = mean(gsa2.fit);
+gsa2.out.SSE = sum((gsa2.fit-gsa2.y).^2);
+gsa2.out.bic = gsa2.out.bic-nest*log(gsa1.out.SSE)+nest*log(gsa2.out.SSE);
+gsa2.r2 = 1-cov(gsa2.fit-gsa2.y)/cov(gsa2.y);
+for j=1:np,
+    gsa2.fs(:,j) = exp(gsa1.fs(:,j)).*mean(exp(gsa1.fit-gsa1.f(:,j)))*isig-lam*isig-gsa2.f0;
+    gsa2.fses(:,j) = exp(gsa1.fs(:,j)+gsa1.fses(:,j)).*mean(exp(gsa1.fit-gsa1.f(:,j)))*isig-lam*isig-gsa2.f0-gsa2.fs(:,j);
+    gsa2.f(:,j) = exp(gsa1.f(:,j)).*mean(exp(gsa1.fit-gsa1.f(:,j)))*isig-lam*isig-gsa2.f0;
+    gsa2.si(j) = var(gsa2.f(:,j))/var(gsa2.y);
+end
+
+return
+
+
+function [gsa22, gsa1, gsax] = ss_anova_log(y,x,isig,lam,gsa0,nvrs)
+
+[nest, np]=size(x);
+
+if nargin==6,
+    gsa1 = ss_anova(y, x, 1, 0, 2, nvrs(:,1));
+else
+    gsa1 = ss_anova(y, x, 1);
+end
+gsa2 = log2level_map(gsa1, isig, lam);
+if nargin >=5 && ~isempty(gsa0),
+    for j=1:np,
+        nvr2(j) = var(diff(gsa2.fs(:,j),2));
+        nvr0(j) = var(diff(gsa0.fs(:,j),2));
+    end
+    inda = find((gsa0.stat<2)&(gsa1.stat>2));
+    inda = inda(log10(nvr0(inda)./nvr2(inda))/2<0);
+    gsa1.nvr(inda)=gsa1.nvr(inda).*10.^(log10(nvr0(inda)./nvr2(inda)));
+    gsa1 = ss_anova(y, x, 1, 0, 2, gsa1.nvr);
+    gsa2 = log2level_map(gsa1, isig, lam);
+end
+if nargin==6,
+    gsax = ss_anova(gsa2.y-gsa2.fit, x, 1, 0, 2, nvrs(:,2));
+else
+    gsax = ss_anova(gsa2.y-gsa2.fit, x, 1);
+end
+gsa22=gsa2;
+gsa22.fit = gsa2.fit+gsax.fit;
+gsa22.f0 = mean(gsa22.fit);
+gsa22.out.SSE = sum((gsa22.fit-gsa22.y).^2);
+gsa22.out.bic = nest*log(gsa22.out.SSE/nest) + (gsax.out.df+gsa2.out.df-1)*log(nest);
+gsa22.r2 = 1-sum((gsa22.fit-gsa22.y).^2)/sum((gsa22.y-mean(gsa22.y)).^2);
+for j=1:np,
+    gsa22.fs(:,j) = gsa2.fs(:,j)+gsax.fs(:,j);
+    gsa22.fses(:,j) = gsax.fses(:,j);
+    gsa22.f(:,j) = gsa2.f(:,j)+gsax.f(:,j);
+    gsa22.si(j) = var(gsa22.f(:,j))/var(gsa22.y);
+end
+
+return
+
+function indmcf = redform_mcf(y0, x0, options_mcf, options_)
+
+hfig=dyn_figure(options_,'name',options_mcf.amcf_title);
+
+[post_mean, post_median, post_var, hpd_interval, post_deciles, ...
+    density] = posterior_moments(y0,1,0.9);
+post_deciles = [-inf; post_deciles; inf];
+
+for jt=1:10,
+    indy{jt}=find( (y0>post_deciles(jt)) & (y0<=post_deciles(jt+1)));
+    leg{jt}=[int2str(jt) '-dec'];
+end
+[proba, dproba] = stab_map_1(x0, indy{1}, indy{end}, [],0);
+indmcf=find(proba<options_mcf.pvalue_ks);
+[tmp,jtmp] = sort(proba(indmcf),2,'ascend');
+indmcf = indmcf(jtmp);
+nbr_par = length(indmcf);
+nrow=ceil(sqrt(nbr_par+1));
+ncol=nrow;
+if nrow*(nrow-1)>nbr_par,
+    ncol=nrow-1;
+end
+
+cmap = colormap(jet(10));
+for jx=1:nbr_par,
+    subplot(nrow,ncol,jx)
+    hold off
+    for jt=1:10,
+        h=cumplot(x0(indy{jt},indmcf(jx)));
+        set(h,'color', cmap(jt,:), 'linewidth', 2)
+        hold all,
+    end
+    title(options_mcf.param_names(indmcf(jx),:),'interpreter','none')
+end
+hleg = legend(leg);
+aa=get(hleg,'Position');
+aa(1)=1-aa(3)-0.02;
+aa(2)=0.02;
+set(hleg,'Position',aa);
+if ~isoctave
+    annotation('textbox', [0.25,0.01,0.5,0.05], ...
+        'String', options_mcf.title, ...
+        'Color','black',...
+        'FontWeight','bold',...
+        'interpreter','none',...
+        'horizontalalignment','center');
+end
+
+dyn_saveas(hfig,[options_mcf.OutputDirectoryName filesep options_mcf.fname_,'_',options_mcf.amcf_name],options_);
+        
+return
diff --git a/matlab/gsa/scatter_mcf.m b/matlab/gsa/scatter_mcf.m
index 90d363cb3c7e4c11567026cdfa433988946f83d4..22654989057a9ad0aea5499ab3049a48d6d2b0ef 100644
--- a/matlab/gsa/scatter_mcf.m
+++ b/matlab/gsa/scatter_mcf.m
@@ -158,8 +158,8 @@ for i = 1:p
     end
 end
 if ~isoctave
-    annotation('textbox', [0.1,0,0.35,0.05],'String', beha_name,'Color','Blue','horizontalalignment','center');
-    annotation('textbox', [0.55,0,0.35,0.05],'String', non_beha_name,'Color','Red','horizontalalignment','center');
+    annotation('textbox', [0.1,0,0.35,0.05],'String', beha_name,'Color','Blue','horizontalalignment','center','interpreter','none');
+    annotation('textbox', [0.55,0,0.35,0.05],'String', non_beha_name,'Color','Red','horizontalalignment','center','interpreter','none');
 end
 
 if ~nograph,
diff --git a/matlab/gsa/stab_map_.m b/matlab/gsa/stab_map_.m
index f7db079df6f0fdf104f14ffb9667a5b368d9517d..876a75e8a1b3e11000b1284366177755975e37fe 100644
--- a/matlab/gsa/stab_map_.m
+++ b/matlab/gsa/stab_map_.m
@@ -267,7 +267,11 @@ if fload==0,
         M_ = set_all_parameters([lpmat0(j,:) lpmat(j,:)]',estim_params_,M_);
         %try stoch_simul([]);
         try
-            [Tt,Rr,SteadyState,info,M_,options_,oo_] = dynare_resolve(M_,options_,oo_,'restrict');
+            if ~ isempty(options_.endogenous_prior_restrictions.moment)
+                [Tt,Rr,SteadyState,info,M_,options_,oo_] = dynare_resolve(M_,options_,oo_);
+            else
+                [Tt,Rr,SteadyState,info,M_,options_,oo_] = dynare_resolve(M_,options_,oo_,'restrict');
+            end
             infox(j,1)=info(1);
             if infox(j,1)==0 && ~exist('T'),
                 dr_=oo_.dr;
@@ -557,7 +561,7 @@ if length(iunstable)>0 || length(iwrong)>0,
         options_mcf.beha_title = 'unique Stable Saddle-Path';
         options_mcf.nobeha_title = 'NO unique Stable Saddle-Path';
         options_mcf.title = 'unique solution';
-        mcf_analysis(lpmat, istable, itmp, options_mcf, options_)
+        mcf_analysis(lpmat, istable, itmp, options_mcf, options_);
 
         if ~isempty(iindeterm),
             itmp = itot(find(~ismember(itot,iindeterm)));
@@ -566,7 +570,7 @@ if length(iunstable)>0 || length(iwrong)>0,
             options_mcf.beha_title = 'NO indeterminacy';
             options_mcf.nobeha_title = 'indeterminacy';
             options_mcf.title = 'indeterminacy';
-            mcf_analysis(lpmat, itmp, iindeterm, options_mcf, options_)
+            mcf_analysis(lpmat, itmp, iindeterm, options_mcf, options_);
         end
         
         if ~isempty(ixun),
@@ -576,7 +580,7 @@ if length(iunstable)>0 || length(iwrong)>0,
             options_mcf.beha_title = 'NO explosive solution';
             options_mcf.nobeha_title = 'explosive solution';
             options_mcf.title = 'instability';
-            mcf_analysis(lpmat, itmp, ixun, options_mcf, options_)
+            mcf_analysis(lpmat, itmp, ixun, options_mcf, options_);
         end
         
         inorestriction = istable(find(~ismember(istable,irestriction))); % what went wrong beyong prior restrictions
@@ -588,7 +592,7 @@ if length(iunstable)>0 || length(iwrong)>0,
             options_mcf.beha_title = 'NO inability to find a solution';
             options_mcf.nobeha_title = 'inability to find a solution';
             options_mcf.title = 'inability to find a solution';
-            mcf_analysis(lpmat, itmp, iwrong, options_mcf, options_)
+            mcf_analysis(lpmat, itmp, iwrong, options_mcf, options_);
         end
         
         if ~isempty(irestriction),
@@ -598,7 +602,7 @@ if length(iunstable)>0 || length(iwrong)>0,
             options_mcf.beha_title = 'prior IRF/moment calibration';
             options_mcf.nobeha_title = 'NO prior IRF/moment calibration';
             options_mcf.title = 'prior restrictions';
-            mcf_analysis([lpmat0 lpmat], irestriction, inorestriction, options_mcf, options_)
+            mcf_analysis([lpmat0 lpmat], irestriction, inorestriction, options_mcf, options_);
             iok = irestriction(1);
             x0 = [lpmat0(iok,:)'; lpmat(iok,:)'];
         else
diff --git a/matlab/identification_analysis.m b/matlab/identification_analysis.m
index 0706988386f8529b991e4641904a4bfa3824d641..f14e74f71d33e53aef00b32f55d2bfde8a4d3a91 100644
--- a/matlab/identification_analysis.m
+++ b/matlab/identification_analysis.m
@@ -85,6 +85,9 @@ if info(1)==0,
     derivatives_info.DYss=dYss;
     if init,
         indJJ = (find(max(abs(JJ'),[],1)>1.e-8));
+        if isempty(indJJ) && any(any(isnan(JJ)))
+            error('There are NaN in the JJ matrix. Please check whether your model has units roots and you forgot to set lik_init~=1.' )
+        end
         while length(indJJ)<nparam && nlags<10,
             disp('The number of moments with non-zero derivative is smaller than the number of parameters')
             disp(['Try increasing ar = ', int2str(nlags+1)])           
diff --git a/matlab/initial_estimation_checks.m b/matlab/initial_estimation_checks.m
index 73637948c9ddb68e9e3019ccfce31317b2842cdf..ca9b3341afc055a63bd9c6316ea6fb8f275deae8 100644
--- a/matlab/initial_estimation_checks.m
+++ b/matlab/initial_estimation_checks.m
@@ -19,7 +19,7 @@ function DynareResults = initial_estimation_checks(objective_function,xparam1,Dy
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2003-2014 Dynare Team
+% Copyright (C) 2003-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -44,8 +44,38 @@ if DynareDataset.vobs>length(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)
-[DynareResults.steady_state] = evaluate_steady_state(DynareResults.steady_state,Model,DynareOptions,DynareResults,DynareOptions.diffuse_filter==0);
+if ~(strcmpi(DynareOptions.proposal_distribution, 'rand_multivariate_student') || ...
+     strcmpi(DynareOptions.proposal_distribution, 'rand_multivariate_normal'))
+    error(['initial_estimation_checks:: the proposal_distribution option to estimation takes either ' ...
+        'rand_multivariate_student or rand_multivariate_normal as options']);
+end
+
+if DynareOptions.student_degrees_of_freedom <= 0
+    error('initial_estimation_checks:: the student_degrees_of_freedom takes a positive integer argument');
+end
+
+old_steady_params=Model.params; %save initial parameters for check if steady state changes param values
+
+% % check if steady state solves static model (except if diffuse_filter == 1)
+[DynareResults.steady_state, new_steady_params] = evaluate_steady_state(DynareResults.steady_state,Model,DynareOptions,DynareResults,DynareOptions.diffuse_filter==0);
+
+if isfield(EstimatedParameters,'param_vals') && ~isempty(EstimatedParameters.param_vals)
+    %check whether steady state file changes estimated parameters
+    Model_par_varied=Model; %store Model structure
+    Model_par_varied.params(EstimatedParameters.param_vals(:,1))=Model_par_varied.params(EstimatedParameters.param_vals(:,1))*1.01; %vary parameters
+    [junk, new_steady_params_2] = evaluate_steady_state(DynareResults.steady_state,Model_par_varied,DynareOptions,DynareResults,DynareOptions.diffuse_filter==0);
+
+    changed_par_indices=find((old_steady_params(EstimatedParameters.param_vals(:,1))-new_steady_params(EstimatedParameters.param_vals(:,1))) ...
+            | (Model_par_varied.params(EstimatedParameters.param_vals(:,1))-new_steady_params_2(EstimatedParameters.param_vals(:,1))));
+
+    if ~isempty(changed_par_indices)
+        fprintf('\nThe steady state file internally changed the values of the following estimated parameters:\n')
+        disp(Model.param_names(changed_par_indices,:));
+        fprintf('This will override the parameter values drawn from the proposal density and may lead to wrong results.\n')
+        fprintf('Check whether this is really intended.\n')    
+        warning('The steady state file internally changes the values of the estimated parameters.')
+    end
+end
 
 if any(BayesInfo.pshape) % if Bayesian estimation
     nvx=EstimatedParameters.nvx;
@@ -69,8 +99,14 @@ if any(BayesInfo.pshape) % if Bayesian estimation
     end
 end
 
-%% display warning if some parameters are still NaN
+% display warning if some parameters are still NaN
 test_for_deep_parameters_calibration(Model);
+
+[lnprior, junk1,junk2,info]= priordens(xparam1,BayesInfo.pshape,BayesInfo.p6,BayesInfo.p7,BayesInfo.p3,BayesInfo.p4);
+if info
+    fprintf('The prior density evaluated at the initial values is Inf for the following parameters: %s\n',BayesInfo.name{info,1})
+    error('The initial value of the prior is -Inf')
+end
     
 % Evaluate the likelihood.
 ana_deriv = DynareOptions.analytic_derivation;
diff --git a/matlab/initvalf.m b/matlab/initvalf.m
index 13e1005d7ba6fcbe5198c17da956802a46b028ad..0493a2b48a8efdb378b478685083c6dacdbd02b8 100644
--- a/matlab/initvalf.m
+++ b/matlab/initvalf.m
@@ -64,6 +64,7 @@ switch (extension)
         load(basename);
     case { '.xls', '.xlsx' }
         [data_,names_v_]=xlsread(fullname); % Octave needs the extension explicitly
+        series_=0;
     otherwise
         error(['Unsupported extension for datafile: ' extension])
 end
@@ -75,27 +76,35 @@ oo_.exo_simul = [];
 for i_=1:size(M_.endo_names,1)
     if series_ == 1
         x_ = eval(M_.endo_names(i_,:));
-        oo_.endo_simul = [oo_.endo_simul; x_'];
+        if size(x_,2)>size(x_,1) %oo_.endo_simul must be collection of row vectors
+            oo_.endo_simul = [oo_.endo_simul; x_];
+        else %transpose if column vector
+            oo_.endo_simul = [oo_.endo_simul; x_'];            
+        end
     else
-        k_ = strmatch(upper(M_.endo_names(i_,:)),names_v_,'exact');
+        k_ = strmatch(deblank(M_.endo_names(i_,:)),names_v_,'exact');
         if isempty(k_)
-            error(['INITVAL_FILE: ' M_.endo_names(i_,:) ' not found'])
+            error(['INITVAL_FILE: ' deblank(M_.endo_names(i_,:)) ' not found'])
         end
         x_ = data_(:,k_);
-        oo_.endo_simul = [oo_.endo_simul; x_']; 
+        oo_.endo_simul = [oo_.endo_simul; x_'];            
     end
 end
 
 for i_=1:size(M_.exo_names,1)
     if series_ == 1
         x_ = eval(M_.exo_names(i_,:) );
-        oo_.exo_simul = [oo_.exo_simul x_];
+        if size(x_,2)>size(x_,1) %oo_.endo_simul must be collection of row vectors
+            oo_.exo_simul = [oo_.exo_simul x_'];
+        else %if column vector
+            oo_.exo_simul = [oo_.exo_simul x_];            
+        end
     else
-        k_ = strmatch(upper(M_.exo_names(i_,:)),names_v_,'exact');
+        k_ = strmatch(deblank(M_.exo_names(i_,:)),names_v_,'exact');
         if isempty(k_)
-            error(['INITVAL_FILE: ' M_.exo_names(i_,:) ' not found'])
+            error(['INITVAL_FILE: ' deblank(M_.exo_names(i_,:)) ' not found'])
         end
         x_ = data_(:,k_);
-        oo_.exo_simul = [oo_.exo_simul x_]; 
+        oo_.exo_simul = [oo_.exo_simul x_];            
     end
-end
+end
\ No newline at end of file
diff --git a/matlab/kalman/likelihood/kalman_filter_d.m b/matlab/kalman/likelihood/kalman_filter_d.m
index ced4d1305d8c02b9fb3b8db3107facfd61fe93e3..3b1161b7597cf30ae997391694f5020349995a47 100644
--- a/matlab/kalman/likelihood/kalman_filter_d.m
+++ b/matlab/kalman/likelihood/kalman_filter_d.m
@@ -1,4 +1,4 @@
-function [dLIK,dlik,a,Pstar] = kalman_filter_d(Y, start, last, a, Pinf, Pstar, kalman_tol, riccati_tol, presample, T, R, Q, H, Z, mm, pp, rr)
+function [dLIK,dlik,a,Pstar] = kalman_filter_d(Y, start, last, a, Pinf, Pstar, kalman_tol, diffuse_kalman_tol, riccati_tol, presample, T, R, Q, H, Z, mm, pp, rr)
 % Computes the diffuse likelihood of a state space model.
 %
 % INPUTS 
@@ -60,12 +60,12 @@ dLIK = Inf;                % Default value of the log likelihood.
 oldK = Inf;
 s    = 0;
 
-while rank(Pinf,kalman_tol) && (t<=last)
+while rank(Pinf,diffuse_kalman_tol) && (t<=last)
     s = t-start+1;
     v = Y(:,t)-Z*a;
     Finf  = Z*Pinf*Z';
-    if rcond(Finf) < kalman_tol
-        if ~all(abs(Finf(:)) < kalman_tol)
+    if rcond(Finf) < diffuse_kalman_tol
+        if ~all(abs(Finf(:)) < diffuse_kalman_tol)
             % The univariate diffuse kalman filter should be used instead.
             return
         else
diff --git a/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m b/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m
index 608a07b7dfe564729c856441f16e102df85c3519..008e1aa8960c6a33a771b2597761b766d3071ac5 100644
--- a/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m
+++ b/matlab/kalman/likelihood/missing_observations_kalman_filter_d.m
@@ -1,7 +1,7 @@
 function [dLIK,dlik,a,Pstar] = missing_observations_kalman_filter_d(data_index,number_of_observations,no_more_missing_observations, ...
                                                       Y, start, last, ...
                                                       a, Pinf, Pstar, ...
-                                                      kalman_tol, riccati_tol, presample, ...
+                                                      kalman_tol, diffuse_kalman_tol, riccati_tol, presample, ...
                                                       T, R, Q, H, Z, mm, pp, rr)
 % Computes the diffuse likelihood of a state space model when some observations are missing.
 %
@@ -72,7 +72,7 @@ if isequal(H,0)
 end
 s = 0;
 
-while rank(Pinf,kalman_tol) && (t<=last)
+while rank(Pinf,diffuse_kalman_tol) && (t<=last)
     s = t-start+1;
     d_index = data_index{t};
     if isempty(d_index)
@@ -83,8 +83,8 @@ while rank(Pinf,kalman_tol) && (t<=last)
         ZZ = Z(d_index,:);
         v  = Y(d_index,t)-ZZ*a;
         Finf  = ZZ*Pinf*ZZ';
-        if rcond(Finf) < kalman_tol
-            if ~all(abs(Finf(:)) < kalman_tol)
+        if rcond(Finf) < diffuse_kalman_tol
+            if ~all(abs(Finf(:)) < diffuse_kalman_tol)
                 % The univariate diffuse kalman filter should be used.
                 return
             else
diff --git a/matlab/kalman/likelihood/univariate_kalman_filter_d.m b/matlab/kalman/likelihood/univariate_kalman_filter_d.m
index ba047a2915a4baa0656178a6646853dc854d39dc..0782f95076b565a1573aacc855e99511f55719ac 100644
--- a/matlab/kalman/likelihood/univariate_kalman_filter_d.m
+++ b/matlab/kalman/likelihood/univariate_kalman_filter_d.m
@@ -1,4 +1,4 @@
-function [dLIK, dlikk, a, Pstar, llik] = univariate_kalman_filter_d(data_index, number_of_observations, no_more_missing_observations, Y, start, last, a, Pinf, Pstar, kalman_tol, riccati_tol, presample, T, R, Q, H, Z, mm, pp, rr)
+function [dLIK, dlikk, a, Pstar, llik] = univariate_kalman_filter_d(data_index, number_of_observations, no_more_missing_observations, Y, start, last, a, Pinf, Pstar, kalman_tol, diffuse_kalman_tol, riccati_tol, presample, T, R, Q, H, Z, mm, pp, rr)
 % Computes the likelihood of a state space model (initialization with diffuse steps, univariate approach).
 
 %@info:
@@ -110,7 +110,7 @@ dLIK = Inf;                % Default value of the log likelihood.
 oldK = Inf;
 llik = zeros(smpl,pp);
 
-newRank = rank(Pinf,kalman_tol);
+newRank = rank(Pinf,diffuse_kalman_tol);
 l2pi = log(2*pi);
 
 while newRank && (t<=last)
@@ -138,7 +138,7 @@ while newRank && (t<=last)
         end
     end
     if newRank
-        oldRank = rank(Pinf,kalman_tol);
+        oldRank = rank(Pinf,diffuse_kalman_tol);
     else
         oldRank = 0;
     end
@@ -146,7 +146,7 @@ while newRank && (t<=last)
     Pstar = T*Pstar*T'+QQ;
     Pinf  = T*Pinf*T';
     if newRank
-        newRank = rank(Pinf,kalman_tol);
+        newRank = rank(Pinf,diffuse_kalman_tol);
     end
     if oldRank ~= newRank
         disp('univariate_diffuse_kalman_filter:: T does influence the rank of Pinf!')
diff --git a/matlab/lmmcp/lmmcp.m b/matlab/lmmcp/lmmcp.m
index 2d6189fd0491554745cbd3db3ce280f964ed714e..aa170222c999699d70c5691d6bf08438cf1a0ea5 100644
--- a/matlab/lmmcp/lmmcp.m
+++ b/matlab/lmmcp/lmmcp.m
@@ -392,7 +392,7 @@ while (k < kmax) && (Psix > eps2)
   Fx        = Fxnew;
   Phix      = Phixnew;
   Psix      = Psixnew;
-  [~,DFx]   = feval(FUN,x,varargin{:});
+  [junk,DFx]   = feval(FUN,x,varargin{:});
   DPhix     = DPhi(x,Fx,DFx,lb,ub,lambda1,lambda2,n,Indexset);
   DPsix     = DPhix'*Phix;
   normDPsix = norm(DPsix);
diff --git a/matlab/lnsrch1_wrapper_two_boundaries.m b/matlab/lnsrch1_wrapper_two_boundaries.m
index 5f4fd356d46f37ea82b40dc9b868fa51b0a669b4..3b55ca70351a1f992f714936ca33078577fc6ee5 100644
--- a/matlab/lnsrch1_wrapper_two_boundaries.m
+++ b/matlab/lnsrch1_wrapper_two_boundaries.m
@@ -1,5 +1,5 @@
 function ra = lnsrch1_wrapper_two_boundaries(ya, fname, y, y_index, x, ...
-                                             params, steady_state, periods, y_kmin, y_size)
+                                             params, steady_state, periods, y_kmin, y_size,Periods)
 % wrapper for solve_one_boundary m-file when it is used with a dynamic
 % model
 %
@@ -26,7 +26,7 @@ function ra = lnsrch1_wrapper_two_boundaries(ya, fname, y, y_index, x, ...
 %   none.
 %  
 
-% Copyright (C) 2009-2011 Dynare Team
+% Copyright (C) 2009-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -45,5 +45,5 @@ function ra = lnsrch1_wrapper_two_boundaries(ya, fname, y, y_index, x, ...
 
 %reshape the input arguments of the dynamic function
 y(y_kmin+1:y_kmin+periods, y_index) = reshape(ya',length(y_index),periods)';
-[r, y, g1, g2, g3, b]=feval(fname, y, x, params, steady_state, periods, 0, y_kmin, y_size);
+[r, y, g1, g2, g3, b]=feval(fname, y, x, params, steady_state, periods, 0, y_kmin, y_size, Periods);
 ra = reshape(r(:, y_kmin+1:periods+y_kmin),periods*y_size, 1);
diff --git a/matlab/load_csv_file_data.m b/matlab/load_csv_file_data.m
deleted file mode 100644
index 639ed5b30a82115e72408089a4460d01f6b8d2f3..0000000000000000000000000000000000000000
--- a/matlab/load_csv_file_data.m
+++ /dev/null
@@ -1,83 +0,0 @@
-function [freq, init, data, varlist] = load_csv_file_data(file)
-
-% Loads data in a csv file.
-%
-% INPUTS 
-%  o file        string, name of the csv file (with path).
-%
-% OUTPUTS 
-%  o freq        integer scalar equal to 1, 4, 12 or 52 (for annual, quaterly, monthly or weekly frequencies).
-%  o init        dates object, initial date in the dataset.
-%  o data        matrix of doubles, the data.
-%  o varlist     cell of strings, names of the variables.
-%
-% REMARKS
-%  The varlist output will be set only if the first line contains variable
-%  names. Similarly, if the first column does not contain dates, then
-%  freq will be 1 and init will be year 1.
-
-% Copyright (C) 2012-2013 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/>.
-
-% Output initialization
-freq = 1;                  % Default frequency is annual.
-init = dates(1,1);         % Default initial date is year one.
-varlist = [];
-
-assert(exist(file, 'file') == 2, ['load_csv_file_data: I can''t find file ' file '!']);
-
-if isoctave
-    if ~user_has_octave_forge_package('io')
-        try
-            pkg load io
-        catch
-            error(['The io package is required to read CSV files from Octave. ' ...
-                'It can be installed by running the following from the Octave ' ...
-                ' command line: pkg install -forge io']);
-        end
-    end
-    A = csv2cell(file);
-    [data, T, L] = parsecell(A);
-    withvars = L.numlimits(2,1) > L.txtlimits(2,1);
-    withtime = L.numlimits(1,1) > L.txtlimits(1,1);
-else
-    A = importdata(file, ',');
-    if ~isstruct(A)
-        data = A;
-        T = {};
-        withvars = 0;
-        withtime = 0;
-    else
-        data = A.data;
-        T = A.textdata;
-        % importdata() allows text only at the top and the left, so the following
-        %  tests are sufficient.
-        withvars = size(T, 2) >= size(data, 2);
-        withtime = size(T, 1) >= size(data, 1);
-    end
-end
-
-if withvars
-    varlist = T(1, 2:end);
-    T = T(2:end, :);
-end
-if withtime
-    init = dates(T{1, 1});
-    freq = init.freq;
-end
-
-varlist = transpose(varlist);
diff --git a/matlab/load_m_file_data.m b/matlab/load_m_file_data.m
deleted file mode 100644
index 5c2e47881fd817154139fc5db5b85cb9dedc6b5f..0000000000000000000000000000000000000000
--- a/matlab/load_m_file_data.m
+++ /dev/null
@@ -1,158 +0,0 @@
-function [freq,init,data,varlist,tex] = load_m_file_data(file)
-
-% Loads data in a matlab/octave script.
-%
-% INPUTS 
-%  o file         string, name of the matlab/octave script (with path)
-%
-% OUTPUTS 
-%  o freq        integer scalar equal to 1, 4, 12 or 52 (for annual, quaterly, monthly or weekly frequencies).
-%  o init        dates object, initial date in the dataset.
-%  o data        matrix of doubles, the data.
-%  o varlist     cell of strings, names of the variables.
-%
-% REMARKS 
-% The frequency and initial date can be specified with variables FREQ__ and INIT__ in the matlab/octave script. FREQ__ must 
-% be a scalar integer and INIT__ a string like '1938M11', '1945Q3', '1973W3' or '2009A'. If these variables are not specified 
-% default values for freq and init are 1 and dates(1,1).
-
-% Copyright (C) 2012-2013 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 isoctave
-    run(file);
-else
-    basename = file(1:end-2);
-    run(basename);
-end
-
-if exist('INIT__','var')
-    if isdate(INIT__)
-        init = dates(INIT__);
-        clear('INIT__')
-    else
-        error('load_m_file_data: INIT__ cannot be interpreted as a date.')
-    end
-else
-    init = dates(1,1); % Default initial date is year one.
-end
-
-if exist('FREQ__','var')
-    freq = FREQ__;
-    clear('FREQ__');
-else
-    freq = init.freq;
-end
-
-if ~isequal(freq,init.freq)
-    error('load_m_file_data: INIT__ and FREQ__ are not consistent!')
-end
-
-if exist('NAMES__','var')
-    varlist0 = NAMES__;
-    clear('NAMES__');
-else
-    varlist0 = [];
-    list_of_variables = [];
-end
-
-if exist('TEX__','var')
-    tex = TEX__;
-    clear('TEX__');
-else
-    tex = [];
-end
-
-
-if isempty(varlist0)
-    list_of_variables = whos();
-end
-
-data = [];
-varlist = {};
-
-if isempty(varlist0)
-    for current_variable_index=1:length(list_of_variables)
-        if isequal(list_of_variables(current_variable_index).name,'freq') ...
-                || isequal(list_of_variables(current_variable_index).name,'time') ...
-                || isequal(list_of_variables(current_variable_index).name,'data') ...
-                || isequal(list_of_variables(current_variable_index).name,'varlist') ...
-                || isequal(list_of_variables(current_variable_index).name,'varlist0') ...
-                || isequal(list_of_variables(current_variable_index).name,'list_of_variables') ...
-                || isequal(list_of_variables(current_variable_index).name,'tex') ...
-            continue
-        end
-        if list_of_variables(current_variable_index).global || list_of_variables(current_variable_index).persistent
-            % A variable cannot be a global or persistent variable.
-            continue
-        end
-        if list_of_variables(current_variable_index).complex || ~strcmp(list_of_variables(current_variable_index).class,'double')
-            % A variable cannot be complex.
-            continue
-        end
-        if list_of_variables(current_variable_index).size(2)>1
-            % A variable must be passed as a column vector.
-            continue
-        end
-        try
-            eval(['data = [data, ' list_of_variables(current_variable_index).name '];'])
-            eval(['varlist = {varlist{:}, ''' list_of_variables(current_variable_index).name '''};'])
-        catch
-            error(['load_m_file:: All the vectors (variables) in ' inputname(1) ' must have the same number of rows (observations)!'])
-        end
-    end
-else
-    for current_variable_index=1:length(varlist0)
-       eval(['data = [data, ' varlist0{current_variable_index} '];'])
-    end
-    varlist = varlist0;
-end
-
-%@test:1
-%$ % Create a data m-file
-%$ fid = fopen('data_m_file.m','w');
-%$ fprintf(fid,'FREQ__ = 4;');
-%$ fprintf(fid,'INIT__ = ''1938Q4'';');
-%$ fprintf(fid,'NAMES__ = {''azert'';''yuiop''};');
-%$ fprintf(fid,'TEX__ = {''azert'';''yuiop''};');
-%$ fprintf(fid,'azert = [1; 2; 3; 4; 5];');
-%$ fprintf(fid,'yuiop = [2; 3; 4; 5; 6];');
-%$ fclose(fid);
-%$
-%$ % Try to read the data m-file
-%$ try
-%$     datafile = 'data_m_file';
-%$     [freq,init,data,varlist,tex] = load_m_file_data(datafile);
-%$     t(1) = 1;
-%$ catch exception
-%$     t(1) = 0;
-%$     T = all(t);
-%$     LOG = getReport(exception,'extended');
-%$     return
-%$ end
-%$
-%$ % Check the results.
-%$ t(2) = dassert(freq,4);
-%$ t(3) = dassert(isa(init,'dates'),1);
-%$ t(4) = dassert(init.freq,4);
-%$ t(5) = dassert(init.time,[1938 4]);
-%$ t(6) = dassert(varlist,{'azert';'yuiop'});
-%$ t(7) = dassert(tex,{'azert';'yuiop'});
-%$ t(8) = dassert(data(:,1),[1;2;3;4;5]);
-%$ t(9) = dassert(data(:,2),[2;3;4;5;6]);
-%$ T = all(t);
-%@eof:1
diff --git a/matlab/load_mat_file_data.m b/matlab/load_mat_file_data.m
deleted file mode 100644
index 98825a49a3113f4648a3aa619b27f067b7a0bd90..0000000000000000000000000000000000000000
--- a/matlab/load_mat_file_data.m
+++ /dev/null
@@ -1,154 +0,0 @@
-function [freq,init,data,varlist,tex] = load_mat_file_data(file)  % --*-- Unitary tests --*--
-
-% Loads data in a matlab/octave mat-file.
-%
-% INPUTS 
-%  o file         string, name of the matlab/octave mat file (with path)
-%
-% OUTPUTS 
-%  o freq        integer scalar equal to 1, 4, 12 or 52 (for annual, quaterly, monthly or weekly frequencies).
-%  o init        dates object, initial date in the dataset.
-%  o data        matrix of doubles, the data.
-%  o varlist     cell of strings, names of the variables.
-%
-% REMARKS 
-% The frequency and initial date can be specified with variables FREQ__ and INIT__ in the matlab/octave binary file. FREQ__ must 
-% be a scalar integer and INIT__ a string like '1938M11', '1945Q3', '1973W3' or '2009A'. If these variables are not specified 
-% default values for freq and init are 1 and dates(1,1).
-
-% Copyright (C) 2012-2014 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/>.
-
-datafile = load(file);
-
-if isfield(datafile,'INIT__')
-    if isdate(datafile.INIT__)
-        init = dates(datafile.INIT__);
-        datafile = rmfield(datafile, 'INIT__');
-    else
-        error('load_mat_file_data: INIT__ cannot be interpreted as a date.')
-    end
-else
-    init = dates(1,1);
-end
-
-if isfield(datafile,'FREQ__')
-    freq = datafile.FREQ__;
-    datafile = rmfield(datafile, 'FREQ__');
-else
-    freq = init.freq;
-end
-
-if ~isequal(freq,init.freq)
-    error('load_mat_file_data: INIT__ and FREQ__ are not consistent!')
-end
-
-if isfield(datafile,'NAMES__')
-    varlist = datafile.NAMES__;
-    datafile = rmfield(datafile, 'NAMES__');
-else
-    varlist = [];
-end
-
-if isfield(datafile,'TEX__')
-    tex = datafile.TEX__;
-    datafile = rmfield(datafile, 'TEX__');
-else
-    tex = [];
-end
-
-data = [];
-if isempty(varlist)
-    varlist = fieldnames(datafile);
-end
-
-for i=1:length(varlist)
-    try
-        tmp = getfield(datafile,varlist{i});
-        data = [data,  tmp(:)];
-    catch
-        error(['load_mat_file:: All the vectors (variables) in ' inputname(1) ' must have the same number of rows (observations)!'])
-    end
-end
-
-%@test:1
-%$ % Create a data mat-file
-%$ FREQ__ = 12;
-%$ INIT__ = '1938M11';
-%$ NAMES__ = {'hagop'; 'bedros'};
-%$ TEX__ = NAMES__;
-%$ hagop  = [1; 2; 3; 4; 5];
-%$ bedros = [2; 3; 4; 5; 6];
-%$ save('datafile_for_test');
-%$
-%$ % Try to read the data mat-file
-%$ t = zeros(8,1);
-%$ try
-%$     [freq,init,data,varlist,tex] = load_mat_file_data('datafile_for_test');
-%$     t(1) = 1;
-%$ catch exception
-%$     t = t(1);
-%$     T = all(t);
-%$     LOG = getReport(exception,'extended');
-%$     return
-%$ end
-%$
-%$ % Check the results.
-%$ t(2) = dassert(freq,12);
-%$ t(3) = dassert(isa(init,'dates'),true);
-%$ t(4) = dassert(init.freq,12);
-%$ t(5) = dassert(init.time,[1938 11]);
-%$ t(6) = dassert(varlist,{'hagop';'bedros'});
-%$ t(7) = dassert(varlist,{'hagop';'bedros'});
-%$ t(8) = dassert(data(:,1),[1;2;3;4;5]);
-%$ t(9) = dassert(data(:,2),[2;3;4;5;6]);
-%$ T = all(t);
-%@eof:1
-
-%@test:2
-%$ % Create a data mat-file
-%$ FREQ__ = 12;
-%$ INIT__ = '1938M11';
-%$ NAMES__ = {'hagop'; 'bedros'};
-%$ TEX__ = NAMES__;
-%$ hagop  = [1, 2, 3, 4, 5];
-%$ bedros = [2, 3, 4, 5, 6];
-%$ save('datafile_for_test');
-%$
-%$ % Try to read the data mat-file
-%$ t = zeros(8,1);
-%$ try
-%$     [freq,init,data,varlist,tex] = load_mat_file_data('datafile_for_test');
-%$     t(1) = 1;
-%$ catch exception
-%$     t = t(1);
-%$     T = all(t);
-%$     LOG = getReport(exception,'extended');
-%$     return
-%$ end
-%$
-%$ % Check the results.
-%$ t(2) = dassert(freq,12);
-%$ t(3) = dassert(isa(init,'dates'),true);
-%$ t(4) = dassert(init.freq,12);
-%$ t(5) = dassert(init.time,[1938 11]);
-%$ t(6) = dassert(varlist,{'hagop';'bedros'});
-%$ t(7) = dassert(varlist,{'hagop';'bedros'});
-%$ t(8) = dassert(data(:,1),[1;2;3;4;5]);
-%$ t(9) = dassert(data(:,2),[2;3;4;5;6]);
-%$ T = all(t);
-%@eof:2
diff --git a/matlab/load_xls_file_data.m b/matlab/load_xls_file_data.m
deleted file mode 100644
index 58bfb5fac508dea161a4f94e737d1995ed332352..0000000000000000000000000000000000000000
--- a/matlab/load_xls_file_data.m
+++ /dev/null
@@ -1,138 +0,0 @@
-function [freq, init, data, varlist] = load_xls_file_data(file, sheet, range)
-
-% Loads data in a xls file.
-%
-% INPUTS 
-%  o file       string, name of the file (with extension).
-%  o sheet      string, name of the sheet to be read.
-%  o range      string of the form 'B2:D6'
-%
-% OUTPUTS 
-%  o freq       integer scalar (1, 4, 12 or 52), code for frequency.
-%  o init       dates object, initial date of the sample.
-%  o data       matrix of doubles, the raw data.
-%  o varlist    cell of strings (column), names of the variables in the database.
-%
-% REMARKS 
-%  The range argument is only available on windows platform (with Excel installed).
-
-% Copyright (C) 2013 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/>.
-
-% Set defaults.
-if nargin<3 || isempty(range)
-    range = '';
-    if nargin<2 || isempty(sheet)
-        sheet = 1;
-        if nargin<1 || isempty(file)
-            error('load_xls_file_data:: I need at least one input (name of the xls or xlsx file)!')
-        end
-    end
-end
-
-% Check file extension.
-if ~(check_file_extension(file,'xls') || check_file_extension(file,'xlsx'))
-    ext = get_file_extension(file);
-    if isempty(ext)
-        if exist([file '.xls'],'file')
-            file = [file '.xls'];
-        elseif exist([file '.xlsx'],'file')
-            file = [file '.xlsx'];
-        else
-            error(['load_xls_file_data:: Unable to find the data file ' file ' with an xls or xlsx extension!'])
-        end
-    else
-        error(['load_xls_file_data:: The data file ' file ' has wrong extension (must be either xls or xlsx)!'])
-    end
-end
-
-% load excel file.
-if isoctave && ~user_has_octave_forge_package('io')
-    error('The io package is required to read XLS/XLSX files from Octave')
-end
-[num,txt,raw] = xlsread(file, sheet, range);
-
-% Get dimensions of num, txt and raw
-[n1, n2] = size(num);
-[t1, t2] = size(txt);
-[r1, r2] = size(raw);
-
-% Check the content of the file.
-if isequal(t1,0) && isequal(t2,0)
-    % The file contains no informations about the variables and dates.
-    notime = 1;
-    noname = 1;
-elseif isequal(t2,1) && t1>=t2 && n2~=t2  %only one column present, but no var name in header text
-    % The file contains no informations about the dates.
-    notime = 0;
-    noname = 1;
-elseif isequal(t2,1) && t1>=t2 && n2==t2 %only one column present with var name in header text
-    % The file contains no informations about the variables.
-    notime = 1;
-    noname = 0;
-elseif isequal(t1,1) && t2>=t1
-    % The file contains no informations about the dates.
-    notime = 1;
-    noname = 0;
-else 
-    % The file contains informations about the variables and dates.
-    notime = 0;
-    noname = 0;
-end
-
-% Output initialization.
-freq = 1;
-init = dates(1,1);
-varlist = [];
-data = num;
-
-% Update freq.
-if ~notime
-    if isempty(txt{1,1})
-        first_date = txt{2,1};
-    else
-        first_date = txt{1,1};
-    end
-    if isnumeric(first_date) && isint(first_date)
-        first_date = [num2str(first_date) 'Y'];
-    end
-    if isdate(first_date)
-        init = dates(first_date);
-        freq = init.freq;
-    else
-        error('load_xls_file_data: I am not able to read the dates!')
-    end
-end
-
-% Update varlist.
-if ~noname
-    if notime
-        varlist = transpose(txt);
-    else
-        varlist = transpose(txt(1,2:end));
-    end
-    % Remove leading and trailing white spaces 
-    for i=1:length(varlist)
-        varlist(i) = {strtrim(varlist{i})};
-    end
-else
-    % set default names
-    varlist = cell(n2,1);
-    for i=1:n2
-        varlist(i) = {['Variable_' int2str(i)]};
-    end
-end
\ No newline at end of file
diff --git a/matlab/maximize_prior_density.m b/matlab/maximize_prior_density.m
index 01e9ffc8db93af8c55f38de47f04e9a4a2bdd105..72df861a4768cd76436c740acd00241224392716 100644
--- a/matlab/maximize_prior_density.m
+++ b/matlab/maximize_prior_density.m
@@ -1,5 +1,5 @@
-function [xparams,lpd,hessian] = ...
-    maximize_prior_density(iparams, prior_shape, prior_hyperparameter_1, prior_hyperparameter_2, prior_inf_bound, prior_sup_bound,DynareOptions,DynareModel,EstimatedParams,DynareResults)
+function [xparams,lpd,hessian_mat] = ...
+    maximize_prior_density(iparams, prior_shape, prior_hyperparameter_1, prior_hyperparameter_2, prior_inf_bound, prior_sup_bound,DynareOptions,DynareModel,BayesInfo,EstimatedParams,DynareResults)
 % Maximizes the logged prior density using Chris Sims' optimization routine.
 % 
 % INPUTS 
@@ -13,9 +13,9 @@ function [xparams,lpd,hessian] = ...
 % OUTPUTS 
 %   xparams       [double]  vector, prior mode.
 %   lpd           [double]  scalar, value of the logged prior density at the mode.
-%   hessian       [double]  matrix, Hessian matrix at the prior mode.
+%   hessian_mat   [double]  matrix, Hessian matrix at the prior mode.
 
-% Copyright (C) 2009-2012 Dynare Team
+% Copyright (C) 2009-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -32,15 +32,10 @@ function [xparams,lpd,hessian] = ...
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-number_of_estimated_parameters = length(iparams);
-H0 = 1e-4*eye(number_of_estimated_parameters);
-crit = 1e-7;
-nit = 1000;
-gradient_method = 2;
-gradient_epsilon = 1e-6;
-
-[lpd,xparams,grad,hessian,itct,fcount,retcodehat] = ...
-    csminwel1('minus_logged_prior_density',iparams,H0,[],crit,nit,gradient_method, gradient_epsilon, ...
-              prior_shape, prior_hyperparameter_1, prior_hyperparameter_2, prior_inf_bound, prior_sup_bound,DynareOptions,DynareModel,EstimatedParams,DynareResults);
+[xparams, lpd, exitflag, hessian_mat]=dynare_minimize_objective('minus_logged_prior_density', ...
+                                                  iparams, DynareOptions.mode_compute, DynareOptions, [prior_inf_bound, prior_sup_bound], ...
+                                                  BayesInfo.name, BayesInfo, [], ...
+                                                  prior_shape, prior_hyperparameter_1, prior_hyperparameter_2, prior_inf_bound, prior_sup_bound, ...
+                                                  DynareOptions,DynareModel,EstimatedParams,DynareResults);
 
 lpd = -lpd;
diff --git a/matlab/metropolis_hastings_initialization.m b/matlab/metropolis_hastings_initialization.m
index e8f4d0ef156fd80d62af87b542539d077bd07f62..4650830e5bdec1b363933e110dbcc61449f6915c 100644
--- a/matlab/metropolis_hastings_initialization.m
+++ b/matlab/metropolis_hastings_initialization.m
@@ -1,7 +1,7 @@
 function [ ix2, ilogpo2, ModelName, MetropolisFolder, fblck, fline, npar, nblck, nruns, NewFile, MAX_nruns, d ] = ...
     metropolis_hastings_initialization(TargetFun, xparam1, vv, mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_)
-%function [ ix2, ilogpo2, ModelName, MhDirectoryName, fblck, fline, npar, nblck, nruns, NewFile, MAX_nruns, d ] = 
-%    metropolis_hastings_initialization(TargetFun, xparam1, vv, mh_bounds, dataset_,dataset_info,,options_,M_,estim_params_,bayestopt_,oo_)
+%function [ ix2, ilogpo2, ModelName, MetropolisFolder, fblck, fline, npar, nblck, nruns, NewFile, MAX_nruns, d ] = ...
+%     metropolis_hastings_initialization(TargetFun, xparam1, vv, mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_)
 % Metropolis-Hastings initialization.
 % 
 % INPUTS 
@@ -11,6 +11,7 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, fblck, fline, npar, nblck,
 %   o vv         [double]   (p*p) matrix, posterior covariance matrix (at the mode).
 %   o mh_bounds  [double]   (p*2) matrix defining lower and upper bounds for the parameters. 
 %   o dataset_              data structure
+%   o dataset_info          dataset info structure
 %   o options_              options structure
 %   o M_                    model structure
 %   o estim_params_         estimated parameters structure
@@ -18,12 +19,25 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, fblck, fline, npar, nblck,
 %   o oo_                   outputs structure
 %  
 % OUTPUTS 
-%   None  
+%   o ix2                   [double]   (nblck*npar) vector of starting points for different chains
+%   o ilogpo2               [double]   (nblck*1) vector of initial posterior values for different chains
+%   o ModelName             [string]    name of the mod-file
+%   o MetropolisFolder      [string]    path to the Metropolis subfolder
+%   o fblck                 [scalar]    number of the first MH chain to be run (not equal to 1 in case of recovery)   
+%   o fline                 [double]   (nblck*1) vector of first draw in each chain (not equal to 1 in case of recovery)   
+%   o npar                  [scalar]    number of parameters estimated
+%   o nblck                 [scalar]    Number of MCM chains requested   
+%   o nruns                 [double]   (nblck*1) number of draws in each chain 
+%   o NewFile               [scalar]    (nblck*1) vector storing the number
+%                                       of the first MH-file to created for each chain when saving additional
+%                                       draws
+%   o MAX_nruns             [scalar]    maximum number of draws in each MH-file on the harddisk
+%   o d                     [double]   (p*p) matrix, Cholesky decomposition of the posterior covariance matrix (at the mode).
 %
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2006-2013 Dynare Team
+% Copyright (C) 2006-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -40,6 +54,7 @@ function [ ix2, ilogpo2, ModelName, MetropolisFolder, fblck, fline, npar, nblck,
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
+%Initialize outputs
 ix2 = [];
 ilogpo2 = [];
 ModelName = []; 
@@ -68,7 +83,7 @@ MAX_nruns = ceil(options_.MaxNumberOfBytes/(npar+2)/8);
 d = chol(vv);
 
 if ~options_.load_mh_file && ~options_.mh_recover
-    % Here we start a new metropolis-hastings, previous draws are discarded.
+    % Here we start a new Metropolis-Hastings, previous draws are discarded.
     if nblck > 1
         disp('Estimation::mcmc: Multiple chains mode.')
     else
@@ -80,7 +95,7 @@ if ~options_.load_mh_file && ~options_.mh_recover
         delete([BaseName '_mh*_blck*.mat']);
         disp('Estimation::mcmc: Old mh-files successfully erased!')
     end
-    % Delete old metropolis log file.
+    % Delete old Metropolis log file.
     file = dir([ MetropolisFolder '/metropolis.log']);
     if length(file)
         delete([ MetropolisFolder '/metropolis.log']);
@@ -128,11 +143,11 @@ if ~options_.load_mh_file && ~options_.mh_recover
                 if init_iter > 100 && validate == 0
                     disp(['Estimation::mcmc: I couldn''t get a valid initial value in 100 trials.'])
                     if options_.nointeractive
-                        disp(['Estimation::mcmc: I reduce mh_init_scale by ten percent:'])
+                        disp(['Estimation::mcmc: I reduce mh_init_scale by 10 percent:'])
                         options_.mh_init_scale = .9*options_.mh_init_scale;
                         disp(sprintf('Estimation::mcmc: Parameter mh_init_scale is now equal to %f.',options_.mh_init_scale))
                     else
-                        disp(['Estimation::mcmc: You should Reduce mh_init_scale...'])
+                        disp(['Estimation::mcmc: You should reduce mh_init_scale...'])
                         disp(sprintf('Estimation::mcmc: Parameter mh_init_scale is equal to %f.',options_.mh_init_scale))
                         options_.mh_init_scale = input('Estimation::mcmc: Enter a new value...  ');
                     end
@@ -217,7 +232,7 @@ if ~options_.load_mh_file && ~options_.mh_recover
     fclose(fidlog);
 elseif options_.load_mh_file && ~options_.mh_recover
     % Here we consider previous mh files (previous mh did not crash).
-    disp('Estimation::mcmc: I am loading past metropolis-hastings simulations...')
+    disp('Estimation::mcmc: I am loading past Metropolis-Hastings simulations...')
     load_last_mh_history_file(MetropolisFolder, ModelName);
     mh_files = dir([ MetropolisFolder filesep ModelName '_mh*.mat']);
     if ~length(mh_files)
@@ -238,7 +253,7 @@ elseif options_.load_mh_file && ~options_.mh_recover
         nblck = past_number_of_blocks;
         options_.mh_nblck = nblck;
     end
-    % I read the last line of the last mh-file for initialization of the new metropolis-hastings simulations:
+    % I read the last line of the last mh-file for initialization of the new Metropolis-Hastings simulations:
     LastFileNumber = record.LastFileNumber;
     LastLineNumber = record.LastLineNumber;
     if LastLineNumber < MAX_nruns
@@ -252,7 +267,7 @@ elseif options_.load_mh_file && ~options_.mh_recover
     ix2 = record.LastParameters;
     fblck = 1;
     NumberOfPreviousSimulations = sum(record.MhDraws(:,1),1);
-    fprintf('Estimation::mcmc: I am writting a new mh-history file... ');
+    fprintf('Estimation::mcmc: I am writing a new mh-history file... ');
     record.MhDraws = [record.MhDraws;zeros(1,3)];
     NumberOfDrawsWrittenInThePastLastFile = MAX_nruns - LastLineNumber;
     NumberOfDrawsToBeSaved = nruns(1) - NumberOfDrawsWrittenInThePastLastFile;
@@ -318,7 +333,7 @@ elseif options_.mh_recover
         disp('Estimation::mcmc: It appears that you don''t need to use the mh_recover option!')
         disp('                  You have to edit the mod file and remove the mh_recover option') 
         disp('                  in the estimation command')
-        error()
+        error('Estimation::mcmc: mh_recover option not required!')
     end
     % I count the number of saved mh files per block.
     NumberOfMhFilesPerBlock = zeros(nblck,1);
@@ -339,7 +354,7 @@ elseif options_.mh_recover
     end
     % How many mh-files are saved in this block?
     NumberOfSavedMhFilesInTheCrashedBlck = NumberOfMhFilesPerBlock(fblck);
-    % Correct the number of saved mh files if the crashed metropolis was not the first session (so
+    % Correct the number of saved mh files if the crashed Metropolis was not the first session (so
     % that NumberOfSavedMhFilesInTheCrashedBlck is the number of saved mh files in the crashed chain 
     % of the current session).  
     if OldMh
diff --git a/matlab/missing_DiffuseKalmanSmootherH1_Z.m b/matlab/missing_DiffuseKalmanSmootherH1_Z.m
index 4b501477129347051923fd752f35d45eecc9b75a..9fc09eb306b355481e2db48b86de297cc4603f40 100644
--- a/matlab/missing_DiffuseKalmanSmootherH1_Z.m
+++ b/matlab/missing_DiffuseKalmanSmootherH1_Z.m
@@ -1,6 +1,6 @@
-function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,decomp] = missing_DiffuseKalmanSmootherH1_Z(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl,data_index,nk,kalman_tol,decomp_flag)
+function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,decomp] = missing_DiffuseKalmanSmootherH1_Z(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl,data_index,nk,kalman_tol,diffuse_kalman_tol,decomp_flag)
 
-% function [alphahat,epsilonhat,etahat,a,aK,PK,decomp] = DiffuseKalmanSmoother1(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl,data_index,nk,kalman_tol,decomp_flag)
+% function [alphahat,epsilonhat,etahat,a,aK,PK,decomp] = DiffuseKalmanSmoother1(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl,data_index,nk,kalman_tol,diffuse_kalman_tol,decomp_flag)
 % Computes the diffuse kalman smoother without measurement error, in the case of a non-singular var-cov matrix 
 %
 % INPUTS
@@ -18,6 +18,7 @@ function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,decomp] = missing_DiffuseKal
 %    data_index                   [cell]      1*smpl cell of column vectors of indices.
 %    nk        number of forecasting periods
 %    kalman_tol   tolerance for reciprocal condition number
+%    diffuse_kalman_tol   tolerance for reciprocal condition number (for Finf) and the rank of Pinf
 %    decomp_flag  if true, compute filter decomposition
 %             
 % OUTPUTS
@@ -38,7 +39,7 @@ function [alphahat,epsilonhat,etahat,atilde,P,aK,PK,decomp] = missing_DiffuseKal
 %   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-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -80,7 +81,6 @@ Kstar           = zeros(mm,pp,smpl);
 P               = zeros(mm,mm,smpl+1);
 Pstar           = zeros(spstar(1),spstar(2),smpl+1); Pstar(:,:,1) = Pstar1;
 Pinf            = zeros(spinf(1),spinf(2),smpl+1); Pinf(:,:,1) = Pinf1;
-crit1       = 1.e-8;
 steady          = smpl;
 rr              = size(Q,1);
 QQ              = R*Q*transpose(R);
@@ -91,7 +91,7 @@ epsilonhat          = zeros(rr,smpl);
 r               = zeros(mm,smpl+1);
 
 t = 0;
-while rank(Pinf(:,:,t+1),crit1) && t<smpl
+while rank(Pinf(:,:,t+1),diffuse_kalman_tol) && t<smpl
     t = t+1;
     di = data_index{t};
     if isempty(di)
@@ -103,8 +103,8 @@ while rank(Pinf(:,:,t+1),crit1) && t<smpl
         ZZ = Z(di,:);
         v(di,t)= Y(di,t) - ZZ*a(:,t);
         Finf = ZZ*Pinf(:,:,t)*ZZ';
-        if rcond(Finf) < kalman_tol
-            if ~all(abs(Finf(:)) < kalman_tol)
+        if rcond(Finf) < diffuse_kalman_tol
+            if ~all(abs(Finf(:)) < diffuse_kalman_tol)
                 % The univariate diffuse kalman filter should be used.
                 alphahat = Inf;
                 return
@@ -170,7 +170,7 @@ while notsteady && t<smpl
         F = ZZ*P(:,:,t)*ZZ' + H(di,di);
         if rcond(F) < kalman_tol
             alphahat = Inf;
-            return              
+            return
         end    
         iF(di,di,t)   = inv(F);
         PZI         = P(:,:,t)*ZZ'*iF(di,di,t);
diff --git a/matlab/missing_DiffuseKalmanSmootherH3_Z.m b/matlab/missing_DiffuseKalmanSmootherH3_Z.m
index f9241c5ef8c3ebb5eaed8cbaa3d8101cfb2365fe..ddd6159b718860896bf699516bfc5556d296f686 100644
--- a/matlab/missing_DiffuseKalmanSmootherH3_Z.m
+++ b/matlab/missing_DiffuseKalmanSmootherH3_Z.m
@@ -1,4 +1,4 @@
-function [alphahat,epsilonhat,etahat,a,P,aK,PK,decomp] = missing_DiffuseKalmanSmootherH3_Z(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl,data_index,nk,kalman_tol,decomp_flag)
+function [alphahat,epsilonhat,etahat,a,P,aK,PK,decomp] = missing_DiffuseKalmanSmootherH3_Z(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl,data_index,nk,kalman_tol,diffuse_kalman_tol,decomp_flag)
 % function [alphahat,epsilonhat,etahat,a1,P,aK,PK,d,decomp] = missing_DiffuseKalmanSmootherH3_Z(T,Z,R,Q,H,Pinf1,Pstar1,Y,pp,mm,smpl,data_index,nk,kalman_tol,decomp_flag)
 % Computes the diffuse kalman smoother without measurement error, in the case of a singular var-cov matrix.
 % Univariate treatment of multivariate time series.
@@ -17,7 +17,8 @@ function [alphahat,epsilonhat,etahat,a,P,aK,PK,decomp] = missing_DiffuseKalmanSm
 %    smpl:     sample size
 %    data_index                   [cell]      1*smpl cell of column vectors of indices.
 %    nk        number of forecasting periods
-%    kalman_tol   tolerance for zero divider 
+%    kalman_tol   tolerance for zero divider
+%    diffuse_kalman_tol   tolerance for zero divider
 %    decomp_flag  if true, compute filter decomposition
 %
 % OUTPUTS
@@ -38,7 +39,7 @@ function [alphahat,epsilonhat,etahat,a,P,aK,PK,decomp] = missing_DiffuseKalmanSm
 %   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-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -80,7 +81,6 @@ Pstar           = zeros(spstar(1),spstar(2),smpl); Pstar(:,:,1) = Pstar1;
 Pinf            = zeros(spinf(1),spinf(2),smpl); Pinf(:,:,1) = Pinf1;
 Pstar1          = Pstar;
 Pinf1           = Pinf;
-crit1       = 1.e-6;
 steady          = smpl;
 rr              = size(Q,1); % number of structural shocks
 QQ              = R*Q*transpose(R);
@@ -92,7 +92,7 @@ r               = zeros(mm,smpl);
 
 t = 0;
 icc=0;
-newRank   = rank(Pinf(:,:,1),crit1);
+newRank = rank(Pinf(:,:,1),diffuse_kalman_tol);
 while newRank && t < smpl
     t = t+1;
     a(:,t) = a1(:,t);
@@ -121,7 +121,7 @@ while newRank && t < smpl
         end
     end
     if newRank
-        oldRank = rank(Pinf(:,:,t),crit1);
+        oldRank = rank(Pinf(:,:,t),diffuse_kalman_tol);
     else
         oldRank = 0;
     end
@@ -134,7 +134,7 @@ while newRank && t < smpl
     Pinf(:,:,t+1) = T*Pinf(:,:,t)*T';
     P0=Pinf(:,:,t+1);
     if newRank,
-        newRank       = rank(Pinf(:,:,t+1),crit1);
+        newRank       = rank(Pinf(:,:,t+1),diffuse_kalman_tol);
     end
     if oldRank ~= newRank
         disp('univariate_diffuse_kalman_filter:: T does influence the rank of Pinf!')   
diff --git a/matlab/mode_check.m b/matlab/mode_check.m
index fd80782d7a123fd95d5102f50a535bac03466aed..39b40c4dac583af9c3392b9a679e02c0e90b611b 100644
--- a/matlab/mode_check.m
+++ b/matlab/mode_check.m
@@ -1,8 +1,8 @@
-function mode_check(fun,x,hessian,DynareDataset,DatasetInfo,DynareOptions,Model,EstimatedParameters,BayesInfo,BoundsInfo,DynareResults)
+function mode_check(fun,x,hessian_mat,DynareDataset,DatasetInfo,DynareOptions,Model,EstimatedParameters,BayesInfo,BoundsInfo,DynareResults)
 % Checks the estimated ML mode or Posterior mode.
 
 %@info:
-%! @deftypefn {Function File} mode_check (@var{fun}, @var{x}, @var{hessian}, @var{DynareDataset}, @var{DynareOptions}, @var{Model}, @var{EstimatedParameters}, @var{BayesInfo}, @var{DynareResults})
+%! @deftypefn {Function File} mode_check (@var{fun}, @var{x}, @var{hessian_mat}, @var{DynareDataset}, @var{DynareOptions}, @var{Model}, @var{EstimatedParameters}, @var{BayesInfo}, @var{DynareResults})
 %! @anchor{mode_check}
 %! @sp 1
 %! Checks the estimated ML mode or Posterior mode by plotting sections of the likelihood/posterior kernel.
@@ -58,17 +58,17 @@ function mode_check(fun,x,hessian,DynareDataset,DatasetInfo,DynareOptions,Model,
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 TeX = DynareOptions.TeX;
-if ~isempty(hessian);
-    [ s_min, k ] = min(diag(hessian));
+if ~isempty(hessian_mat);
+    [ s_min, k ] = min(diag(hessian_mat));
 end
 
 fval = feval(fun,x,DynareDataset,DatasetInfo,DynareOptions,Model,EstimatedParameters,BayesInfo,BoundsInfo,DynareResults);
 
-if ~isempty(hessian);
+if ~isempty(hessian_mat);
     skipline()
     disp('MODE CHECK')
     skipline()
-    disp(sprintf('Fval obtained by the minimization routine: %f', fval))
+    fprintf('Fval obtained by the minimization routine (minus the posterior/likelihood)): %f', fval);
     skipline()
     if s_min<eps
         disp(sprintf('Most negative variance %f for parameter %d (%s = %f)', s_min, k , BayesInfo.name{k}, x(k)))
@@ -149,7 +149,7 @@ for plt = 1:nbplt,
                 y(i,2)  = (y(i,1)+lnprior-dy);
             end
         end
-        plot(z,-y);
+        fighandle=plot(z,-y);
         hold on
         yl=get(gca,'ylim');
         plot( [x(kk) x(kk)], yl, 'c', 'LineWidth', 1)
@@ -173,8 +173,9 @@ for plt = 1:nbplt,
         else
             axes('position',[0.3 0.01 0.42 0.05],'box','on'),
         end
-        plot([0.48 0.68],[0.5 0.5],'color',[0 0.5 0])
-        hold on, plot([0.04 0.24],[0.5 0.5],'b')
+        line_color=get(fighandle,'color');
+        plot([0.48 0.68],[0.5 0.5],'color',line_color{2})
+        hold on, plot([0.04 0.24],[0.5 0.5],'color',line_color{1})
         set(gca,'xlim',[0 1],'ylim',[0 1],'xtick',[],'ytick',[])
         text(0.25,0.5,'log-post')
         text(0.69,0.5,'log-lik kernel')
diff --git a/matlab/model_diagnostics.m b/matlab/model_diagnostics.m
index 62ec92054e666ab69cd9b41ce1837de78e408647..21b7d7d7198e59919b1bd209cce3028388402de8 100644
--- a/matlab/model_diagnostics.m
+++ b/matlab/model_diagnostics.m
@@ -173,7 +173,7 @@ if singularity_problem
         options_check=options;
         options_check.noprint=1;
         [eigenvalues_] = check(M, options_check, oo);
-        if any((abs(eigenvalues_)-1)<1e-6)
+        if any(abs(abs(eigenvalues_)-1)<1e-6)
             fprintf('MODEL_DIAGNOSTICS:  The singularity seems to be (partly) caused by the presence of a unit root\n')
             fprintf('MODEL_DIAGNOSTICS:  as the absolute value of one eigenvalue is in the range of +-1e-6 to 1.\n')
             fprintf('MODEL_DIAGNOSTICS:  If the model is actually supposed to feature unit root behavior, such a warning is expected,\n')
diff --git a/matlab/modules/dates b/matlab/modules/dates
index 79e67d31857ee344b5d4c3906fe66dbce4fded6b..0ab546e6fa6f6d712cb7e8a0b536eb9e86581f67 160000
--- a/matlab/modules/dates
+++ b/matlab/modules/dates
@@ -1 +1 @@
-Subproject commit 79e67d31857ee344b5d4c3906fe66dbce4fded6b
+Subproject commit 0ab546e6fa6f6d712cb7e8a0b536eb9e86581f67
diff --git a/matlab/modules/dseries b/matlab/modules/dseries
index 5d76092a0ebca10c4c458b1d5fd5448ab2c9cff3..55686d7f06673bde2ab52e75833a1bbdba16b2a1 160000
--- a/matlab/modules/dseries
+++ b/matlab/modules/dseries
@@ -1 +1 @@
-Subproject commit 5d76092a0ebca10c4c458b1d5fd5448ab2c9cff3
+Subproject commit 55686d7f06673bde2ab52e75833a1bbdba16b2a1
diff --git a/matlab/modules/reporting b/matlab/modules/reporting
new file mode 160000
index 0000000000000000000000000000000000000000..b7d5391051635207f088a493c92d7357f3bdd4e9
--- /dev/null
+++ b/matlab/modules/reporting
@@ -0,0 +1 @@
+Subproject commit b7d5391051635207f088a493c92d7357f3bdd4e9
diff --git a/matlab/ms-sbvar/identification/exclusions.m b/matlab/ms-sbvar/identification/exclusions.m
index 9632356fe2e3f8ce02060999b8a7d6d628facf93..a2447b1ba157060e599b33eb58130441288014a5 100644
--- a/matlab/ms-sbvar/identification/exclusions.m
+++ b/matlab/ms-sbvar/identification/exclusions.m
@@ -1,4 +1,4 @@
-function [Ui,Vi,n0,np,ixmC0Pres] = exclusions(nvar,nexo,options_ms)
+function [Ui,Vi,n0,np,ixmC0Pres,Qi] = exclusions(nvar,nexo,options_ms)
 % function [Ui,Vi,n0,np,ixmC0Pres] = exclusions(nvar,nexo,options_ms)
 %
 % INPUTS
diff --git a/matlab/ms-sbvar/sbvar_global_identification_check.m b/matlab/ms-sbvar/sbvar_global_identification_check.m
new file mode 100644
index 0000000000000000000000000000000000000000..642220f54fb4f9e90436eba9bbfd9bc8dddcdd88
--- /dev/null
+++ b/matlab/ms-sbvar/sbvar_global_identification_check.m
@@ -0,0 +1,77 @@
+function indent = sbvar_global_identification_check(options_)
+% function sbvar_global_identification_check(options_.ms)
+%
+% INPUTS
+%    options_ms:    (struct)    options
+%
+% OUTPUTS
+%    ident:          (boolean) false = not identified; true = identified
+%
+% SPECIAL REQUIREMENTS
+%    none
+
+% Copyright (C) 2015 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+ident = false;
+
+if isequal(options_.ms.restriction_fname, 'upper_cholesky') || ...
+        isequal(options_.ms.restriction_fname, 'lower_cholesky')
+    ident = true;
+    if ~options_.noprint
+        disp(' ')
+        disp('SBVAR: Cholesky identification is always identified')
+        disp(' ')
+    end
+    return
+end
+nvar = length(options_.varobs);   % number of endogenous variables
+nexo = 1;
+   
+[Uiconst,Viconst,n0,np,ixmC0Pres,Qi] = exclusions(nvar,nexo,options_.ms );
+
+% order column constraints by rank
+Qranks = zeros(nvar,2);
+for j=1:nvar
+    Qranks(j,:) = [j,rank(Qi{j})];
+end
+Qranks = sortrows(Qranks,-2);
+
+ident = true;
+
+for j=1:nvar
+    i = Qranks(j,1);
+    for k=1:1
+        M = [Qi{i}*rand(size(Qi{i},1),nvar);[eye(j) zeros(j,nvar- ...
+                                                          j)]];
+        disp([j,k,rank(M)])
+        if rank(M) < nvar
+            ident = false
+            break
+        end
+    end
+end
+
+if ~options_.noprint
+    disp(' ')
+    if ident
+        disp('The sufficient condition for SBVAR identification is met')
+    else
+        disp('WARNGING: The sufficient condition for SBVAR identification is not met')
+    end
+    disp(' ')
+end
\ No newline at end of file
diff --git a/matlab/non_linear_dsge_likelihood.m b/matlab/non_linear_dsge_likelihood.m
index 99c77292950605b0c3f93e6efe7a98b1d72db2e2..a9348034a3e821c55d372a24eb23af47f4092acd 100644
--- a/matlab/non_linear_dsge_likelihood.m
+++ b/matlab/non_linear_dsge_likelihood.m
@@ -298,9 +298,11 @@ DynareOptions.warning_for_steadystate = 0;
 LIK = feval(DynareOptions.particle.algorithm,ReducedForm,Y,start,DynareOptions.particle,DynareOptions.threads);
 set_dynare_random_generator_state(s1,s2);
 if imag(LIK)
+    info = 46;
     likelihood = objective_function_penalty_base;
     exit_flag  = 0;
 elseif isnan(LIK)
+    info = 45;
     likelihood = objective_function_penalty_base;
     exit_flag  = 0;
 else
@@ -311,4 +313,18 @@ DynareOptions.warning_for_steadystate = 1;
 % Adds prior if necessary
 % ------------------------------------------------------------------------------
 lnprior = priordens(xparam1(:),BayesInfo.pshape,BayesInfo.p6,BayesInfo.p7,BayesInfo.p3,BayesInfo.p4);
-fval    = (likelihood-lnprior);
\ No newline at end of file
+fval    = (likelihood-lnprior);
+
+if isnan(fval)
+    info = 47;
+    fval = objective_function_penalty_base + 100;
+    exit_flag = 0;
+    return
+end
+
+if imag(fval)~=0
+    info = 48;
+    fval = objective_function_penalty_base + 100;
+    exit_flag = 0;
+    return
+end
diff --git a/matlab/optimization/apprgrdn.m b/matlab/optimization/apprgrdn.m
new file mode 100644
index 0000000000000000000000000000000000000000..9f16e44667b2c415968c541884bc1031642a04ff
--- /dev/null
+++ b/matlab/optimization/apprgrdn.m
@@ -0,0 +1,73 @@
+function g = apprgrdn(x,f,fun,deltax,obj,varargin)
+% g = apprgrdn(x,f,fun,deltax,obj,varargin)
+% Performs the finite difference approximation of the gradient <g> at a
+% point <x> used in solveopt
+% 
+% Inputs:
+% x:        point at which to evaluate gradient
+% f:        calculated function value at a point x;
+% fun:      Name of the Matlab function calculating the function values
+% deltax:   vector of the relative stepsizes,
+% obj       flag indicating whether the gradient of the objective
+%           function (1) or the constraint function (0) is to be calculated.
+%
+% Modified by Giovanni Lombardo and Johannes Pfeifer to accomodate Dynare
+% structure
+%
+% 
+% Copyright (C) 1997-2008, Alexei Kuntsevich and Franz Kappel 
+% Copyright (C) 2008-2015 Giovanni Lombardo
+% Copyright (C) 2015 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+n=max(size(x)); ee=ones(size(x));
+di=abs(x); idx=find(di<5e-15); di(idx)=5e-15*ee(idx);
+di=deltax.*di;
+if obj
+    idx=find(abs(di)<2e-10); 
+    di(idx)=2e-10*sign(di(idx));
+else
+    idx=find(abs(di)<5e-15); 
+    di(idx)=5e-15*sign(di(idx));
+end
+y=x;
+
+g=NaN(n,1);
+for i=1:n
+    y(i)=x(i)+di(i);
+    fi=feval(fun,y,varargin{:});
+    if obj
+        if fi==f,
+            for j=1:3
+                di(i)=di(i)*10;  y(i)=x(i)+di(i);
+                fi=feval(fun,y,varargin{:});
+                if fi~=f
+                    break
+                end
+            end
+        end
+    end
+    g(i)=(fi-f)/di(i);
+    if obj
+        if ~isempty(idx) && any(idx==i)
+            y(i)=x(i)-di(i);
+            fi=feval(fun,y,varargin{:});
+            g(i)=.5*(g(i)+(f-fi)/di(i));
+        end
+    end
+    y(i)=x(i);
+end
diff --git a/matlab/cmaes.m b/matlab/optimization/cmaes.m
similarity index 100%
rename from matlab/cmaes.m
rename to matlab/optimization/cmaes.m
diff --git a/matlab/csminit1.m b/matlab/optimization/csminit1.m
similarity index 85%
rename from matlab/csminit1.m
rename to matlab/optimization/csminit1.m
index b6eb95da04aaf22c4c7752076be034ee6a5d0479..b6574b005ad8653d03cf5379ed709e1d58e11a02 100644
--- a/matlab/csminit1.m
+++ b/matlab/optimization/csminit1.m
@@ -1,10 +1,24 @@
 function [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,f0,g0,badg,H0,varargin)
-% [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,f0,g0,badg,H0,...
-%                                       P1,P2,P3,P4,P5,P6,P7,P8)
-% retcodes: 0, normal step.  5, largest step still improves too fast.
-% 4,2 back and forth adjustment of stepsize didn't finish.  3, smallest
-% stepsize still improves too slow.  6, no improvement found.  1, zero
-% gradient.
+% [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,f0,g0,badg,H0,varargin)
+% 
+% Inputs: 
+%   fcn:    [string]        string naming the objective function to be minimized
+%   x0:     [npar by 1]     initial value of the parameter vector
+%   g0:     [npar by 1]     initial value of the gradient vector
+%   H0:     [npar by npar]  initial value for the inverse Hessian.  Must be positive definite.
+%   varargin:               Optional additional inputs that get handed off to fcn each
+%                           time it is called.
+
+% Outputs:
+%   fhat:   [scalar]        function value at minimum
+%   xhat:   [npar by 1]     parameter vector at minimum
+%   fcount  [scalar]        function iteration count upon termination
+%   retcode    [scalar]    0: normal step
+%                           1: zero gradient.
+%                           5: largest step still improves too fast.
+%                           2,4: back and forth adjustment of stepsize didn't finish.  
+%                           3: smallest stepsize still improves too slow
+%                           6: no improvement found
 %---------------------
 % Modified 7/22/96 to omit variable-length P list, for efficiency and compilation.
 % Places where the number of P's need to be altered or the code could be returned to
@@ -15,12 +29,12 @@ function [fhat,xhat,fcount,retcode] = csminit1(fcn,x0,f0,g0,badg,H0,varargin)
 %
 % Fixed 7/19/93 to flip eigenvalues of H to get better performance when
 % it's not psd.
-
+% 
 % Original file downloaded from:
 % http://sims.princeton.edu/yftp/optimize/mfiles/csminit.m
-
+% 
 % Copyright (C) 1993-2007 Christopher Sims
-% Copyright (C) 2008-2011 Dynare Team
+% Copyright (C) 2008-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/csminwel1.m b/matlab/optimization/csminwel1.m
similarity index 53%
rename from matlab/csminwel1.m
rename to matlab/optimization/csminwel1.m
index b6e38fedc0f6f0b9d61474e6a0a18b25cfd108d6..dcc579f50d4076b3a563217c56483b65ab90b552 100644
--- a/matlab/csminwel1.m
+++ b/matlab/optimization/csminwel1.m
@@ -1,29 +1,48 @@
 function [fh,xh,gh,H,itct,fcount,retcodeh] = csminwel1(fcn,x0,H0,grad,crit,nit,method,epsilon,varargin)
-%[fhat,xhat,ghat,Hhat,itct,fcount,retcodehat] = csminwel1(fcn,x0,H0,grad,crit,nit,method,epsilon,varargin)
-% fcn:   string naming the objective function to be minimized
-% x0:    initial value of the parameter vector
-% H0:    initial value for the inverse Hessian.  Must be positive definite.
-% grad:  Either a string naming a function that calculates the gradient, or the null matrix.
-%        If it's null, the program calculates a numerical gradient.  In this case fcn must
-%        be written so that it can take a matrix argument and produce a row vector of values.
-% crit:  Convergence criterion.  Iteration will cease when it proves impossible to improve the
-%        function value by more than crit.
-% nit:   Maximum number of iterations.
-% method: integer scalar, 2, 3 or 5 points formula.
-% epsilon: scalar double, numerical differentiation increment
-% varargin: A list of optional length of additional parameters that get handed off to fcn each
-%        time it is called.
+%[fhat,xhat,ghat,Hhat,itct,fcount,retcodeh] = csminwel1(fcn,x0,H0,grad,crit,nit,method,epsilon,varargin)
+% Inputs:
+%   fcn:    [string]        string naming the objective function to be minimized
+%   x0:     [npar by 1]     initial value of the parameter vector
+%   H0:     [npar by npar]  initial value for the inverse Hessian.  Must be positive definite.
+%   grad:   [string or empty matrix] Either a string naming a function that calculates the gradient, or the null matrix.
+%                           If it's null, the program calculates a numerical gradient.  In this case fcn must
+%                           be written so that it can take a matrix argument and produce a row vector of values.
+%   crit:   [scalar]        Convergence criterion.  Iteration will cease when it proves impossible to improve the
+%                           function value by more than crit.
+%   nit:    [scalar]        Maximum number of iterations.
+%   method: [scalar]        integer scalar for selecting gradient method: 2, 3 or 5 points formula.
+%   epsilon: [scalar]       scalar double, numerical differentiation increment
+%   varargin:               Optional additional inputs that get handed off to fcn each
+%                           time it is called.
+% 
 %        Note that if the program ends abnormally, it is possible to retrieve the current x,
 %        f, and H from the files g1.mat and H.mat that are written at each iteration and at each
 %        hessian update, respectively.  (When the routine hits certain kinds of difficulty, it
-%        write g2.mat and g3.mat as well.  If all were written at about the same time, any of them
-%        may be a decent starting point.  One can also start from the one with best function value.)
-
+%        writes g2.mat and g3.mat as well. If all were written at about the same time, any of them
+%        may be a decent starting point. One can also start from the one with best function value.)
+% 
+% Outputs:
+%   fh:     [scalar]        function value at minimum
+%   xh:     [npar by 1]     parameter vector at minimum
+%   gh      [npar by 1]     gradient vector
+%   H       [npar by npar]  inverse of the Hessian matrix
+%   itct    [scalar]        iteration count upon termination
+%   fcount  [scalar]        function iteration count upon termination
+%   retcodeh [scalar]       return code:
+%                               0: normal step
+%                               1: zero gradient 
+%                               2: back and forth on step length never finished
+%                               3: smallest step still improving too slow
+%                               4: back and forth on step length never finished
+%                               5: largest step still improving too fast
+%                               6: smallest step still improving too slow, reversed gradient
+%                               7: warning: possible inaccuracy in H matrix
+% 
 % Original file downloaded from:
 % http://sims.princeton.edu/yftp/optimize/mfiles/csminwel.m
-
+% 
 % Copyright (C) 1993-2007 Christopher Sims
-% Copyright (C) 2006-2012 Dynare Team
+% Copyright (C) 2006-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -51,7 +70,6 @@ NumGrad= isempty(grad);
 done=0;
 itct=0;
 fcount=0;
-snit=100;
 gh = [];
 H = [];
 retcodeh = [];
@@ -74,20 +92,7 @@ if ~cost_flag
 end
 
 if NumGrad
-    switch method
-      case 2
-        [g,badg] = numgrad2(fcn, f0, x0, epsilon, varargin{:});
-      case 3
-        [g,badg] = numgrad3(fcn, f0, x0, epsilon, varargin{:});
-      case 5
-        [g,badg] = numgrad5(fcn, f0, x0, epsilon, varargin{:});
-      case 13
-        [g,badg] = numgrad3_(fcn, f0, x0, epsilon, varargin{:});
-      case 15
-        [g,badg] = numgrad5_(fcn, f0, x0, epsilon, varargin{:});
-      otherwise
-        error('csminwel1: Unknown method for gradient evaluation!')
-    end
+    [g, badg]=get_num_grad(method,fcn,f0,x0,epsilon,varargin{:});
 elseif ischar(grad)
     [g,badg] = feval(grad,x0,varargin{:});
 else
@@ -105,19 +110,15 @@ while ~done
 
     g1=[]; g2=[]; g3=[];
     %addition fj. 7/6/94 for control
-    disp('-----------------')
-    disp('-----------------')
-    %disp('f and x at the beginning of new iteration')
-    disp(sprintf('f at the beginning of new iteration, %20.10f',f))
+    if Verbose
+        disp('-----------------')
+        disp(sprintf('f at the beginning of new iteration, %20.10f',f))
+    end
     %-----------Comment out this line if the x vector is long----------------
     %   disp([sprintf('x = ') sprintf('%15.8g %15.8g %15.8g %15.8g\n',x)]);
     %-------------------------
     itct=itct+1;
-    [f1 x1 fc retcode1] = csminit1(fcn,x,f,g,badg,H,varargin{:});
-    %ARGLIST
-    %[f1 x1 fc retcode1] = csminit(fcn,x,f,g,badg,H,P1,P2,P3,P4,P5,P6,P7,...
-    %           P8,P9,P10,P11,P12,P13);
-    % itct=itct+1;
+    [f1, x1, fc, retcode1] = csminit1(fcn,x,f,g,badg,H,varargin{:});
     fcount = fcount+fc;
     % erased on 8/4/94
     % if (retcode == 1) || (abs(f1-f) < crit)
@@ -132,22 +133,9 @@ while ~done
             wall1=1; badg1=1;
         else
             if NumGrad
-                switch method
-                  case 2
-                    [g1 badg1] = numgrad2(fcn, f1, x1, epsilon, varargin{:});
-                  case 3
-                    [g1 badg1] = numgrad3(fcn, f1, x1, epsilon, varargin{:});
-                  case 5
-                    [g1,badg1] = numgrad5(fcn, f1, x1, epsilon, varargin{:});
-                  case 13
-                    [g1,badg1] = numgrad3_(fcn, f1, x1, epsilon, varargin{:});
-                  case 15
-                    [g1,badg1] = numgrad5_(fcn, f1, x1, epsilon, varargin{:});
-                  otherwise
-                    error('csminwel1: Unknown method for gradient evaluation!')
-                end
+                [g1, badg1]=get_num_grad(method,fcn,f1,x1,epsilon,varargin{:});
             elseif ischar(grad),
-                [g1 badg1] = feval(grad,x1,varargin{:});
+                [g1, badg1] = feval(grad,x1,varargin{:});
             else
                 [junk1,g1,junk2, cost_flag] = feval(fcn,x1,varargin{:});
                 badg1 = ~cost_flag;
@@ -155,8 +143,6 @@ while ~done
             wall1=badg1;
             % g1
             save g1.mat g1 x1 f1 varargin;
-            %ARGLIST
-            %save g1 g1 x1 f1 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13;
         end
         if wall1 % && (~done) by Jinill
                  % Bad gradient or back and forth on step length.  Possibly at
@@ -164,33 +150,19 @@ while ~done
                  %
                  %fcliff=fh;xcliff=xh;
             Hcliff=H+diag(diag(H).*rand(nx,1));
-            disp('Cliff.  Perturbing search direction.')
-            [f2 x2 fc retcode2] = csminit1(fcn,x,f,g,badg,Hcliff,varargin{:});
-            %ARGLIST
-            %[f2 x2 fc retcode2] = csminit(fcn,x,f,g,badg,Hcliff,P1,P2,P3,P4,...
-            %     P5,P6,P7,P8,P9,P10,P11,P12,P13);
+            if Verbose
+                disp('Cliff.  Perturbing search direction.')
+            end
+            [f2, x2, fc, retcode2] = csminit1(fcn,x,f,g,badg,Hcliff,varargin{:});
             fcount = fcount+fc; % put by Jinill
             if  f2 < f
                 if retcode2==2 || retcode2==4
                     wall2=1; badg2=1;
                 else
                     if NumGrad
-                        switch method
-                          case 2
-                            [g2 badg2] = numgrad2(fcn, f2, x2, epsilon, varargin{:});
-                          case 3
-                            [g2 badg2] = numgrad3(fcn, f2, x2, epsilon, varargin{:});
-                          case 5
-                            [g2,badg2] = numgrad5(fcn, f2, x2, epsilon, varargin{:});
-                          case 13
-                            [g2,badg2] = numgrad3_(fcn, f2, x2, epsilon, varargin{:});
-                          case 15
-                            [g2,badg2] = numgrad5_(fcn, f2, x2, epsilon, varargin{:});
-                          otherwise
-                            error('csminwel1: Unknown method for gradient evaluation!')
-                        end
+                        [g2, badg2]=get_num_grad(method,fcn,f2,x2,epsilon,varargin{:});
                     elseif ischar(grad),
-                        [g2 badg2] = feval(grad,x2,varargin{:});
+                        [g2, badg2] = feval(grad,x2,varargin{:});
                     else
                         [junk1,g2,junk2, cost_flag] = feval(fcn,x1,varargin{:});
                         badg2 = ~cost_flag;
@@ -199,8 +171,6 @@ while ~done
                     % g2
                     badg2
                     save g2.mat g2 x2 f2 varargin
-                    %ARGLIST
-                    %save g2 g2 x2 f2 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13;
                 end
                 if wall2
                     disp('Cliff again.  Try traversing')
@@ -208,33 +178,19 @@ while ~done
                         f3=f; x3=x; badg3=1;retcode3=101;
                     else
                         gcliff=((f2-f1)/((norm(x2-x1))^2))*(x2-x1);
-                        if(size(x0,2)>1), gcliff=gcliff', end
-                        [f3 x3 fc retcode3] = csminit1(fcn,x,f,gcliff,0,eye(nx),varargin{:});
-                        %ARGLIST
-                        %[f3 x3 fc retcode3] = csminit(fcn,x,f,gcliff,0,eye(nx),P1,P2,P3,...
-                        %         P4,P5,P6,P7,P8,...
-                        %      P9,P10,P11,P12,P13);
+                        if(size(x0,2)>1)
+                            gcliff=gcliff';
+                        end
+                        [f3, x3, fc, retcode3] = csminit1(fcn,x,f,gcliff,0,eye(nx),varargin{:});
                         fcount = fcount+fc; % put by Jinill
                         if retcode3==2 || retcode3==4
-                            wall3=1; badg3=1;
+                            wall3=1; 
+                            badg3=1;
                         else
                             if NumGrad
-                                switch method
-                                  case 2
-                                    [g3 badg3] = numgrad2(fcn, f3, x3, epsilon, varargin{:});
-                                  case 3
-                                    [g3 badg3] = numgrad3(fcn, f3, x3, epsilon, varargin{:});
-                                  case 5
-                                    [g3,badg3] = numgrad5(fcn, f3, x3, epsilon, varargin{:});
-                                  case 13
-                                    [g3,badg3] = numgrad3_(fcn, f3, x3, epsilon, varargin{:});
-                                  case 15
-                                    [g3,badg3] = numgrad5_(fcn, f3, x3, epsilon, varargin{:});
-                                  otherwise
-                                    error('csminwel1: Unknown method for gradient evaluation!')
-                                end
+                                [g3, badg3]=get_num_grad(method,fcn,f3,x3,epsilon,varargin{:});
                             elseif ischar(grad),
-                                [g3 badg3] = feval(grad,x3,varargin{:});
+                                [g3, badg3] = feval(grad,x3,varargin{:});
                             else
                                 [junk1,g3,junk2, cost_flag] = feval(fcn,x1,varargin{:});
                                 badg3 = ~cost_flag;
@@ -242,8 +198,6 @@ while ~done
                             wall3=badg3;
                             % g3
                             save g3.mat g3 x3 f3 varargin;
-                            %ARGLIST
-                            %save g3 g3 x3 f3 P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13;
                         end
                     end
                 else
@@ -292,22 +246,9 @@ while ~done
         end
         if nogh
             if NumGrad
-                switch method
-                  case 2
-                    [gh,badgh] = numgrad2(fcn, fh, xh, epsilon, varargin{:});
-                  case 3
-                    [gh,badgh] = numgrad3(fcn, fh, xh, epsilon, varargin{:});
-                  case 5
-                    [gh,badgh] = numgrad5(fcn, fh, xh, epsilon, varargin{:});
-                  case 13
-                    [gh,badgh] = numgrad3_(fcn, fh, xh, epsilon, varargin{:});
-                  case 15
-                    [gh,badgh] = numgrad5_(fcn, fh, xh, epsilon, varargin{:});
-                  otherwise
-                    error('csminwel1: Unknown method for gradient evaluation!')
-                end
+                [gh, badgh]=get_num_grad(method,fcn,fh,xh,epsilon,varargin{:});
             elseif ischar(grad),
-                [gh badgh] = feval(grad, xh,varargin{:});
+                [gh, badgh] = feval(grad, xh,varargin{:});
             else
                 [junk1,gh,junk2, cost_flag] = feval(fcn,x1,varargin{:});
                 badgh = ~cost_flag;
@@ -316,11 +257,6 @@ while ~done
         badgh=1;
     end
     %end of picking
-    %ih
-    %fh
-    %xh
-    %gh
-    %badgh
     stuck = (abs(fh-f) < crit);
     if (~badg) && (~badgh) && (~stuck)
         H = bfgsi1(H,gh-g,xh-x);
@@ -338,24 +274,47 @@ while ~done
         done = 1;
     end
     rc=retcodeh;
-    if rc == 1
-        disp('zero gradient')
-    elseif rc == 6
-        disp('smallest step still improving too slow, reversed gradient')
-    elseif rc == 5
-        disp('largest step still improving too fast')
-    elseif (rc == 4) || (rc==2)
-        disp('back and forth on step length never finished')
-    elseif rc == 3
-        disp('smallest step still improving too slow')
-    elseif rc == 7
-        disp('warning: possible inaccuracy in H matrix')
+    if Verbose || done
+        if rc ==0
+            %do nothing, just a normal step
+        elseif rc == 1
+            disp('zero gradient')
+        elseif rc == 6
+            disp('smallest step still improving too slow, reversed gradient')
+        elseif rc == 5
+            disp('largest step still improving too fast')
+        elseif (rc == 4) || (rc==2)
+            disp('back and forth on step length never finished')
+        elseif rc == 3
+            disp('smallest step still improving too slow')
+        elseif rc == 7
+            disp('warning: possible inaccuracy in H matrix')
+        else
+            error('Unaccounted Case, please contact the developers')
+        end
     end
-    % end
+     
     f=fh;
     x=xh;
     g=gh;
     badg=badgh;
 end
-% what about making an m-file of 10 lines including numgrad.m
-% since it appears three times in csminwel.m
\ No newline at end of file
+
+end
+
+function [g, badg]=get_num_grad(method,fcn,f0,x0,epsilon,varargin)
+    switch method
+      case 2
+        [g,badg] = numgrad2(fcn, f0, x0, epsilon, varargin{:});
+      case 3
+        [g,badg] = numgrad3(fcn, f0, x0, epsilon, varargin{:});
+      case 5
+        [g,badg] = numgrad5(fcn, f0, x0, epsilon, varargin{:});
+      case 13
+        [g,badg] = numgrad3_(fcn, f0, x0, epsilon, varargin{:});
+      case 15
+        [g,badg] = numgrad5_(fcn, f0, x0, epsilon, varargin{:});
+      otherwise
+        error('csminwel1: Unknown method for gradient evaluation!')
+    end
+end
\ No newline at end of file
diff --git a/matlab/optimization/dynare_minimize_objective.m b/matlab/optimization/dynare_minimize_objective.m
new file mode 100644
index 0000000000000000000000000000000000000000..fc04310399f9c2e85f7c77cef978f5c1ef9da689
--- /dev/null
+++ b/matlab/optimization/dynare_minimize_objective.m
@@ -0,0 +1,384 @@
+function [opt_par_values,fval,exitflag,hessian_mat,options_,Scale]=dynare_minimize_objective(objective_function,start_par_value,minimizer_algorithm,options_,bounds,parameter_names,prior_information,Initial_Hessian,varargin)
+
+% Calls a minimizer
+%
+% INPUTS
+%   objective_function  [function handle]                   handle to the objective function
+%   start_par_value     [n_params by 1] vector of doubles   starting values for the parameters
+%   minimizer_algorithm [scalar double]                     code of the optimizer algorithm
+%   options_            [matlab structure]                  Dynare options structure
+%   bounds              [n_params by 2] vector of doubles   2 row vectors containing lower and upper bound for parameters
+%   parameter_names     [n_params by 1] cell array          strings containing the parameters names   
+%   prior_information   [matlab structure]                  Dynare prior information structure (bayestopt_) provided for algorithm 6
+%   Initial_Hessian     [n_params by n_params] matrix       initial hessian matrix provided for algorithm 6
+%   varargin            [cell array]                        Input arguments for objective function
+%    
+% OUTPUTS
+%   opt_par_values      [n_params by 1] vector of doubles   optimal parameter values minimizing the objective
+%   fval                [scalar double]                     value of the objective function at the minimum
+%   exitflag            [scalar double]                     return code of the respective optimizer
+%   hessian_mat         [n_params by n_params] matrix       hessian matrix at the mode returned by optimizer
+%   options_            [matlab structure]                  Dynare options structure (to return options set by algorithms 5)
+%   Scale               [scalar double]                     scaling parameter returned by algorith 6
+%    
+% SPECIAL REQUIREMENTS
+%   none.
+%  
+% 
+% Copyright (C) 2014-2015 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+
+%% set bounds and parameter names if not already set
+n_params=size(start_par_value,1);
+if isempty(bounds)
+    if isnumeric(minimizer_algorithm) && minimizer_algorithm==10
+        error('Algorithm 10 (simpsa) requires upper and lower bounds')
+    else
+        bounds=[-Inf(n_params,1) Inf(n_params,1)];
+    end
+end
+
+if isempty(parameter_names)
+    parameter_names=[repmat('parameter ',n_params,1),num2str((1:n_params)')];
+end
+
+%% initialize function outputs
+hessian_mat=[];
+Scale=[];
+exitflag=1;
+fval=NaN;
+opt_par_values=NaN(size(start_par_value));
+
+
+switch minimizer_algorithm
+  case 1
+    if isoctave
+        error('Optimization algorithm 1 is not available under Octave')
+    elseif ~user_has_matlab_license('optimization_toolbox')
+        error('Optimization algorithm 1 requires the Optimization Toolbox')
+    end
+    % Set default optimization options for fmincon.
+    optim_options = optimset('display','iter', 'LargeScale','off', 'MaxFunEvals',100000, 'TolFun',1e-8, 'TolX',1e-6);
+    if ~isempty(options_.optim_opt)
+        eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']);
+    end
+    if options_.analytic_derivation,
+        optim_options = optimset(optim_options,'GradObj','on','TolX',1e-7);
+    end
+    [opt_par_values,fval,exitflag,output,lamdba,grad,hessian_mat] = ...
+        fmincon(objective_function,start_par_value,[],[],[],[],bounds(:,1),bounds(:,2),[],optim_options,varargin{:});
+  case 2
+    %simulating annealing
+    sa_options = options_.saopt;
+    if ~isempty(options_.optim_opt)
+        options_list = read_key_value_string(options_.optim_opt);
+        for i=1:rows(options_list)
+            switch options_list{i,1}
+              case 'neps'
+                sa_options.neps = options_list{i,2};
+              case 'rt'
+                sa_options.rt = options_list{i,2};
+              case 'MaxIter'
+                sa_options.MaxIter = options_list{i,2};
+              case 'TolFun'
+                sa_options.TolFun = options_list{i,2};
+              case 'verbosity'
+                sa_options.verbosity = options_list{i,2};
+              case 'initial_temperature'
+                sa_options.initial_temperature = options_list{i,2};
+              case 'ns'
+                sa_options.ns = options_list{i,2};
+              case 'nt'
+                sa_options.nt = options_list{i,2};
+              case 'step_length_c'
+                sa_options.step_length_c = options_list{i,2};
+              case 'initial_step_length'
+                sa_options.initial_step_length = options_list{i,2};
+              otherwise
+                warning(['solveopt: Unknown option (' options_list{i,1} ')!'])
+            end
+        end
+    end
+    npar=length(start_par_value);
+    [LB, UB]=set_bounds_to_finite_values(bounds, options_.huge_number);
+    fprintf('\nNumber of parameters= %d, initial temperatur= %4.3f \n', npar,sa_options.initial_temperature);
+    fprintf('rt=  %4.3f; TolFun=  %4.3f; ns=  %4.3f;\n',sa_options.rt,sa_options.TolFun,sa_options.ns);
+    fprintf('nt=  %4.3f; neps=  %4.3f; MaxIter=  %d\n',sa_options.nt,sa_options.neps,sa_options.MaxIter);
+    fprintf('Initial step length(vm): %4.3f; step_length_c: %4.3f\n', sa_options.initial_step_length,sa_options.step_length_c);
+    fprintf('%-20s  %-6s    %-6s    %-6s\n','Name:', 'LB;','Start;','UB;');
+    for pariter=1:npar
+        fprintf('%-20s  %6.4f;   %6.4f;  %6.4f;\n',parameter_names{pariter}, LB(pariter),start_par_value(pariter),UB(pariter));
+    end
+    sa_options.initial_step_length= sa_options.initial_step_length*ones(npar,1); %bring step length to correct vector size
+    sa_options.step_length_c= sa_options.step_length_c*ones(npar,1); %bring step_length_c to correct vector size
+    [opt_par_values, fval,exitflag, n_accepted_draws, n_total_draws, n_out_of_bounds_draws, t, vm] =...
+        simulated_annealing(objective_function,start_par_value,sa_options,LB,UB,varargin{:});
+  case 3
+    if isoctave && ~user_has_octave_forge_package('optim')
+        error('Optimization algorithm 3 requires the optim package')
+    elseif ~isoctave && ~user_has_matlab_license('optimization_toolbox')
+        error('Optimization algorithm 3 requires the Optimization Toolbox')
+    end
+    % Set default optimization options for fminunc.
+    optim_options = optimset('display','iter','MaxFunEvals',100000,'TolFun',1e-8,'TolX',1e-6);
+    if ~isempty(options_.optim_opt)
+        eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']);
+    end
+    if options_.analytic_derivation,
+        optim_options = optimset(optim_options,'GradObj','on');
+    end
+    if ~isoctave
+        [opt_par_values,fval,exitflag] = fminunc(objective_function,start_par_value,optim_options,varargin{:});
+    else
+        % Under Octave, use a wrapper, since fminunc() does not have a 4th arg
+        func = @(x) objective_function(x,varargin{:});
+        [opt_par_values,fval,exitflag] = fminunc(func,start_par_value,optim_options);
+    end
+  case 4
+    % Set default options.
+    H0 = 1e-4*eye(n_params);
+    crit = options_.csminwel.tolerance.f;
+    nit = options_.csminwel.maxiter;
+    numgrad = options_.gradient_method;
+    epsilon = options_.gradient_epsilon;
+    % Change some options.
+    if ~isempty(options_.optim_opt)
+        options_list = read_key_value_string(options_.optim_opt);
+        for i=1:rows(options_list)
+            switch options_list{i,1}
+              case 'MaxIter'
+                nit = options_list{i,2};
+              case 'InitialInverseHessian'
+                H0 = eval(options_list{i,2});
+              case 'TolFun'
+                crit = options_list{i,2};
+              case 'NumgradAlgorithm'
+                numgrad = options_list{i,2};
+              case 'NumgradEpsilon'
+                epsilon = options_list{i,2};
+              otherwise
+                warning(['csminwel: Unknown option (' options_list{i,1} ')!'])
+            end
+        end
+    end
+    % Set flag for analytical gradient.
+    if options_.analytic_derivation
+        analytic_grad=1;
+    else
+        analytic_grad=[];
+    end
+    % Call csminwell.
+    [fval,opt_par_values,grad,inverse_hessian_mat,itct,fcount,exitflag] = ...
+        csminwel1(objective_function, start_par_value, H0, analytic_grad, crit, nit, numgrad, epsilon, varargin{:});
+    hessian_mat=inv(inverse_hessian_mat);
+  case 5
+    if options_.analytic_derivation==-1 %set outside as code for use of analytic derivation
+        analytic_grad=1;
+        crit = options_.newrat.tolerance.f_analytic;
+        newratflag = 0; %analytical Hessian
+    else
+        analytic_grad=0;
+        crit=options_.newrat.tolerance.f;
+        newratflag = options_.newrat.hess; %default
+    end
+    nit=options_.newrat.maxiter;
+    if ~isempty(options_.optim_opt)
+        options_list = read_key_value_string(options_.optim_opt);
+        for i=1:rows(options_list)
+            switch options_list{i,1}
+              case 'MaxIter'
+                nit = options_list{i,2};
+              case 'Hessian'
+                flag=options_list{i,2};
+                if options_.analytic_derivation && flag~=0
+                    error('newrat: analytic_derivation is incompatible with numerical Hessian. Using analytic Hessian')
+                else
+                    newratflag=flag; 
+                end
+              case 'TolFun'
+                crit = options_list{i,2};
+              otherwise
+                warning(['newrat: Unknown option (' options_list{i,1} ')!'])
+            end
+        end
+    end
+    [opt_par_values,hessian_mat,gg,fval,invhess] = newrat(objective_function,start_par_value,analytic_grad,crit,nit,0,varargin{:});
+    %hessian_mat is the plain outer product gradient Hessian
+  case 6
+    [opt_par_values, hessian_mat, Scale, fval] = gmhmaxlik(objective_function, start_par_value, ...
+                                                      Initial_Hessian, options_.mh_jscale, bounds, prior_information.p2, options_.gmhmaxlik, options_.optim_opt, varargin{:});
+  case 7
+    % Matlab's simplex (Optimization toolbox needed).
+    if isoctave && ~user_has_octave_forge_package('optim')
+        error('Option mode_compute=7 requires the optim package')
+    elseif ~isoctave && ~user_has_matlab_license('optimization_toolbox')
+        error('Option mode_compute=7 requires the Optimization Toolbox')
+    end
+    optim_options = optimset('display','iter','MaxFunEvals',1000000,'MaxIter',6000,'TolFun',1e-8,'TolX',1e-6);
+    if ~isempty(options_.optim_opt)
+        eval(['optim_options = optimset(optim_options,' options_.optim_opt ');']);
+    end
+    if ~isoctave
+        [opt_par_values,fval,exitflag] = fminsearch(objective_function,start_par_value,optim_options,varargin{:});
+    else
+        % Under Octave, use a wrapper, since fminsearch() does not have a 4th arg
+        func = @(x) objective_function(x,varargin{:});
+        [opt_par_values,fval,exitflag] = fminsearch(func,start_par_value,optim_options);
+    end
+  case 8
+    % Dynare implementation of the simplex algorithm.
+    simplexOptions = options_.simplex;
+    if ~isempty(options_.optim_opt)
+        options_list = read_key_value_string(options_.optim_opt);
+        for i=1:rows(options_list)
+            switch options_list{i,1}
+              case 'MaxIter'
+                simplexOptions.maxiter = options_list{i,2};
+              case 'TolFun'
+                simplexOptions.tolerance.f = options_list{i,2};
+              case 'TolX'
+                simplexOptions.tolerance.x = options_list{i,2};
+              case 'MaxFunEvals'
+                simplexOptions.maxfcall = options_list{i,2};
+              case 'MaxFunEvalFactor'
+                simplexOptions.maxfcallfactor = options_list{i,2};
+              case 'InitialSimplexSize'
+                simplexOptions.delta_factor = options_list{i,2};
+              otherwise
+                warning(['simplex: Unknown option (' options_list{i,1} ')!'])
+            end
+        end
+    end
+    [opt_par_values,fval,exitflag] = simplex_optimization_routine(objective_function,start_par_value,simplexOptions,parameter_names,varargin{:});
+  case 9
+    % Set defaults
+    H0 = 1e-4*ones(n_params,1);
+    cmaesOptions = options_.cmaes;
+    % Modify defaults
+    if ~isempty(options_.optim_opt)
+        options_list = read_key_value_string(options_.optim_opt);
+        for i=1:rows(options_list)
+            switch options_list{i,1}
+              case 'MaxIter'
+                cmaesOptions.MaxIter = options_list{i,2};
+              case 'TolFun'
+                cmaesOptions.TolFun = options_list{i,2};
+              case 'TolX'
+                cmaesOptions.TolX = options_list{i,2};
+              case 'MaxFunEvals'
+                cmaesOptions.MaxFunEvals = options_list{i,2};
+              otherwise
+                warning(['cmaes: Unknown option (' options_list{i,1}  ')!'])
+            end
+        end
+    end
+    warning('off','CMAES:NonfinitenessRange');
+    warning('off','CMAES:InitialSigma');
+    [x, fval, COUNTEVAL, STOPFLAG, OUT, BESTEVER] = cmaes(func2str(objective_function),start_par_value,H0,cmaesOptions,varargin{:});
+    opt_par_values=BESTEVER.x;
+    fval=BESTEVER.f;
+  case 10
+    simpsaOptions = options_.simpsa;
+    if ~isempty(options_.optim_opt)
+        options_list = read_key_value_string(options_.optim_opt);
+        for i=1:rows(options_list)
+            switch options_list{i,1}
+              case 'MaxIter'
+                simpsaOptions.MAX_ITER_TOTAL = options_list{i,2};
+              case 'TolFun'
+                simpsaOptions.TOLFUN = options_list{i,2};
+              case 'TolX'
+                tolx = options_list{i,2};
+                if tolx<0
+                    simpsaOptions = rmfield(simpsaOptions,'TOLX'); % Let simpsa choose the default.
+                else
+                    simpsaOptions.TOLX = tolx;
+                end
+              case 'EndTemparature'
+                simpsaOptions.TEMP_END = options_list{i,2};
+              case 'MaxFunEvals'
+                simpsaOptions.MAX_FUN_EVALS = options_list{i,2};
+              otherwise
+                warning(['simpsa: Unknown option (' options_list{i,1}  ')!'])
+            end
+        end
+    end
+    simpsaOptionsList = options2cell(simpsaOptions);
+    simpsaOptions = simpsaset(simpsaOptionsList{:});
+    [LB, UB]=set_bounds_to_finite_values(bounds, options_.huge_number);
+    [opt_par_values, fval, exitflag] = simpsa(func2str(objective_function),start_par_value,LB,UB,simpsaOptions,varargin{:});
+  case 11
+     options_.cova_compute = 0 ;
+     [opt_par_values,stdh,lb_95,ub_95,med_param] = online_auxiliary_filter(start_par_value,varargin{:}) ;
+  case 101
+    solveoptoptions = options_.solveopt;
+    if ~isempty(options_.optim_opt)
+        options_list = read_key_value_string(options_.optim_opt);
+        for i=1:rows(options_list)
+            switch options_list{i,1}
+              case 'TolX'
+                solveoptoptions.TolX = options_list{i,2};
+              case 'TolFun'
+                solveoptoptions.TolFun = options_list{i,2};
+              case 'MaxIter'
+                solveoptoptions.MaxIter = options_list{i,2};
+              case 'verbosity'
+                solveoptoptions.verbosity = options_list{i,2};
+              case 'SpaceDilation'
+                solveoptoptions.SpaceDilation = options_list{i,2};
+              case 'LBGradientStep'
+                solveoptoptions.LBGradientStep = options_list{i,2};
+              otherwise
+                warning(['solveopt: Unknown option (' options_list{i,1} ')!'])
+            end
+        end
+    end
+    [opt_par_values,fval]=solvopt(start_par_value,objective_function,[],[],[],solveoptoptions,varargin{:});
+  case 102
+    if isoctave
+        error('Optimization algorithm 2 is not available under Octave')
+    elseif ~user_has_matlab_license('GADS_Toolbox')
+        error('Optimization algorithm 2 requires the Global Optimization Toolbox')
+    end
+    % Set default optimization options for fmincon.
+    optim_options = saoptimset('display','iter','TolFun',1e-8);
+    if ~isempty(options_.optim_opt)
+        eval(['optim_options = saoptimset(optim_options,' options_.optim_opt ');']);
+    end
+    func = @(x)objective_function(x,varargin{:});
+    [opt_par_values,fval,exitflag,output] = simulannealbnd(func,start_par_value,bounds(:,1),bounds(:,2),optim_options);
+  otherwise
+    if ischar(minimizer_algorithm)
+        if exist(options_.mode_compute)
+            [opt_par_values, fval, exitflag] = feval(options_.mode_compute,objective_function,start_par_value,varargin{:});
+        else
+            error('No minimizer with the provided name detected.')
+        end
+    else
+        error(['Optimization algorithm ' int2str(minimizer_algorithm) ' is unknown!'])
+    end
+end
+
+end
+
+function [LB, UB]=set_bounds_to_finite_values(bounds, huge_number)
+    LB=bounds(:,1);
+    LB(isinf(LB))=-huge_number;
+    UB=bounds(:,2);
+    UB(isinf(UB))=huge_number;
+end
diff --git a/matlab/optimization/gmhmaxlik.m b/matlab/optimization/gmhmaxlik.m
new file mode 100644
index 0000000000000000000000000000000000000000..6ac4f79c96876940982a7550b95408a14895ad1a
--- /dev/null
+++ b/matlab/optimization/gmhmaxlik.m
@@ -0,0 +1,120 @@
+function [PostMode, HessianMatrix, Scale, ModeValue] = gmhmaxlik(fun, xinit, Hinit, iscale, bounds, priorstd, gmhmaxlikOptions, OptimizationOptions, varargin)
+
+% Copyright (C) 2006-2015 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+    
+% Set default options
+
+if ~isempty(Hinit);
+    gmhmaxlikOptions.varinit = 'previous';
+else
+    gmhmaxlikOptions.varinit = 'prior';
+end
+
+if ~isempty(OptimizationOptions)
+    DynareOptionslist = read_key_value_string(OptimizationOptions);
+    for i=1:rows(DynareOptionslist)
+        switch DynareOptionslist{i,1}
+          case 'NumberOfMh'
+            gmhmaxlikOptions.iterations = DynareOptionslist{i,2};
+          case 'ncov-mh'
+            gmhmaxlikOptions.number = DynareOptionslist{i,2};
+          case 'nscale'
+            gmhmaxlikOptions.nscale = DynareOptionslist{i,2};
+          case 'nclimb'
+            gmhmaxlikOptions.nclimb = DynareOptionslist{i,2};
+          case 'InitialCovarianceMatrix'
+            switch DynareOptionslist{i,2}
+              case 'previous'
+                if isempty(Hinit)
+                    error('gmhmaxlik: No previous estimate of the Hessian matrix available! You cannot use the InitialCovarianceMatrix option!')
+                else
+                    gmhmaxlikOptions.varinit = 'previous';
+                end
+              case {'prior', 'identity'}
+                gmhmaxlikOptions.varinit = DynareOptionslist{i,2};
+              otherwise
+                error('gmhmaxlik: Unknown value for option ''InitialCovarianceMatrix''!')
+            end
+          case 'AcceptanceRateTarget'
+            gmhmaxlikOptions.target = DynareOptionslist{i,2};
+            if gmhmaxlikOptions.target>1 || gmhmaxlikOptions.target<eps
+                error('gmhmaxlik: The value of option AcceptanceRateTarget should be a double between 0 and 1!')
+            end
+          otherwise
+            warning(['gmhmaxlik: Unknown option (' DynareOptionslist{i,1}  ')!'])
+        end
+    end
+end
+
+% Evaluate the objective function.
+OldModeValue = feval(fun,xinit,varargin{:});
+
+if ~exist('MeanPar','var')
+    MeanPar = xinit;
+end
+
+switch gmhmaxlikOptions.varinit
+  case 'previous'
+    CovJump = inv(Hinit);
+  case 'prior'
+    % The covariance matrix is initialized with the prior
+    % covariance (a diagonal matrix) %%Except for infinite variances ;-)
+    stdev = priorstd;
+    indx = find(isinf(stdev));
+    stdev(indx) = ones(length(indx),1)*sqrt(10);
+    vars = stdev.^2;
+    CovJump = diag(vars);
+  case 'identity'
+    vars = ones(length(priorstd),1)*0.1;
+    CovJump = diag(vars);
+  otherwise
+    error('gmhmaxlik: This is a bug! Please contact the developers.')
+end
+
+OldPostVariance = CovJump;
+OldPostMean = xinit;
+OldPostMode = xinit;
+Scale = iscale;
+
+for i=1:gmhmaxlikOptions.iterations
+    if i<gmhmaxlikOptions.iterations
+        flag = '';
+    else
+        flag = 'LastCall';
+    end
+    [PostMode, PostVariance, Scale, PostMean] = gmhmaxlik_core(fun, OldPostMode, bounds, gmhmaxlikOptions, Scale, flag, MeanPar, OldPostVariance, varargin{:});
+    ModeValue = feval(fun, PostMode, varargin{:});
+    dVariance = max(max(abs(PostVariance-OldPostVariance)));
+    dMean = max(abs(PostMean-OldPostMean));
+    skipline()
+    printline(58,'=')
+    disp(['   Change in the posterior covariance matrix = ' num2str(dVariance) '.'])
+    disp(['   Change in the posterior mean = ' num2str(dMean) '.'])
+    disp(['   Mode improvement = ' num2str(abs(OldModeValue-ModeValue))])
+    disp(['   New value of jscale = ' num2str(Scale)])
+    printline(58,'=')
+    OldModeValue = ModeValue;
+    OldPostMean = PostMean;
+    OldPostVariance = PostVariance;
+end
+
+HessianMatrix = inv(PostVariance);
+
+skipline()
+disp(['Optimal value of the scale parameter = ' num2str(Scale)])
+skipline()
\ No newline at end of file
diff --git a/matlab/gmhmaxlik.m b/matlab/optimization/gmhmaxlik_core.m
similarity index 97%
rename from matlab/gmhmaxlik.m
rename to matlab/optimization/gmhmaxlik_core.m
index b5789d230b844674846e7cf78d3479a73ff98f3e..2d7a3cb814fe1db262ff8ab597ecf24049e5bcff 100644
--- a/matlab/gmhmaxlik.m
+++ b/matlab/optimization/gmhmaxlik_core.m
@@ -1,8 +1,5 @@
-function [PostMod,PostVar,Scale,PostMean] = ...
-    gmhmaxlik(ObjFun,xparam1,mh_bounds,options,iScale,info,MeanPar,VarCov,varargin)  
+function [PostMod,PostVar,Scale,PostMean] = gmhmaxlik_core(ObjFun,xparam1,mh_bounds,options,iScale,info,MeanPar,VarCov,varargin)  
 
-%function [PostMod,PostVar,Scale,PostMean] = ...
-%gmhmaxlik(ObjFun,xparam1,mh_bounds,num,iScale,info,MeanPar,VarCov,varargin)  
 % (Dirty) Global minimization routine of (minus) a likelihood (or posterior density) function. 
 % 
 % INPUTS 
@@ -59,7 +56,7 @@ function [PostMod,PostVar,Scale,PostMean] = ...
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 2006-2012 Dynare Team
+% Copyright (C) 2006-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
diff --git a/matlab/mr_gstep.m b/matlab/optimization/mr_gstep.m
similarity index 100%
rename from matlab/mr_gstep.m
rename to matlab/optimization/mr_gstep.m
diff --git a/matlab/mr_hessian.m b/matlab/optimization/mr_hessian.m
similarity index 100%
rename from matlab/mr_hessian.m
rename to matlab/optimization/mr_hessian.m
diff --git a/matlab/numgrad2.m b/matlab/optimization/numgrad2.m
similarity index 100%
rename from matlab/numgrad2.m
rename to matlab/optimization/numgrad2.m
diff --git a/matlab/numgrad3.m b/matlab/optimization/numgrad3.m
similarity index 100%
rename from matlab/numgrad3.m
rename to matlab/optimization/numgrad3.m
diff --git a/matlab/numgrad3_.m b/matlab/optimization/numgrad3_.m
similarity index 100%
rename from matlab/numgrad3_.m
rename to matlab/optimization/numgrad3_.m
diff --git a/matlab/numgrad5.m b/matlab/optimization/numgrad5.m
similarity index 100%
rename from matlab/numgrad5.m
rename to matlab/optimization/numgrad5.m
diff --git a/matlab/numgrad5_.m b/matlab/optimization/numgrad5_.m
similarity index 100%
rename from matlab/numgrad5_.m
rename to matlab/optimization/numgrad5_.m
diff --git a/matlab/simplex_optimization_routine.m b/matlab/optimization/simplex_optimization_routine.m
similarity index 100%
rename from matlab/simplex_optimization_routine.m
rename to matlab/optimization/simplex_optimization_routine.m
diff --git a/matlab/simpsa.m b/matlab/optimization/simpsa.m
similarity index 100%
rename from matlab/simpsa.m
rename to matlab/optimization/simpsa.m
diff --git a/matlab/simpsaget.m b/matlab/optimization/simpsaget.m
similarity index 100%
rename from matlab/simpsaget.m
rename to matlab/optimization/simpsaget.m
diff --git a/matlab/simpsaset.m b/matlab/optimization/simpsaset.m
similarity index 100%
rename from matlab/simpsaset.m
rename to matlab/optimization/simpsaset.m
diff --git a/matlab/optimization/simulated_annealing.m b/matlab/optimization/simulated_annealing.m
new file mode 100644
index 0000000000000000000000000000000000000000..5b505b71d6246d288da9c2e72b60e2c46dafaaf1
--- /dev/null
+++ b/matlab/optimization/simulated_annealing.m
@@ -0,0 +1,459 @@
+function [xopt, fopt,exitflag, n_accepted_draws, n_total_draws, n_out_of_bounds_draws, t, vm] = ...
+    simulated_annealing(fcn,x,optim,lb,ub,varargin)
+% function [xopt, fopt,exitflag, n_accepted_draws, n_total_draws, n_out_of_bounds_draws, t, vm] = ...
+%     simulated_annealing(fcn,x,optim,lb,ub,varargin)
+%
+% Implements the continuous simulated annealing global optimization
+% algorithm described in Corana et al. (1987)
+% 
+%  A very quick (perhaps too quick) overview of SA:
+%     SA tries to find the global optimum of an N dimensional function.
+%  It moves both up and downhill and as the optimization process
+%  proceeds, it focuses on the most promising area.
+%     To start, it randomly chooses a trial point within the step length
+%  VM (a vector of length N) of the user selected starting point. The
+%  function is evaluated at this trial point and its value is compared
+%  to its value at the initial point.
+%     In a maximization problem, all uphill moves are accepted and the
+%  algorithm continues from that trial point. Downhill moves may be
+%  accepted  the decision is made by the Metropolis criteria. It uses T
+%  (temperature) and the size of the downhill move in a probabilistic
+%  manner. The smaller T and the size of the downhill move are, the more
+%  likely that move will be accepted. If the trial is accepted, the
+%  algorithm moves on from that point. If it is rejected, another point
+%  is chosen instead for a trial evaluation.
+%     Each element of VM periodically adjusted so that half of all
+%  function evaluations in that direction are accepted.
+%     A fall in T is imposed upon the system with the RT option by
+%  T(i+1) = RT*T(i) where i is the ith iteration. Thus, as T declines,
+%  downhill moves are less likely to be accepted and the percentage of
+%  rejections rise. Given the scheme for the selection for VM, VM falls.
+%  Thus, as T declines, VM falls and SA focuses upon the most promising
+%  area for optimization.
+%
+%  The importance of the parameter T (initial_temperature):
+%     The parameter T is crucial in using SA successfully. It influences
+%  VM, the step length over which the algorithm searches for optima. For
+%  a small intial T, the step length may be too small  thus not enough
+%  of the function might be evaluated to find the global optima. The user
+%  should carefully examine VM in the intermediate output (set verbosity =
+%  1) to make sure that VM is appropriate. The relationship between the
+%  initial temperature and the resulting step length is function
+%  dependent.
+%     To determine the starting temperature that is consistent with
+%  optimizing a function, it is worthwhile to run a trial run first. Set
+%  RT = 1.5 and T = 1.0. With RT > 1.0, the temperature increases and VM
+%  rises as well. Then select the T that produces a large enough VM.
+%
+%  Input Parameters:
+%    Note: The suggested values generally come from Corana et al. To
+%          drastically reduce runtime, see Goffe et al., pp. 90-1 for
+%          suggestions on choosing the appropriate RT and NT.
+% 
+%    fcn - function to be optimized.
+%    x - The starting values for the variables of the function to be
+%        optimized. (N)
+%    optim:     Options structure with fields
+% 
+%       optim.maximizer_indicator - Denotes whether the function should be maximized or
+%           minimized. A value =1 denotes maximization while a
+%           value =0 denotes minimization. Intermediate output (see verbosity)
+%           takes this into account.
+%       optim.RT - The temperature reduction factor 
+%       optim.TolFun - Error tolerance for termination. If the final function
+%           values from the last neps temperatures differ from the
+%           corresponding value at the current temperature by less than
+%           optim.TolFun and the final function value at the current temperature
+%           differs from the current optimal function value by less than
+%           optim.TolFun, execution terminates and exitflag = 0 is returned.
+%       optim.ns - Number of cycles. After NS*N function evaluations, each
+%           element of VM is adjusted so that approximately half of
+%           all function evaluations are accepted. The suggested value
+%           is 20.
+%       optim.nt - Number of iterations before temperature reduction. After
+%           NT*NS*N function evaluations, temperature (T) is changed
+%           by the factor optim.RT. Value suggested by Corana et al. is
+%           max(100, 5*n). See Goffe et al. for further advice.
+%       optim.neps - Number of final function values used to decide upon termi-
+%           nation. See optim.TolFun. Suggested value is 4.
+%       optim.MaxIter - Maximum number of function evaluations. If it is
+%           exceeded, exitflag = 1.
+%       optim.step_length_c - Vector that controls the step length adjustment. The suggested
+%           value for all elements is 2.0.
+%       optim.verbosity - controls printing inside SA.
+%           Values: 0 - Nothing printed.
+%                     1 - Function value for the starting value and summary results before each temperature
+%                         reduction. This includes the optimal function value found so far, the total
+%                         number of moves (broken up into uphill, downhill, accepted and rejected), the
+%                         number of out of bounds trials, the number of new optima found at this
+%                         temperature, the current optimal X and the step length VM. Note that there are
+%                         N*NS*NT function evalutations before each temperature reduction. Finally, notice is
+%                         is also given upon achieveing the termination criteria.
+%                     2 - Each new step length (VM), the current optimal X (XOPT) and the current trial X (X). This
+%                         gives the user some idea about how far X strays from XOPT as well as how VM is adapting
+%                         to the function.
+%                     3 - Each function evaluation, its acceptance or rejection and new optima. For many problems,
+%                         this option will likely require a small tree if hard copy is used. This option is best
+%                         used to learn about the algorithm. A small value for optim.MaxIter is thus recommended when
+%                         using optim.verbosity = 3.
+%    optim.initial_temperature  initial temperature. See Goffe et al. for advice.
+%    optim.initial_step_length  (VM) step length vector. On input it should encompass the
+%                               region of interest given the starting value X. For point
+%                               X(I), the next trial point is selected is from X(I) - VM(I)
+%                               to  X(I) + VM(I). Since VM is adjusted so that about half
+%                               of all points are accepted, the input value is not very
+%                               important (i.e. is the value is off, SA adjusts VM to the
+%                               correct value)
+% 
+%    lb - The lower bound for the allowable solution variables. 
+%    ub - The upper bound for the allowable solution variables. 
+%         If the algorithm chooses X(I) < LB(I) or X(I) > UB(I),
+%         I = 1, N, a point is from inside is randomly selected. 
+%         This focuses the algorithm on the region inside UB and LB.
+%         Unless the user wishes to concentrate the search to a par-
+%         ticular region, UB and LB should be set to very large positive
+%         and negative values, respectively. Note that the starting
+%         vector X should be inside this region. Also note that LB and
+%         UB are fixed in position, while VM is centered on the last
+%         accepted trial set of variables that optimizes the function.
+% 
+% 
+% Input/Output Parameters:
+%
+%  Output Parameters:
+%    xopt - The variables that optimize the function. (N)
+%    fopt - The optimal value of the function.
+%    exitflag - The error return number.
+%          Values: 0 - Normal return  termination criteria achieved.
+%                  1 - Number of function evaluations (NFCNEV) is
+%                      greater than the maximum number (optim.MaxIter).
+%                  2 - The starting value (X) is not inside the
+%                      bounds (LB and UB).
+%                  3 - The initial temperature is not positive.
+%                  99 - Should not be seen  only used internally.
+%    n_accepted_draws - The number of accepted function evaluations.
+%    n_total_draws - The total number of function evaluations. In a minor
+%             point, note that the first evaluation is not used in the
+%             core of the algorithm  it simply initializes the
+%             algorithm.
+%    n_out_of_bounds_draws - The total number of trial function evaluations that
+%            would have been out of bounds of LB and UB. Note that
+%            a trial point is randomly selected between LB and UB.
+%    t:     On output, the final temperature.
+%    vm:    Final step length vector
+%
+% Algorithm: 
+%  This routine implements the continuous simulated annealing global
+%  optimization algorithm described in Corana et al.'s article
+%  "Minimizing Multimodal Functions of Continuous Variables with the
+%  "Simulated Annealing" Algorithm" in the September 1987 (vol. 13,
+%  no. 3, pp. 262-280) issue of the ACM Transactions on Mathematical
+%  Software.
+% 
+% For modifications to the algorithm and many details on its use,
+%  (particularly for econometric applications) see Goffe, Ferrier
+%  and Rogers, "Global Optimization of Statistical Functions with
+%  Simulated Annealing," Journal of Econometrics, vol. 60, no. 1/2,
+%  Jan./Feb. 1994, pp. 65-100.
+% 
+%  Based on the Matlab code written by Thomas Werner (Bundesbank December
+%  2002), which in turn is based on the GAUSS version of Bill Goffe's simulated annealing 
+%  program for global optimization, written by E.G.Tsionas (9/4/95).
+% 
+% Copyright (C) 1995 E.G.Tsionas 
+% Copyright (C) 1995-2002 Thomas Werner 
+% Copyright (C) 2002-2015 Giovanni Lombardo
+% Copyright (C) 2015 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+c=optim.step_length_c;
+t=optim.initial_temperature;
+vm=optim.initial_step_length;
+n=size(x,1);
+xp=zeros(n,1);
+%*  Set initial values.*
+n_accepted_draws=0;
+n_out_of_bounds_draws=0;
+n_total_draws=0;
+exitflag=99;
+xopt=x;
+nacp=zeros(n,1);
+fstar=1e20*ones(optim.neps,1);
+%* If the initial temperature is not positive, notify the user and abort. *
+if(t<=0.0);
+    fprintf('\nThe initial temperature is not positive. Reset the variable t\n');
+    exitflag=3;
+    return;
+end;
+%*  If the initial value is out of bounds, notify the user and abort. *
+if(sum(x>ub)+sum(x<lb)>0);
+    fprintf('\nInitial condition out of bounds\n');
+    exitflag=2;
+    return;
+end;
+%*  Evaluate the function with input x and return value as f. *
+f=feval(fcn,x,varargin{:});
+%*
+%  If the function is to be minimized, switch the sign of the function.
+%  Note that all intermediate and final output switches the sign back
+%  to eliminate any possible confusion for the user.
+%*
+if(optim.maximizer_indicator==0);
+    f=-f;
+end;
+n_total_draws=n_total_draws+1;
+fopt=f;
+fstar(1)=f;
+if(optim.verbosity >1);
+    disp '  ';
+    disp(['initial x    ' num2str(x(:)')]);
+    if(optim.maximizer_indicator);
+        disp(['initial f    ' num2str(f)]);
+    else
+        disp(['initial f    ' num2str(-f)]);
+    end;
+end;
+%  Start the main loop. Note that it terminates if (i) the algorithm
+%  succesfully optimizes the function or (ii) there are too many
+%  function evaluations (more than optim.MaxIter).
+
+while (1>0);
+    nup=0;
+    nrej=0;
+    nnew=0;
+    ndown=0;
+    lnobds=0;
+    m=1;
+    while m<=optim.nt;
+        j=1;
+        while j<=optim.ns;
+            h=1;
+            while h<=n;
+                %*  Generate xp, the trial value of x. Note use of vm to choose xp. *
+                i=1;
+                while i<=n;
+                    if(i==h);
+                        xp(i)=x(i)+(rand(1,1)*2.0-1.0)*vm(i);
+                    else
+                        xp(i)=x(i);
+                    end;
+                    %*  If xp is out of bounds, select a point in bounds for the trial. *
+                    if((xp(i)<lb(i) || xp(i)>ub(i)));
+                        xp(i)=lb(i)+(ub(i)-lb(i))*rand(1,1);
+                        lnobds=lnobds+1;
+                        n_out_of_bounds_draws=n_out_of_bounds_draws+1;
+                        if(optim.verbosity >=3);
+                            if exist('fp','var')
+                                print_current_invalid_try(optim.maximizer_indicator,xp,x,fp,f);
+                            end
+                        end;
+                    end;
+                    i=i+1;
+                end;
+                %*  Evaluate the function with the trial point xp and return as fp. *
+                % fp=feval(fcn,xp,listarg);
+                fp=feval(fcn,xp,varargin{:});
+                if(optim.maximizer_indicator==0);
+                    fp=-fp;
+                end;
+                n_total_draws=n_total_draws+1;
+                if(optim.verbosity >=3);
+                    print_current_valid_try(optim.maximizer_indicator,xp,x,fp,f);
+                end;
+                %*  If too many function evaluations occur, terminate the algorithm. *
+                if(n_total_draws>=optim.MaxIter);
+                    fprintf('Too many function evaluations; consider\n');
+                    fprintf('increasing optim.MaxIter or optim.TolFun or decreasing\n');
+                    fprintf('optim.nt or optim.rt. These results are likely to be poor\n');
+                    if(optim.maximizer_indicator==0);
+                        fopt=-fopt;
+                    end;
+                    exitflag=1;
+                    return;
+                end;
+                %*  Accept the new point if the function value increases. *
+                if(fp>=f);
+                    if(optim.verbosity >=3);
+                        fprintf('point accepted\n');
+                    end;
+                    x=xp;
+                    f=fp;
+                    n_accepted_draws=n_accepted_draws+1;
+                    nacp(h)=nacp(h)+1;
+                    nup=nup+1;
+                    %*  If greater than any other point, record as new optimum. *
+                    if(fp>fopt);
+                        if(optim.verbosity >=3);
+                            fprintf('new optimum\n');
+                        end;
+                        xopt=xp;
+                        fopt=fp;
+                        nnew=nnew+1;
+                    end;
+                    %*
+                    % If the point is lower, use the Metropolis criteria to decide on
+                    % acceptance or rejection.
+                    %*
+                else
+                    p=exp((fp-f)/t);
+                    pp=rand(1,1);
+                    if(pp<p);
+                        if(optim.verbosity >=3);
+                            if(optim.maximizer_indicator);
+                             fprintf('though lower, point accepted\n');
+                            else
+                             fprintf('though higher, point accepted\n');
+                            end;
+                        end;
+                        x=xp;
+                        f=fp;
+                        n_accepted_draws=n_accepted_draws+1;
+                        nacp(h)=nacp(h)+1;
+                        ndown=ndown+1;
+                    else
+                        nrej=nrej+1;
+                        if(optim.verbosity >=3);
+                            if(optim.maximizer_indicator);
+                                fprintf('lower point rejected\n');
+                            else
+                                fprintf('higher point rejected\n');
+                            end;
+                        end;
+                    end;
+                end;
+                h=h+1;
+            end;
+            j=j+1;
+        end;
+        %*  Adjust vm so that approximately half of all evaluations are accepted. *
+        i=1;
+        while i<=n;
+            ratio=nacp(i)/optim.ns;
+            if(ratio>.6);
+                vm(i)=vm(i)*(1.+c(i)*(ratio-.6)/.4);
+            elseif(ratio<.4);
+                vm(i)=vm(i)/(1.+c(i)*((.4-ratio)/.4));
+            end;
+            if(vm(i)>(ub(i)-lb(i)));
+                vm(i)=ub(i)-lb(i);
+            end;
+            i=i+1;
+        end;
+        if(optim.verbosity >=2);
+            fprintf('intermediate results after step length adjustment\n');
+            fprintf('new step length(vm)  %4.3f', vm(:)');
+            fprintf('current optimal x    %4.3f', xopt(:)');
+            fprintf('current x            %4.3f', x(:)');
+        end;
+        nacp=zeros(n,1);
+        m=m+1;
+    end;
+    if(optim.verbosity >=1);
+        print_intermediate_statistics(optim.maximizer_indicator,t,xopt,vm,fopt,nup,ndown,nrej,lnobds,nnew);
+    end;
+    %*  Check termination criteria. *
+    quit=0;
+    fstar(1)=f;
+    if((fopt-fstar(1))<=optim.TolFun);
+        quit=1;
+    end;
+    if(sum(abs(f-fstar)>optim.TolFun)>0);
+        quit=0;
+    end;
+    %*  Terminate SA if appropriate. *
+    if(quit);
+        exitflag=0;
+        if(optim.maximizer_indicator==0);
+            fopt=-fopt;
+        end;
+        if(optim.verbosity >=1);
+            fprintf('SA achieved termination criteria.exitflag=0\n');
+        end;
+        return;        
+    end;
+    %*  If termination criteria are not met, prepare for another loop. *
+    t=optim.rt*t;
+    i=optim.neps;
+    while i>=2;
+        fstar(i)=fstar(i-1);
+        i=i-1;
+    end;
+    f=fopt;
+    x=xopt;
+    %*  Loop again. *
+end;
+
+end
+
+function  print_current_invalid_try(max,xp,x,fp,f)
+fprintf('\n');
+    disp(['Current x    ' num2str(x(:)')]);
+if(max);
+    disp(['Current f    ' num2str(f)]);
+else
+    disp(['Current f    ' num2str(-f)]);
+end;
+disp(['Trial x      ' num2str(xp(:)')]);
+disp 'Point rejected since out of bounds';
+end
+
+function print_current_valid_try(max,xp,x,fp,f)
+
+disp(['Current x    ' num2str(x(:)')]);
+if(max);
+    disp(['Current f   ' num2str(f)]);
+    disp(['Trial x     ' num2str(xp(:)')]);
+    disp(['Resulting f ' num2str(fp)]);
+else
+    disp(['Current f   ' num2str(-f)]);
+    disp(['Trial x     ' num2str(xp(:)')]);
+    disp(['Resulting f ' num2str(-fp)]);
+end;
+end
+
+
+function  print_intermediate_statistics(max,t,xopt,vm,fopt,nup,ndown,nrej,lnobds,nnew)
+
+totmov=nup+ndown+nrej;
+fprintf('\nIntermediate results before next temperature reduction\n');
+disp(['current temperature         ' num2str(t)]);
+
+if(max)
+    disp(['Max function value so far   ' num2str(fopt)]);
+    disp(['Total moves                 ' num2str(totmov)]);
+    disp(['Uphill                      ' num2str(nup)]);
+    disp(['Accepted downhill           ' num2str(ndown)]);
+    disp(['Rejected downhill           ' num2str(nrej)]);
+    disp(['Out of bounds trials        ' num2str(lnobds)]);
+    disp(['New maxima this temperature ' num2str(nnew)]);
+else
+    disp(['Min function value so far   ' num2str(-fopt)]);
+    disp(['Total moves                 ' num2str(totmov)]);
+    disp(['Downhill                    ' num2str(nup)]);
+    disp(['Accepted uphill             ' num2str(ndown)]);
+    disp(['Rejected uphill             ' num2str(nrej)]);
+    disp(['Trials out of bounds        ' num2str(lnobds)]);
+    disp(['New minima this temperature ' num2str(nnew)]);
+end
+xopt1=xopt(1:round(length(xopt)/2));
+xopt2=xopt(round(length(xopt)/2)+1:end);
+
+disp(['Current optimal x1           ' num2str(xopt1')]);
+disp(['Current optimal x2           ' num2str(xopt2')]);
+disp(['Strength(vm)                ' num2str(vm')]);
+fprintf('\n');
+end
\ No newline at end of file
diff --git a/matlab/optimization/solvopt.m b/matlab/optimization/solvopt.m
new file mode 100644
index 0000000000000000000000000000000000000000..6d5693e8643b1ee218cb8d5b1abbc37968f1a44a
--- /dev/null
+++ b/matlab/optimization/solvopt.m
@@ -0,0 +1,991 @@
+function [x,f,exitflag,n_f_evals,n_grad_evals,n_constraint_evals,n_constraint_gradient_evals]=solvopt(x,fun,grad,func,gradc,optim,varargin)
+% [x,f,options]=solvopt(x,fun,grad,func,gradc,options,varargin)
+% 
+% The function SOLVOPT, developed by Alexei Kuntsevich and Franz Kappe,  
+% performs a modified version of Shor's r-algorithm in
+% order to find a local minimum resp. maximum of a nonlinear function
+% defined on the n-dimensional Euclidean space or % a solution of a nonlinear 
+% constrained problem:
+% min { f(x): g(x) (<)= 0, g(x) in R(m), x in R(n) }
+%
+% Inputs:
+%   x       n-vector (row or column) of the coordinates of the starting
+%           point,
+% fun       name of an M-file (M-function) which computes the value
+%           of the objective function <fun> at a point x,
+%           synopsis: f=fun(x)
+% grad      name of an M-file (M-function) which computes the gradient
+%           vector of the function <fun> at a point x,
+%           synopsis: g=grad(x)
+% func      name of an M-file (M-function) which computes the MAXIMAL
+%           RESIDUAL(!) for a set of constraints at a point x,
+%           synopsis: fc=func(x)
+% gradc     name of an M-file (M-function) which computes the gradient
+%           vector for the maximal residual constraint at a point x,
+%           synopsis: gc=gradc(x)
+% optim     Options structure with fields:
+%    optim.minimizer_indicator= H, where sign(H)=-1 resp. sign(H)=+1 means minimize
+%        resp. maximize <fun> (valid only for unconstrained problem)
+%        and H itself is a factor for the initial trial step size
+%        (optim.minimizer_indicator=-1 by default),
+%    optim.TolX= relative error for the argument in terms of the
+%        infinity-norm (1.e-4 by default),
+%    optim.TolFun= relative error for the function value (1.e-6 by default),
+%    optim.MaxIter= limit for the number of iterations (15000 by default),
+%    optim.verbosity= control of the display of intermediate results and error
+%        resp. warning messages (default value is 0, i.e., no intermediate
+%        output but error and warning messages, see more in the manual),
+%    optim.TolXConstraint= admissible maximal residual for a set of constraints
+%        (optim.TolXConstraint=1e-8 by default, see more in the manual),
+%   *optim.SpaceDilation= the coefficient of space dilation (2.5 by default),
+%   *optim.LBGradientStep= lower bound for the stepsize used for the difference
+%        approximation of gradients (1e-12 by default, see more in the manual).
+%  (* ... changes should be done with care)
+% 
+% Outputs:
+% x                     optimal parameter vector (row resp. column),
+% f                     optimum function value
+% exitflag:             the number of iterations, if positive,
+%                       or an abnormal stop code, if negative (see more in the manual),
+% n_f_evals:            number of objective evaluations
+% n_grad_evals:         number of gradient evaluations,
+% n_constraint_evals:   number of constraint function evaluations,
+% n_constraint_gradient_evals   number of constraint gradient evaluations.
+% 
+% 
+% Algorithm: Kuntsevich, A.V., Kappel, F., SolvOpt - The solver for local nonlinear optimization problems 
+% (version 1.1, Matlab, C, FORTRAN). University of Graz, Graz, 1997. 
+% 
+% 
+% Copyright (C) 1997-2008, Alexei Kuntsevich and Franz Kappel 
+% Copyright (C) 2008-2015 Giovanni Lombardo
+% Copyright (C) 2015 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+
+
+% strings: ----{
+errmes='SolvOpt error:';
+wrnmes='SolvOpt warning:';
+error1='No function name and/or starting point passed to the function.';
+error2='Argument X has to be a row or column vector of dimension > 1.';
+error30='<fun> returns an empty string.';
+error31='Function value does not exist (NaN is returned).';
+error32='Function equals infinity at the point.';
+error40='<grad> returns an improper matrix. Check the dimension.';
+error41='Gradient does not exist (NaN is returned by <grad>).';
+error42='Gradient equals infinity at the starting point.';
+error43='Gradient equals zero at the starting point.';
+error50='<func> returns an empty string.';
+error51='<func> returns NaN at the point.';
+error52='<func> returns infinite value at the point.';
+error60='<gradc> returns an improper vector. Check the dimension';
+error61='<gradc> returns NaN at the point.';
+error62='<gradc> returns infinite vector at the point.';
+error63='<gradc> returns zero vector at an infeasible point.';
+error5='Function is unbounded.';
+error6='Choose another starting point.';
+warn1= 'Gradient is zero at the point, but stopping criteria are not fulfilled.';
+warn20='Normal re-setting of a transformation matrix.' ;
+warn21='Re-setting due to the use of a new penalty coefficient.' ;
+warn4= 'Iterations limit exceeded.';
+warn31='The function is flat in certain directions.';
+warn32='Trying to recover by shifting insensitive variables.';
+warn09='Re-run from recorded point.';
+warn08='Ravine with a flat bottom is detected.';
+termwarn0='SolvOpt: Normal termination.';
+termwarn1='SolvOpt: Termination warning:';
+appwarn='The above warning may be reasoned by inaccurate gradient approximation';
+endwarn=[...
+    'Premature stop is possible. Try to re-run the routine from the obtained point.               ';...
+    'Result may not provide the optimum. The function apparently has many extremum points.        ';...
+    'Result may be inaccurate in the coordinates. The function is flat at the optimum.            ';...
+    'Result may be inaccurate in a function value. The function is extremely steep at the optimum.'];
+% ----}
+
+% ARGUMENTS PASSED ----{
+if nargin<2           % Function and/or starting point are not specified
+    exitflag=-1;
+    disp(errmes);
+    disp(error1);
+    return
+end
+if nargin<3
+    app=1;             % No user-supplied gradients
+elseif isempty(grad)
+    app=1;
+else
+    app=0;                     % Exact gradients are supplied
+end
+
+% OPTIONS ----{
+doptions.minimizer_indicator=1;
+doptions.TolX=1e-6; %accuracy of argument
+doptions.TolFun=1e-6; %accuracy of function (see Solvopt p.29)
+doptions.MaxIter=15000;
+doptions.verbosity=1;
+doptions.TolXConstraint=1.e-8;
+doptions.SpaceDilation=2.5;
+doptions.LBGradientStep=1.e-11;
+
+if nargin<4
+    optim=doptions;
+elseif isempty(optim)
+    optim=doptions;
+end
+% Check the values:
+optim.TolX=max(optim.TolX,1.e-12);
+optim.TolFun=max(optim.TolFun,1.e-12);
+optim.TolX=max(optim.LBGradientStep*1.e2,optim.TolX);
+optim.TolX=min(optim.TolX,1);
+optim.TolFun=min(optim.TolFun,1);
+optim.TolXConstraint=max(optim.TolXConstraint,1e-12);
+optim.SpaceDilation=max([optim.SpaceDilation,1.5]);
+optim.LBGradientStep=max(optim.LBGradientStep,1e-11);
+% ----}
+
+if isempty(func)
+    constr=0;
+else
+    constr=1;                  % Constrained problem
+    if isempty(gradc),
+        appconstr=1;
+    else
+        appconstr=0;            % Exact gradients of constraints are supplied
+    end
+end
+% ----}
+
+% STARTING POINT ----{
+if max(size(x))<=1
+    disp(errmes);
+    disp(error2);
+    exitflag=-2;
+    return
+elseif size(x,2)==1
+    n=size(x,1);
+    x=x';
+    trx=1;
+elseif size(x,1)==1
+    n=size(x,2);
+    trx=0;
+else
+    disp(errmes);
+    disp(error2);
+    exitflag=-2;
+    return
+end
+% ----}
+
+% WORKING CONSTANTS AND COUNTERS ----{
+
+n_f_evals=0; n_grad_evals=0;      % function and gradient calculations
+if constr
+    n_constraint_evals=0;
+    n_constraint_gradient_evals=0;      % same for constraints
+end
+epsnorm=1.e-15;
+epsnorm2=1.e-30;    % epsilon & epsilon^2
+
+if constr, h1=-1;                  % NLP: restricted to minimization
+    cnteps=optim.TolXConstraint;                % Max. admissible residual
+else
+    h1=sign(optim.minimizer_indicator);         % Minimize resp. maximize a function
+end
+
+k=0;                               % Iteration counter
+
+wdef=1/optim.SpaceDilation-1;               % Default space transf. coeff.
+
+%Gamma control ---{
+ajb=1+.1/n^2;                    % Base I
+ajp=20;
+ajpp=ajp;                        % Start value for the power
+ajs=1.15;                        % Base II
+knorms=0; gnorms=zeros(1,10);    % Gradient norms stored
+%---}
+
+%Display control ---{
+if optim.verbosity<=0, dispdata=0;
+    if optim.verbosity==-1
+        dispwarn=0;
+    else
+        dispwarn=1;
+    end
+else
+    dispdata=round(optim.verbosity);
+    dispwarn=1;
+end
+ld=dispdata;
+%---}
+
+%Stepsize control ---{
+dq=5.1;                          % Step divider (at f_{i+1}>gamma*f_{i})
+du20=2;du10=1.5;du03=1.05;       % Step multipliers (at certain steps made)
+kstore=3;nsteps=zeros(1,kstore); % Steps made at the last 'kstore' iterations
+if app
+    des=6.3;                 % Desired number of steps per 1-D search
+else
+    des=3.3;
+end
+mxtc=3;                          % Number of trial cycles (steep wall detect)
+%---}
+termx=0; limxterm=50;              % Counter and limit for x-criterion
+
+ddx   =max(1e-11,optim.LBGradientStep);      % stepsize for gradient approximation
+
+low_bound=-1+1e-4;                 % Lower bound cosine used to detect a ravine
+
+ZeroGrad=n*1.e-16;                 % Lower bound for a gradient norm
+
+nzero=0;                           % Zero-gradient events counter
+% Lower bound for values of variables taking into account
+lowxbound=max([optim.TolX,1e-3]);
+% Lower bound for function values to be considered as making difference
+lowfbound=optim.TolFun^2;
+krerun=0;                          % Re-run events counter
+detfr=optim.TolFun*100;              % relative error for f/f_{record}
+detxr=optim.TolX*10;               % relative error for norm(x)/norm(x_{record})
+
+warnno=0;                          % the number of warn.mess. to end with
+
+kflat=0;                           % counter for points of flatness
+stepvanish=0;                      % counter for vanished steps
+stopf=0;
+% ----}  End of setting constants
+% ----}  End of the preamble
+
+% COMPUTE THE FUNCTION  ( FIRST TIME ) ----{
+if trx
+    f=feval(fun,x',varargin{:});
+else
+    f=feval(fun,x,varargin{:});
+end
+n_f_evals=n_f_evals+1;
+if isempty(f),      if dispwarn,disp(errmes);disp(error30);end
+    exitflag=-3; if trx, x=x';end, return
+elseif isnan(f),    if dispwarn,disp(errmes);disp(error31);disp(error6);end
+    exitflag=-3; if trx, x=x';end, return
+elseif abs(f)==Inf, if dispwarn,disp(errmes);disp(error32);disp(error6);end
+    exitflag=-3; if trx, x=x';end, return
+end
+xrec=x; frec=f;     % record point and function value
+% Constrained problem
+if constr,  fp=f; kless=0;
+    if trx,
+        fc=feval(func,x');
+    else
+        fc=feval(func,x);
+    end
+    if isempty(fc),
+        if dispwarn,disp(errmes);disp(error50);end
+        exitflag=-5; if trx, x=x';end, return
+    elseif isnan(fc),
+        if dispwarn,disp(errmes);disp(error51);disp(error6);end
+        exitflag=-5; if trx, x=x';end, return
+    elseif abs(fc)==Inf,
+        if dispwarn,disp(errmes);disp(error52);disp(error6);end
+        exitflag=-5; if trx, x=x';end, return
+    end
+    n_constraint_evals=n_constraint_evals+1;
+    PenCoef=1;                              % first rough approximation
+    if fc<=cnteps
+        FP=1; fc=0;             % feasible point
+    else
+        FP=0;                   % infeasible point
+    end
+    f=f+PenCoef*fc;
+end
+% ----}
+% COMPUTE THE GRADIENT ( FIRST TIME ) ----{
+if app
+    deltax=h1*ddx*ones(size(x));
+    if constr
+        if trx
+            g=apprgrdn(x',fp,fun,deltax',1,varargin{:});
+        else
+            g=apprgrdn(x ,fp,fun,deltax,1,varargin{:}); 
+        end
+    else
+        if trx
+            g=apprgrdn(x',f,fun,deltax',1,varargin{:});
+        else
+            g=apprgrdn(x ,f,fun,deltax,1,varargin{:}); 
+        end
+    end
+    n_f_evals=n_f_evals+n;
+else
+    if trx
+        g=feval(grad,x',varargin{:});
+    else
+        g=feval(grad,x,varargin{:});   
+    end
+    n_grad_evals=n_grad_evals+1;
+end
+if size(g,2)==1, g=g'; end, ng=norm(g);
+if size(g,2)~=n,    if dispwarn,disp(errmes);disp(error40);end
+    exitflag=-4; if trx, x=x';end, return
+elseif isnan(ng),   if dispwarn,disp(errmes);disp(error41);disp(error6);end
+    exitflag=-4; if trx, x=x';end, return
+elseif ng==Inf,     if dispwarn,disp(errmes);disp(error42);disp(error6);end
+    exitflag=-4; if trx, x=x';end, return
+elseif ng<ZeroGrad, if dispwarn,disp(errmes);disp(error43);disp(error6);end
+    exitflag=-4; if trx, x=x';end, return
+end
+if constr
+    if ~FP
+        if appconstr,
+            deltax=sign(x); idx=find(deltax==0);
+            deltax(idx)=ones(size(idx));  
+            deltax=ddx*deltax;
+            if trx
+                gc=apprgrdn(x',fc,func,deltax',0);
+            else
+                gc=apprgrdn(x ,fc,func,deltax ,0); 
+            end
+            n_constraint_evals=n_constraint_evals+n;
+        else
+            if trx
+                gc=feval(gradc,x');
+            else
+                gc=feval(gradc,x); 
+            end
+            n_constraint_gradient_evals=n_constraint_gradient_evals+1;
+        end
+        if size(gc,2)==1
+            gc=gc'; 
+        end
+        ngc=norm(gc);
+        if size(gc,2)~=n,
+            if dispwarn
+                disp(errmes);
+                disp(error60);
+            end
+            exitflag=-6; 
+            if trx
+                x=x';
+            end
+            return
+        elseif isnan(ngc),
+            if dispwarn
+                disp(errmes);
+                disp(error61);
+                disp(error6);
+            end
+            exitflag=-6; 
+            if trx
+                x=x';
+            end
+            return
+        elseif ngc==Inf,
+            if dispwarn
+                disp(errmes);
+                disp(error62);
+                disp(error6);
+            end
+            exitflag=-6; 
+            if trx
+                x=x';
+            end
+            return
+        elseif ngc<ZeroGrad,
+            if dispwarn
+                disp(errmes);
+                disp(error63);
+            end
+            exitflag=-6; 
+            if trx
+                x=x';
+            end
+            return
+        end
+        g=g+PenCoef*gc; ng=norm(g);
+    end, end
+grec=g; nng=ng;
+% ----}
+% INITIAL STEPSIZE
+h=h1*sqrt(optim.TolX)*max(abs(x));     % smallest possible stepsize
+if abs(optim.minimizer_indicator)~=1,
+    h=h1*max(abs([optim.minimizer_indicator,h]));     % user-supplied stepsize
+else
+    h=h1*max(1/log(ng+1.1),abs(h));    % calculated stepsize
+end
+
+% RESETTING LOOP ----{
+while 1,
+    kcheck=0;                        % Set checkpoint counter.
+    kg=0;                            % stepsizes stored
+    kj=0;                            % ravine jump counter
+    B=eye(n);                        % re-set transf. matrix to identity
+    fst=f; g1=g;  dx=0;
+    % ----}
+    
+    % MAIN ITERATIONS ----{
+    
+    while 1,
+        k=k+1;kcheck=kcheck+1;
+        laststep=dx;
+        
+        % ADJUST GAMMA --{
+        gamma=1+max([ajb^((ajp-kcheck)*n),2*optim.TolFun]);
+        gamma=min([gamma,ajs^max([1,log10(nng+1)])]);
+        % --}
+        gt=g*B;   w=wdef;
+        % JUMPING OVER A RAVINE ----{
+        if (gt/norm(gt))*(g1'/norm(g1))<low_bound
+            if kj==2, xx=x;  end,  if kj==0, kd=4;  end,
+            kj=kj+1;  w=-.9; h=h*2;             % use large coef. of space dilation
+            if kj>2*kd,     kd=kd+1;  warnno=1;
+                if any(abs(x-xx)<epsnorm*abs(x)), % flat bottom is detected
+                    if dispwarn,disp(wrnmes);disp(warn08); end
+                end
+            end
+        else
+            kj=0;
+        end
+        % ----}
+        % DILATION ----{
+        z=gt-g1;
+        nrmz=norm(z);
+        if(nrmz>epsnorm*norm(gt))
+            z=z/nrmz;
+            g1=gt+w*(z*gt')*z;  B=B+w*(B*z')*z;
+        else
+            z=zeros(1,n); 
+            nrmz=0; 
+            g1=gt;
+        end
+        d1=norm(g1);  g0=(g1/d1)*B';
+        % ----}
+        % RESETTING ----{
+        if kcheck>1
+            idx=find(abs(g)>ZeroGrad); numelem=size(idx,2);
+            if numelem>0, grbnd=epsnorm*numelem^2;
+                if all(abs(g1(idx))<=abs(g(idx))*grbnd) | nrmz==0
+                    if dispwarn,  disp(wrnmes);  disp(warn20); end
+                    if abs(fst-f)<abs(f)*.01
+                        ajp=ajp-10*n;
+                    else
+                        ajp=ajpp; 
+                    end
+                    h=h1*dx/3; 
+                    k=k-1;
+                    break
+                end
+            end
+        end
+        % ----}
+        % STORE THE CURRENT VALUES AND SET THE COUNTERS FOR 1-D SEARCH
+        xopt=x;fopt=f;   k1=0;k2=0;ksm=0;kc=0;knan=0;  hp=h;
+        if constr, Reset=0; end
+        % 1-D SEARCH ----{
+        while 1,
+            x1=x;f1=f;
+            if constr, FP1=FP; fp1=fp; end
+            x=x+hp*g0;
+            % FUNCTION VALUE
+            if trx
+                f=feval(fun,x',varargin{:});
+            else
+                f=feval(fun,x,varargin{:});  
+            end
+            n_f_evals=n_f_evals+1;
+            if h1*f==Inf
+                if dispwarn
+                    disp(errmes); 
+                    disp(error5); 
+                end
+                exitflag=-7; 
+                if trx
+                    x=x';
+                end
+                return
+            end
+            if constr, fp=f;
+                if trx
+                    fc=feval(func,x');
+                else
+                    fc=feval(func,x);
+                end
+                n_constraint_evals=n_constraint_evals+1;
+                if  isnan(fc),
+                    if dispwarn,disp(errmes);disp(error51);disp(error6);end
+                    exitflag=-5; if trx, x=x';end, return
+                elseif abs(fc)==Inf,
+                    if dispwarn,disp(errmes);disp(error52);disp(error6);end
+                    exitflag=-5; if trx, x=x';end, return
+                end
+                if fc<=cnteps
+                    FP=1; 
+                    fc=0;
+                else
+                    FP=0;
+                    fp_rate=(fp-fp1);
+                    if fp_rate<-epsnorm
+                        if ~FP1
+                            PenCoefNew=-15*fp_rate/norm(x-x1);
+                            if PenCoefNew>1.2*PenCoef,
+                                PenCoef=PenCoefNew; Reset=1; kless=0; f=f+PenCoef*fc; break
+                            end
+                        end
+                    end
+                end
+                f=f+PenCoef*fc;
+            end
+            if abs(f)==Inf || isnan(f)
+                if dispwarn, disp(wrnmes);
+                    if isnan(f)
+                        disp(error31); 
+                    else
+                        disp(error32); 
+                    end
+                end
+                if ksm || kc>=mxtc
+                    exitflag=-3; 
+                    if trx
+                        x=x';
+                    end
+                    return
+                else
+                    k2=k2+1;
+                    k1=0; 
+                    hp=hp/dq; 
+                    x=x1;
+                    f=f1; 
+                    knan=1;
+                    if constr
+                        FP=FP1; 
+                        fp=fp1; 
+                    end
+                end
+                % STEP SIZE IS ZERO TO THE EXTENT OF EPSNORM
+            elseif all(abs(x-x1)<abs(x)*epsnorm),
+                stepvanish=stepvanish+1;
+                if stepvanish>=5,
+                    exitflag=-14;
+                    if dispwarn, disp(termwarn1);
+                        disp(endwarn(4,:)); end
+                    if trx,x=x';end,  return
+                else
+                    x=x1; 
+                    f=f1; 
+                    hp=hp*10; 
+                    ksm=1;
+                    if constr
+                        FP=FP1; 
+                        fp=fp1; 
+                    end
+                end
+                % USE SMALLER STEP
+            elseif h1*f<h1*gamma^sign(f1)*f1
+                if ksm,break,end,  k2=k2+1;k1=0; hp=hp/dq; x=x1;f=f1;
+                if constr, FP=FP1; fp=fp1; end
+                if kc>=mxtc, break, end
+                % 1-D OPTIMIZER IS LEFT BEHIND
+            else   if h1*f<=h1*f1, break,  end
+                % USE LARGER STEP
+                k1=k1+1; if k2>0, kc=kc+1; end, k2=0;
+                if k1>=20,      hp=du20*hp;
+                elseif k1>=10,  hp=du10*hp;
+                elseif k1>=3,   hp=du03*hp;
+                end
+            end
+        end
+        % ----}  End of 1-D search
+        % ADJUST THE TRIAL STEP SIZE ----{
+        dx=norm(xopt-x);
+        if kg<kstore,  kg=kg+1;  end
+        if kg>=2,  nsteps(2:kg)=nsteps(1:kg-1); end
+        nsteps(1)=dx/(abs(h)*norm(g0));
+        kk=sum(nsteps(1:kg).*[kg:-1:1])/sum([kg:-1:1]);
+        if     kk>des
+            if kg==1
+                h=h*(kk-des+1);
+            else
+                h=h*sqrt(kk-des+1); 
+            end
+        elseif kk<des
+            h=h*sqrt(kk/des);
+        end
+        
+        stepvanish=stepvanish+ksm;
+        % ----}
+        % COMPUTE THE GRADIENT ----{
+        if app,
+            deltax=sign(g0); idx=find(deltax==0);
+            deltax(idx)=ones(size(idx));  deltax=h1*ddx*deltax;
+            if constr
+                if trx
+                    g=apprgrdn(x',fp,fun,deltax',1,varargin{:});
+                else
+                    g=apprgrdn(x ,fp,fun,deltax,1,varargin{:});    
+                end
+            else
+                if trx
+                    g=apprgrdn(x',f,fun,deltax',1,varargin{:});
+                else
+                    g=apprgrdn(x ,f,fun,deltax ,1,varargin{:});    
+                end
+            end
+            n_f_evals=n_f_evals+n;
+        else
+            if trx
+                g=feval(grad,x',varargin{:});
+            else
+                g=feval(grad,x,varargin{:}); 
+            end
+            n_grad_evals=n_grad_evals+1;
+        end
+        if size(g,2)==1, g=g'; end,    ng=norm(g);
+        if isnan(ng),
+            if dispwarn, disp(errmes); disp(error41); end
+            exitflag=-4; if trx, x=x'; end, return
+        elseif ng==Inf,
+            if dispwarn,disp(errmes);disp(error42);end
+            exitflag=-4; if trx, x=x';end, return
+        elseif ng<ZeroGrad,
+            if dispwarn,disp(wrnmes);disp(warn1);end
+            ng=ZeroGrad;
+        end
+        % Constraints:
+        if constr
+            if ~FP
+                if ng<.01*PenCoef
+                    kless=kless+1;
+                    if kless>=20, PenCoef=PenCoef/10; Reset=1; kless=0; end
+                else
+                    kless=0;
+                end
+                if appconstr,
+                    deltax=sign(x); idx=find(deltax==0);
+                    deltax(idx)=ones(size(idx));  deltax=ddx*deltax;
+                    if trx
+                        gc=apprgrdn(x',fc,func,deltax',0);
+                    else
+                        gc=apprgrdn(x ,fc,func,deltax ,0); 
+                    end
+                    n_constraint_evals=n_constraint_evals+n;
+                else
+                    if trx
+                        gc=feval(gradc,x');
+                    else
+                        gc=feval(gradc,x ); 
+                    end
+                    n_constraint_gradient_evals=n_constraint_gradient_evals+1;
+                end
+                if size(gc,2)==1, gc=gc'; end, ngc=norm(gc);
+                if     isnan(ngc),
+                    if dispwarn,disp(errmes);disp(error61);end
+                    exitflag=-6; if trx, x=x';end, return
+                elseif ngc==Inf,
+                    if dispwarn,disp(errmes);disp(error62);end
+                    exitflag=-6; if trx, x=x';end, return
+                elseif ngc<ZeroGrad && ~appconstr,
+                    if dispwarn,disp(errmes);disp(error63);end
+                    exitflag=-6; if trx, x=x';end, return
+                end
+                g=g+PenCoef*gc; ng=norm(g);
+                if Reset, if dispwarn,  disp(wrnmes);  disp(warn21); end
+                    h=h1*dx/3; k=k-1; nng=ng; break
+                end
+            end, end
+        if h1*f>h1*frec, frec=f; xrec=x; grec=g; end
+        % ----}
+        if ng>ZeroGrad,
+            if knorms<10,  knorms=knorms+1;  end
+            if knorms>=2,  gnorms(2:knorms)=gnorms(1:knorms-1); end
+            gnorms(1)=ng;
+            nng=(prod(gnorms(1:knorms)))^(1/knorms);
+        end
+        
+        % DISPLAY THE CURRENT VALUES ----{
+        if k==ld
+            disp('Iter.# ..... Function ... Step Value ... Gradient Norm ');
+            disp(sprintf('%5i   %13.5e   %13.5e     %13.5e',k,f,dx,ng));
+            ld=k+dispdata;
+        end
+        %----}
+        % CHECK THE STOPPING CRITERIA ----{
+        termflag=1;
+        if constr, if ~FP, termflag=0; end, end
+        if kcheck<=5, termflag=0; end
+        if knan, termflag=0; end
+        if kc>=mxtc, termflag=0; end
+        % ARGUMENT
+        if termflag
+            idx=find(abs(x)>=lowxbound);
+            if isempty(idx) || all(abs(xopt(idx)-x(idx))<=optim.TolX*abs(x(idx)))
+                termx=termx+1;
+                % FUNCTION
+                if abs(f-frec)> detfr * abs(f)    && ...
+                        abs(f-fopt)<=optim.TolFun*abs(f) && ...
+                        krerun<=3                      && ...
+                        ~constr
+                    if any(abs(xrec(idx)-x(idx))> detxr * abs(x(idx)))
+                        if dispwarn
+                            disp(wrnmes);
+                            disp(warn09);
+                        end
+                        x=xrec; 
+                        f=frec; 
+                        g=grec; 
+                        ng=norm(g); 
+                        krerun=krerun+1;
+                        h=h1*max([dx,detxr*norm(x)])/krerun;
+                        warnno=2; 
+                        break
+                    else
+                        h=h*10;
+                    end
+                elseif  abs(f-frec)> optim.TolFun*abs(f)    && ...
+                        norm(x-xrec)<optim.TolX*norm(x) && constr
+                    
+                elseif  abs(f-fopt)<=optim.TolFun*abs(f)  || ...
+                        abs(f)<=lowfbound               || ...
+                        (abs(f-fopt)<=optim.TolFun && termx>=limxterm )
+                    if stopf
+                        if dx<=laststep
+                            if warnno==1 && ng<sqrt(optim.TolFun), warnno=0; end
+                            if ~app, if any(abs(g)<=epsnorm2), warnno=3; end, end
+                            if warnno~=0
+                                exitflag=-warnno-10;
+                                if dispwarn, disp(termwarn1);
+                                    disp(endwarn(warnno,:));
+                                    if app, disp(appwarn); end
+                                end
+                            else
+                                exitflag=k;
+                                if dispwarn
+                                    disp(termwarn0); 
+                                end
+                            end
+                            if trx
+                                x=x';
+                            end
+                            return
+                        end
+                    else
+                        stopf=1;
+                    end
+                elseif dx<1.e-12*max(norm(x),1) && termx>=limxterm
+                    exitflag=-14;
+                    if dispwarn, disp(termwarn1); disp(endwarn(4,:));
+                        if app, disp(appwarn); end
+                    end
+                    x=xrec; f=frec;
+                    if trx,x=x';end,  return
+                else
+                    stopf=0;
+                end
+            end
+        end
+        % ITERATIONS LIMIT
+        if(k==optim.MaxIter)
+            exitflag=-9; 
+            if trx
+                x=x'; 
+            end,
+            if dispwarn, disp(wrnmes);  disp(warn4); end
+            return
+        end
+        % ----}
+        % ZERO GRADIENT ----{
+        if constr
+            if ng<=ZeroGrad,
+                if dispwarn,  disp(termwarn1);  disp(warn1); end
+                exitflag=-8; 
+                if trx
+                    x=x';
+                end
+                return
+            end
+        else
+            if ng<=ZeroGrad,        nzero=nzero+1;
+                if dispwarn, disp(wrnmes);  disp(warn1);  end
+                if nzero>=3
+                    exitflag=-8; 
+                    if trx
+                        x=x';
+                    end
+                    return
+                end
+                g0=-h*g0/2;
+                for i=1:10,
+                    x=x+g0;
+                    if trx
+                        f=feval(fun,x',varargin{:});
+                    else
+                        f=feval(fun,x,varargin{:}); 
+                    end
+                    n_f_evals=n_f_evals+1;
+                    if abs(f)==Inf
+                        if dispwarn
+                            disp(errmes);  
+                            disp(error32);  
+                        end
+                        exitflag=-3;
+                        if trx
+                            x=x';
+                        end
+                        return
+                    elseif isnan(f),
+                        if dispwarn
+                            disp(errmes);  
+                            disp(error32);  
+                        end
+                        exitflag=-3;
+                        if trx
+                            x=x';
+                        end
+                        return
+                    end
+                    if app,
+                        deltax=sign(g0); 
+                        idx=find(deltax==0);
+                        deltax(idx)=ones(size(idx));  
+                        deltax=h1*ddx*deltax;
+                        if trx  
+                            g=apprgrdn(x',f,fun,deltax',1,varargin{:});
+                        else
+                            g=apprgrdn(x,f,fun,deltax,1,varargin{:});
+                        end
+                        n_f_evals=n_f_evals+n;
+                    else
+                        if trx  
+                            g=feval(grad,x',varargin{:});
+                        else
+                            g=feval(grad,x,varargin{:});   
+                        end
+                        n_grad_evals=n_grad_evals+1;
+                    end
+                    if size(g,2)==1
+                        g=g'; 
+                    end
+                    ng=norm(g);
+                    if ng==Inf
+                        if dispwarn
+                            disp(errmes);  
+                            disp(error42); 
+                        end
+                        exitflag=-4; 
+                        if trx
+                            x=x'; 
+                        end
+                        return
+                    elseif isnan(ng)
+                        if dispwarn
+                            disp(errmes);  
+                            disp(error41); 
+                        end
+                        exitflag=-4; 
+                        if trx
+                            x=x'; 
+                        end
+                        return
+                    end
+                    if ng>ZeroGrad
+                        break
+                    end
+                end
+                if ng<=ZeroGrad,
+                    if dispwarn
+                        disp(termwarn1);  
+                        disp(warn1); 
+                    end
+                    exitflag=-8; 
+                    if trx
+                        x=x';
+                    end
+                    return
+                end
+                h=h1*dx; 
+                break
+            end
+        end
+        % ----}
+        % FUNCTION IS FLAT AT THE POINT ----{
+        if ~constr && abs(f-fopt)<abs(fopt)*optim.TolFun && kcheck>5 && ng<1
+            idx=find(abs(g)<=epsnorm2); 
+            ni=size(idx,2);
+            if ni>=1 && ni<=n/2 && kflat<=3, kflat=kflat+1;
+                if dispwarn,  disp(wrnmes); disp(warn31); end, warnno=1;
+                x1=x; fm=f;
+                for j=idx, y=x(j); f2=fm;
+                    if y==0, x1(j)=1; elseif abs(y)<1, x1(j)=sign(y); else, x1(j)=y; end
+                    for i=1:20, x1(j)=x1(j)/1.15;
+                        if trx
+                            f1=feval(fun,x1',varargin{:});
+                        else
+                            f1=feval(fun,x1,varargin{:}); 
+                        end
+                        n_f_evals=n_f_evals+1;
+                        if abs(f1)~=Inf && ~isnan(f1),
+                            if h1*f1>h1*fm
+                                y=x1(j); 
+                                fm=f1;
+                            elseif h1*f2>h1*f1
+                                break
+                            elseif f2==f1
+                                x1(j)=x1(j)/1.5;
+                            end
+                            f2=f1;
+                        end
+                    end
+                    x1(j)=y;
+                end
+                if h1*fm>h1*f
+                    if app,
+                        deltax=h1*ddx*ones(size(deltax));
+                        if trx
+                            gt=apprgrdn(x1',fm,fun,deltax',1,varargin{:});
+                        else
+                            gt=apprgrdn(x1 ,fm,fun,deltax ,1,varargin{:});    
+                        end
+                        n_f_evals=n_f_evals+n;
+                    else
+                        if trx
+                            gt=feval(grad,x1',varargin{:});
+                        else
+                            gt=feval(grad,x1,varargin{:}); 
+                        end
+                        n_grad_evals=n_grad_evals+1;
+                    end
+                    if size(gt,2)==1
+                        gt=gt'; 
+                    end
+                    ngt=norm(gt);
+                    if ~isnan(ngt) && ngt>epsnorm2,
+                        if dispwarn
+                            disp(warn32); 
+                        end
+                        optim.TolFun=optim.TolFun/5;
+                        x=x1; 
+                        g=gt; 
+                        ng=ngt; 
+                        f=fm; 
+                        h=h1*dx/3; 
+                        break
+                    end
+                end
+            end
+        end
+        % ----}
+    end % iterations
+end % restart
+% end of the function
+%
+end
\ No newline at end of file
diff --git a/matlab/optimize_prior.m b/matlab/optimize_prior.m
new file mode 100644
index 0000000000000000000000000000000000000000..d5b5e0ac121a8a66011c7a4c2293160dd5981ab3
--- /dev/null
+++ b/matlab/optimize_prior.m
@@ -0,0 +1,74 @@
+function optimize_prior(DynareOptions, ModelInfo, DynareResults, BayesInfo, EstimationInfo)
+
+% This routine computes the mode of the prior density using an optimization algorithm.
+
+% Copyright (C) 2015 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+% Initialize to the prior mean
+DynareResults.dr = set_state_space(DynareResults.dr,ModelInfo,DynareOptions);
+xparam1 = BayesInfo.p1;
+
+% Pertubation of the initial condition.
+look_for_admissible_initial_condition = 1; scale = 1.0; iter  = 0;
+while look_for_admissible_initial_condition
+    xinit = xparam1+scale*randn(size(xparam1));
+    if all(xinit(:)>BayesInfo.p3) && all(xinit(:)<BayesInfo.p4)
+        ModelInfo = set_all_parameters(xinit,EstimationInfo,ModelInfo);
+        [dr,INFO,ModelInfo,DynareOptions,DynareResults] = resol(0,ModelInfo,DynareOptions,DynareResults);
+        if ~INFO(1)
+            look_for_admissible_initial_condition = 0;
+        end
+    else
+        if iter == 2000;
+            scale = scale/1.1;
+            iter  = 0;
+        else
+            iter = iter+1;
+        end
+    end
+end
+
+% Evaluate the prior density at the initial condition.
+objective_function_penalty_base = minus_logged_prior_density(xinit, BayesInfo.pshape, ...
+                               BayesInfo.p6, ...
+                               BayesInfo.p7, ...
+                               BayesInfo.p3, ...
+                               BayesInfo.p4,DynareOptions,ModelInfo,EstimationInfo,DynareResults);
+
+% Maximization of the prior density
+[xparams, lpd, hessian_mat] = ...
+    maximize_prior_density(xinit, BayesInfo.pshape, ...
+                           BayesInfo.p6, ...
+                           BayesInfo.p7, ...
+                           BayesInfo.p3, ...
+                           BayesInfo.p4,DynareOptions,ModelInfo,BayesInfo,EstimationInfo,DynareResults);
+
+% Display the results.
+skipline(2)
+disp('------------------')
+disp('PRIOR OPTIMIZATION')
+disp('------------------')
+skipline()
+for i = 1:length(xparams)
+    disp(['deep parameter ' int2str(i) ': ' get_the_name(i,0,ModelInfo,EstimationInfo,DynareOptions) '.'])
+    disp(['  Initial condition ....... ' num2str(xinit(i)) '.'])
+    disp(['  Prior mode .............. ' num2str(BayesInfo.p5(i)) '.'])
+    disp(['  Optimized prior mode .... ' num2str(xparams(i)) '.'])
+    skipline()
+end
+skipline()
\ No newline at end of file
diff --git a/matlab/osr1.m b/matlab/osr1.m
index eb23312ffe499556b3bcd583a7014db3e1a6a8a2..a96c618fb38fb24d7bf30ce52e02d3c1735b5227 100644
--- a/matlab/osr1.m
+++ b/matlab/osr1.m
@@ -73,9 +73,6 @@ t0 = M_.params(i_params);
 
 inv_order_var = oo_.dr.inv_order_var;
 
-H0 = 1e-4*eye(np);
-crit=options_.osr.tolf;
-nit=options_.osr.maxit;
 
 %extract unique entries of covariance
 i_var=unique(i_var);
@@ -93,20 +90,25 @@ if isinf(loss)
    error('OSR: Initial likelihood is infinite')
 end
 
+
+if isequal(options_.osr.opt_algo,5)
+    error('OSR: OSR does not support opt_algo=5.')
+elseif isequal(options_.osr.opt_algo,6)
+    error('OSR: OSR does not support opt_algo=6.')
+elseif isequal(options_.osr.opt_algo,10)
+    error('OSR: OSR does not support opt_algo=10.')    
+else
 %%do actual optimization
-[f,p]=csminwel1('osr_obj',t0,H0,[],crit,nit,options_.gradient_method,options_.gradient_epsilon,i_params,...
+[p, f, exitflag] = dynare_minimize_objective(str2func('osr_obj'),t0,options_.osr.opt_algo,options_,[],cellstr(M_.param_names(i_params,:)),[],[], i_params,...
                 inv_order_var(i_var),weights(i_var,i_var));
+end
+
 osr_res.objective_function = f;
 M_.params(i_params)=p; %make sure optimal parameters are set (and not the last draw used in csminwel)
 for i=1:length(i_params)
     osr_res.optim_params.(deblank(M_.param_names(i_params(i),:))) = p(i);
 end
 
-%  options = optimset('fminunc');
-%  options = optimset('display','iter');
-%  [p,f]=fminunc(@osr_obj,t0,options,i_params,...
-%               inv_order_var(i_var),weights(i_var,i_var));
-
 skipline()
 disp('OPTIMAL VALUE OF THE PARAMETERS:')
 skipline()
diff --git a/matlab/parallel/masterParallel.m b/matlab/parallel/masterParallel.m
index 6b218310ec72116eb23ea91e2d125303bc981097..75728bb0f7746afce6ed955b674683505084cb7a 100644
--- a/matlab/parallel/masterParallel.m
+++ b/matlab/parallel/masterParallel.m
@@ -3,28 +3,38 @@ function [fOutVar,nBlockPerCPU, totCPU] = masterParallel(Parallel,fBlock,nBlock,
 % This is the most important function for the management of DYNARE parallel
 % computing.
 % It is the top-level function called on the master computer when parallelizing a task.
-
-% This function has two main computational strategies for managing the matlab worker (slave process).
+% 
+% This function has two main computational strategies for managing the
+% matlab worker (slave process):
+% 
 % 0 Simple Close/Open Stategy:
-% In this case the new Matlab instances (slave process) are open when
-% necessary and then closed. This can happen many times during the
-% simulation of a model.
-
+%   In this case the new Matlab instances (slave process) are open when
+%   necessary and then closed. This can happen many times during the
+%   simulation of a model.
+% 
 % 1 Always Open Strategy:
-% In this case we have a more sophisticated management of slave processes,
-% which are no longer closed at the end of each job. The slave processes
-% wait for a new job (if it exists). If a slave does not receive a new job after a
-% fixed time it is destroyed. This solution removes the computational
-% time necessary to Open/Close new Matlab instances.
-
+%   In this case we have a more sophisticated management of slave processes,
+%   which are no longer closed at the end of each job. The slave processes
+%   wait for a new job (if it exists). If a slave does not receive a new job after a
+%   fixed time it is destroyed. This solution removes the computational
+%   time necessary to Open/Close new Matlab instances.
+% 
 % The first (point 0) is the default Strategy
 % i.e.(Parallel_info.leaveSlaveOpen=0). This value can be changed by the
 % user in xxx.mod file or it is changed by the programmer if it is necessary to
 % reduce the overall computational time. See for example the
 % prior_posterior_statistics.m.
-
+% 
 % The number of parallelized threads will be equal to (nBlock-fBlock+1).
 %
+% Treatment of global variables:
+%   Global variables used within the called function (e.g.
+%   objective_function_penalty_base) are wrapped and passed by storing their 
+%   values at the start of the parallel computation in a file via
+%   storeGlobalVars.m. This file is then loaded in the separate,
+%   independent slave Matlab sessions. By keeping them separate, no
+%   interaction via global variables can take place. 
+% 
 % INPUTS
 %  o Parallel [struct vector]   copy of options_.parallel
 %  o fBlock [int]               index number of the first thread
@@ -53,7 +63,7 @@ function [fOutVar,nBlockPerCPU, totCPU] = masterParallel(Parallel,fBlock,nBlock,
 %                              the number of CPUs declared in "Parallel", if
 %                              the number of required threads is lower)
 
-% Copyright (C) 2009-2013 Dynare Team
+% Copyright (C) 2009-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -126,7 +136,7 @@ if isHybridMatlabOctave || isoctave
         end
     end
     
-    if exist('fGlobalVar') && ~isempty(fGlobalVar),
+    if exist('fGlobalVar','var') && ~isempty(fGlobalVar),
     fInputNames = fieldnames(fGlobalVar);
     for j=1:length(fInputNames),
         TargetVar = fGlobalVar.(fInputNames{j});
@@ -161,7 +171,7 @@ switch Strategy
         save([fname,'_input.mat'],'fInputVar','Parallel','-append')
         
     case 1
-        if exist('fGlobalVar'),
+        if exist('fGlobalVar','var'),
             save(['temp_input.mat'],'fInputVar','fGlobalVar')
         else
             save(['temp_input.mat'],'fInputVar')
@@ -540,7 +550,6 @@ else
         'Renderer','Painters', ...
         'Resize','off');
     
-    vspace = 0.1;
     ncol = ceil(totCPU/10);
     hspace = 0.9/ncol;
     hstatus(1) = axes('position',[0.05/ncol 0.92 0.9/ncol 0.03], ...
@@ -882,8 +891,4 @@ switch Strategy
                 end
             end
         end
-end
-
-
-
-
+end
\ No newline at end of file
diff --git a/matlab/partial_information/PCL_resol.m b/matlab/partial_information/PCL_resol.m
index 3787de03ba1bad984c86f24680a074730d1b5cdd..ba0b1666fefd3611995a07c304f5029bc14d4bef 100644
--- a/matlab/partial_information/PCL_resol.m
+++ b/matlab/partial_information/PCL_resol.m
@@ -89,7 +89,9 @@ else
             % nonlinear models
             if max(abs(feval(fh,dr.ys,[oo_.exo_steady_state; ...
                                     oo_.exo_det_steady_state], M_.params))) > options_.dynatol.f
-                [dr.ys,check1] = dynare_solve(fh,dr.ys,options_.jacobian_flag,...
+                opt = options_;
+                opt.jacobian_flag = 0;
+                [dr.ys,check1] = dynare_solve(fh,dr.ys,opt,...
                                               [oo_.exo_steady_state; ...
                                     oo_.exo_det_steady_state], M_.params);
             end
diff --git a/matlab/partial_information/dr1_PI.m b/matlab/partial_information/dr1_PI.m
index 996c02e9d36381675c16cdd8eb6a51aafe3fd4c1..0475d4befc4c44791fad2406755f315981f1bee7 100644
--- a/matlab/partial_information/dr1_PI.m
+++ b/matlab/partial_information/dr1_PI.m
@@ -87,7 +87,9 @@ if options_.ramsey_policy && options_.ACES_solver == 0
     end
     old_solve_algo = options_.solve_algo;
     %  options_.solve_algo = 1;
-    oo_.steady_state = dynare_solve('ramsey_static',oo_.steady_state,0,M_,options_,oo_,it_);
+    opt = options_;
+    opt.jacobian_flag = 0;
+    oo_.steady_state = dynare_solve('ramsey_static',oo_.steady_state,opt,M_,options_,oo_,it_);
     options_.solve_algo = old_solve_algo;
     [junk,junk,multbar] = ramsey_static(oo_.steady_state,M_,options_,oo_,it_);
     [jacobia_,M_] = ramsey_dynamic(oo_.steady_state,multbar,M_,options_,oo_,it_);
diff --git a/matlab/det_cond_forecast.m b/matlab/perfect-foresight-models/det_cond_forecast.m
similarity index 100%
rename from matlab/det_cond_forecast.m
rename to matlab/perfect-foresight-models/det_cond_forecast.m
diff --git a/matlab/make_ex_.m b/matlab/perfect-foresight-models/make_ex_.m
similarity index 100%
rename from matlab/make_ex_.m
rename to matlab/perfect-foresight-models/make_ex_.m
diff --git a/matlab/make_y_.m b/matlab/perfect-foresight-models/make_y_.m
similarity index 85%
rename from matlab/make_y_.m
rename to matlab/perfect-foresight-models/make_y_.m
index ae8928693a112d4cc1c2dfaf6a66b09a8235595d..788d6eb93ee9aff905acefb7735424fc214c9a5e 100644
--- a/matlab/make_y_.m
+++ b/matlab/perfect-foresight-models/make_y_.m
@@ -43,14 +43,14 @@ end
 
 if isempty(M_.endo_histval)
     if isempty(ys0_)
-        oo_.endo_simul = [oo_.steady_state*ones(1,M_.maximum_endo_lag+options_.periods+M_.maximum_endo_lead)];
+        oo_.endo_simul = [oo_.steady_state*ones(1,M_.maximum_lag+options_.periods+M_.maximum_lead)];
     else
-        oo_.endo_simul = [ys0_*ones(1,M_.maximum_endo_lag) oo_.steady_state*ones(1,options_.periods+M_.maximum_endo_lead)];
+        oo_.endo_simul = [ys0_*ones(1,M_.maximum_lag) oo_.steady_state*ones(1,options_.periods+M_.maximum_lead)];
     end
 else
     if ~isempty(ys0_)
         error('histval and endval cannot be used simultaneously')
     end
     oo_.endo_simul = [M_.endo_histval ...
-                      oo_.steady_state*ones(1,options_.periods+M_.maximum_endo_lead)];
+                      oo_.steady_state*ones(1,options_.periods+M_.maximum_lead)];
 end
diff --git a/matlab/perfect_foresight_problem.m b/matlab/perfect-foresight-models/perfect_foresight_problem.m
similarity index 100%
rename from matlab/perfect_foresight_problem.m
rename to matlab/perfect-foresight-models/perfect_foresight_problem.m
diff --git a/matlab/perfect_foresight_setup.m b/matlab/perfect-foresight-models/perfect_foresight_setup.m
similarity index 77%
rename from matlab/perfect_foresight_setup.m
rename to matlab/perfect-foresight-models/perfect_foresight_setup.m
index da03d46a68cf949e19f3ab7b3c32253d12ab5ae2..081eaf887e1694f61cd2449884df96df71743bbe 100644
--- a/matlab/perfect_foresight_setup.m
+++ b/matlab/perfect-foresight-models/perfect_foresight_setup.m
@@ -34,8 +34,16 @@ global M_ options_ oo_
 test_for_deep_parameters_calibration(M_);
 
 if size(M_.lead_lag_incidence,2)-nnz(M_.lead_lag_incidence(M_.maximum_endo_lag+1,:)) > 0
-    mess = ['PERFECT_FORESIGHT_SETUP: error in model specification : variable ' M_.endo_names(find(M_.lead_lag_incidence(M_.maximum_lag+1,:)==0),:)];
-    mess = [mess ' doesn''t appear as current variable.'];
+    mess = ['PERFECT_FORESIGHT_SETUP: error in model specification : the variable(s) '];
+        var_list=M_.endo_names(find(M_.lead_lag_incidence(M_.maximum_lag+1,:)==0),:);
+        for i=1:size(var_list,1)
+            if i<size(var_list,1)
+                mess = [mess, deblank(var_list(i,:)) ', '];
+            else
+                mess = [mess, deblank(var_list(i,:)) ];
+            end
+        end
+    mess = [mess ' don''t appear as current period variables.'];
     error(mess)
 end
 
diff --git a/matlab/perfect_foresight_simulation.m b/matlab/perfect-foresight-models/perfect_foresight_simulation.m
similarity index 100%
rename from matlab/perfect_foresight_simulation.m
rename to matlab/perfect-foresight-models/perfect_foresight_simulation.m
diff --git a/matlab/perfect-foresight-models/perfect_foresight_solver.m b/matlab/perfect-foresight-models/perfect_foresight_solver.m
new file mode 100644
index 0000000000000000000000000000000000000000..4c1ee15a0d7ed78474c87b4b33bdd17488dce2f7
--- /dev/null
+++ b/matlab/perfect-foresight-models/perfect_foresight_solver.m
@@ -0,0 +1,171 @@
+function perfect_foresight_solver()
+% Computes deterministic simulations
+%  
+% INPUTS
+%   None
+%  
+% OUTPUTS
+%   none
+%    
+% ALGORITHM
+%   
+% SPECIAL REQUIREMENTS
+%   none
+
+% Copyright (C) 1996-2015 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+global M_ options_ oo_
+
+check_input_arguments(options_, M_, oo_);
+
+if isempty(options_.scalv) || options_.scalv == 0
+    options_.scalv = oo_.steady_state;
+end
+
+options_.scalv= 1;
+
+if options_.debug
+    model_static = str2func([M_.fname,'_static']);
+    for ii=1:size(oo_.exo_simul,1)
+        [residual(:,ii)] = model_static(oo_.steady_state, oo_.exo_simul(ii,:),M_.params);
+    end
+    problematic_periods=find(any(isinf(residual)) | any(isnan(residual)))-M_.maximum_endo_lag;
+    if ~isempty(problematic_periods) 
+        period_string=num2str(problematic_periods(1));
+        for ii=2:length(problematic_periods)
+            period_string=[period_string, ', ', num2str(problematic_periods(ii))];
+        end
+        fprintf('\n\nWARNING: Value for the exogenous variable(s) in period(s) %s inconsistent with the static model.\n',period_string);   
+        fprintf('WARNING: Check for division by 0.\n')
+    end
+end
+
+initperiods = 1:M_.maximum_lag;
+lastperiods = (M_.maximum_endo_lag+options_.periods+1):(M_.maximum_endo_lag+options_.periods+M_.maximum_endo_lead);
+
+
+oo_ = simulation_core(options_, M_, oo_);
+
+% If simulation failed try homotopy.
+if ~oo_.deterministic_simulation.status && ~options_.no_homotopy
+    skipline()
+    disp('Simulation of the perfect foresight model failed!')
+    disp('Switching to a homotopy method...')
+    skipline()
+    
+    % Disable warnings if homotopy
+    warning_old_state = warning;
+    warning off all
+    % Do not print anything
+    oldverbositylevel = options_.verbosity;
+    options_.verbosity = 0;
+    
+    exosim = oo_.exo_simul;
+    exoinit = repmat(oo_.exo_steady_state',M_.maximum_lag+options_.periods+M_.maximum_lead,1);
+    
+    endosim = oo_.endo_simul;
+    endoinit = repmat(oo_.steady_state, 1,M_.maximum_lag+options_.periods+M_.maximum_lead);
+
+    current_weight = 0; % Current weight of target point in convex combination
+    step = .5;
+    success_counter = 0;
+    iteration = 0;
+
+    fprintf('Iter. \t | Lambda \t | status \t | Max. residual\n')
+    fprintf('++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n')
+    
+    while (step > options_.dynatol.x)
+
+        if ~isequal(step,1)
+            options_.verbosity = 0;
+        end
+
+        iteration = iteration+1;
+        new_weight = current_weight + step; % Try this weight, and see if it succeeds
+
+        if new_weight >= 1
+            new_weight = 1; % Don't go beyond target point
+            step = new_weight - current_weight;
+        end
+
+        % Compute convex combination for exo path and initial/terminal endo conditions
+        % But take care of not overwriting the computed part of oo_.endo_simul
+        oo_.exo_simul = exosim*new_weight + exoinit*(1-new_weight);
+        
+        oo_.endo_simul(:,[initperiods, lastperiods]) = ...
+            new_weight*oo_.endo_simul(:,[initperiods, lastperiods])+(1-new_weight)*endoinit(:,[initperiods, lastperiods]);
+        
+        path_with_nans = any(any(isnan(oo_.endo_simul)));
+        path_with_cplx = any(any(~isreal(oo_.endo_simul)));
+        
+        if isequal(iteration,1)
+            oo_.endo_simul(:,M_.maximum_lag+1:end-M_.maximum_lead) = endoinit(:,1:options_.periods);
+        elseif path_with_nans || path_with_cplx
+            oo_.endo_simul(:,M_.maximum_lag+1:end-M_.maximum_lead) = saved_endo_simul(:,1+M_.maximum_endo_lag:end-M_.maximum_endo_lead);
+        end
+        
+        saved_endo_simul = oo_.endo_simul;
+
+        [oo_, me] = simulation_core(options_, M_, oo_);
+
+        if oo_.deterministic_simulation.status == 1
+            current_weight = new_weight;
+            if current_weight >= 1
+                fprintf('%i \t | %1.5f \t | %s \t | %e\n', iteration, new_weight, 'succeeded', me)
+                break
+            end
+            success_counter = success_counter + 1;
+            if success_counter >= 3
+                success_counter = 0;
+                step = step * 2;
+            end
+            fprintf('%i \t | %1.5f \t | %s \t | %e\n', iteration, new_weight, 'succeeded', me)
+        else
+            oo_.endo_simul = saved_endo_simul;
+            success_counter = 0;
+            step = step / 2;
+            if isreal(me)
+                fprintf('%i \t | %1.5f \t | %s \t | %e\n', iteration, new_weight, 'failed', me)
+            else
+                fprintf('%i \t | %1.5f \t | %s \t | %s\n', iteration, new_weight, 'failed', 'Complex')
+            end
+        end
+    end
+    fprintf('++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n')
+    skipline()
+    options_.verbosity = oldverbositylevel;
+    warning(warning_old_state);
+end
+
+if oo_.deterministic_simulation.status == 1
+    disp('Perfect foresight solution found.')
+    skipline()
+else
+    warning('Failed to solve perfect foresight model')
+end
+
+dyn2vec;
+
+if ~isdates(options_.initial_period) && isnan(options_.initial_period)
+    initial_period = dates(1,1);
+else
+    initial_period = options_.initial_period;
+end
+
+ts = dseries(transpose(oo_.endo_simul),initial_period,cellstr(M_.endo_names));
+assignin('base', 'Simulated_time_series', ts);
diff --git a/matlab/perfect-foresight-models/private/check_input_arguments.m b/matlab/perfect-foresight-models/private/check_input_arguments.m
new file mode 100644
index 0000000000000000000000000000000000000000..affb808e081591bf1fc84b0e1a0026af030454b2
--- /dev/null
+++ b/matlab/perfect-foresight-models/private/check_input_arguments.m
@@ -0,0 +1,63 @@
+function check_input_arguments(DynareOptions, DynareModel, DynareResults)
+%function check_input_arguments(DynareOptions, DynareModel, DynareResults)
+%Conducts checks for inconsistent/missing inputs to deterministic
+%simulations
+
+% Copyright (C) 2015 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+if DynareOptions.stack_solve_algo < 0 || DynareOptions.stack_solve_algo > 7
+    error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: stack_solve_algo must be between 0 and 7')
+end
+
+if ~DynareOptions.block && ~DynareOptions.bytecode && DynareOptions.stack_solve_algo ~= 0 ...
+        && DynareOptions.stack_solve_algo ~= 6 && DynareOptions.stack_solve_algo ~= 7
+    error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: you must use stack_solve_algo=0 or stack_solve_algo=6 when not using block nor bytecode option')
+end
+
+if DynareOptions.block && ~DynareOptions.bytecode && DynareOptions.stack_solve_algo == 5
+    error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: you can''t use stack_solve_algo = 5 without bytecode option')
+end
+
+if (DynareOptions.block || DynareOptions.bytecode) && DynareOptions.stack_solve_algo == 6
+    error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: you can''t use stack_solve_algo = 6 with block or bytecode option')
+end
+
+if isoctave && DynareOptions.stack_solve_algo == 2
+    error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: you can''t use stack_solve_algo = 2 under Octave')
+end
+
+
+if isempty(DynareResults.endo_simul) || any(size(DynareResults.endo_simul) ~= [ DynareModel.endo_nbr, DynareModel.maximum_lag+DynareOptions.periods+DynareModel.maximum_lead ])
+    
+    if DynareOptions.initval_file
+        fprintf('PERFECT_FORESIGHT_SOLVER: ''oo_.endo_simul'' has wrong size. Check whether your initval-file provides %d periods.',DynareModel.maximum_endo_lag+DynareOptions.periods+DynareModel.maximum_endo_lead)
+        error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: ''oo_.endo_simul'' has wrong size. Did you run ''perfect_foresight_setup'' ?')
+    else
+        error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: ''oo_.endo_simul'' has wrong size. Did you run ''perfect_foresight_setup'' ?')
+    end
+end
+
+if (DynareModel.exo_nbr > 0) && ...
+        (isempty(DynareResults.exo_simul) || any(size(DynareResults.exo_simul) ~= [ DynareModel.maximum_lag+DynareOptions.periods+DynareModel.maximum_lead, DynareModel.exo_nbr ]))
+    if DynareOptions.initval_file
+        fprintf('PERFECT_FORESIGHT_SOLVER: ''oo_.exo_simul'' has wrong size. Check whether your initval-file provides %d periods.',DynareModel.maximum_endo_lag+DynareOptions.periods+DynareModel.maximum_endo_lead)
+        error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: ''oo_.exo_simul'' has wrong size.')
+    else
+        error('perfect_foresight_solver:ArgCheck','PERFECT_FORESIGHT_SOLVER: ''oo_.exo_simul'' has wrong size. Did you run ''perfect_foresight_setup'' ?')
+    end
+end
diff --git a/matlab/perfect-foresight-models/private/simulation_core.m b/matlab/perfect-foresight-models/private/simulation_core.m
new file mode 100644
index 0000000000000000000000000000000000000000..81674e4a2a7df01df1bf63b8d8f1427ee13e9401
--- /dev/null
+++ b/matlab/perfect-foresight-models/private/simulation_core.m
@@ -0,0 +1,131 @@
+function [oo_, maxerror] = simulation_core(options_, M_, oo_)
+%function [oo_, maxerror] = simulation_core(options_, M_, oo_)
+
+% Copyright (C) 2015 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+if options_.block
+    if options_.bytecode
+        try
+            [info, tmp] = bytecode('dynamic', oo_.endo_simul, oo_.exo_simul, M_.params, repmat(oo_.steady_state,1,options_.periods+2), options_.periods);
+        catch
+            info = 0;
+        end
+        if info
+            oo_.deterministic_simulation.status = false;
+        else
+            oo_.endo_simul = tmp;
+            oo_.deterministic_simulation.status = true;
+        end
+        if options_.no_homotopy
+            mexErrCheck('bytecode', info);
+        end
+    else
+        oo_ = feval([M_.fname '_dynamic'], options_, M_, oo_);
+    end
+else
+    if options_.bytecode
+        try
+            [info, tmp] = bytecode('dynamic', oo_.endo_simul, oo_.exo_simul, M_.params, repmat(oo_.steady_state,1,options_.periods+2), options_.periods);
+        catch
+            info = 0;
+        end
+        if info
+            oo_.deterministic_simulation.status = false;
+        else
+            oo_.endo_simul = tmp;
+            oo_.deterministic_simulation.status = true;
+        end
+        if options_.no_homotopy
+            mexErrCheck('bytecode', info);
+        end
+    else
+        if M_.maximum_endo_lead == 0 % Purely backward model
+            oo_ = sim1_purely_backward(options_, M_, oo_);
+        elseif M_.maximum_endo_lag == 0 % Purely forward model
+            oo_ = sim1_purely_forward(options_, M_, oo_);
+        else % General case
+            if options_.stack_solve_algo == 0
+                oo_ = sim1(options_, M_, oo_);
+            elseif options_.stack_solve_algo == 6
+                oo_ = sim1_lbj(options_, M_, oo_);
+            elseif options_.stack_solve_algo == 7
+                periods = options_.periods;
+                if ~isfield(options_.lmmcp,'lb')
+                    [lb,ub,pfm.eq_index] = get_complementarity_conditions(M_);
+                    options_.lmmcp.lb = repmat(lb,periods,1);
+                    options_.lmmcp.ub = repmat(ub,periods,1);
+                end
+                y = oo_.endo_simul;
+                y0 = y(:,1);
+                yT = y(:,periods+2);
+                z = y(:,2:periods+1);
+                illi = M_.lead_lag_incidence';
+                [i_cols,junk,i_cols_j] = find(illi(:));
+                illi = illi(:,2:3);
+                [i_cols_J1,junk,i_cols_1] = find(illi(:));
+                i_cols_T = nonzeros(M_.lead_lag_incidence(1:2,:)');
+                [y,info] = dynare_solve(@perfect_foresight_problem,z(:),options_, ...
+                                 str2func([M_.fname '_dynamic']),y0,yT, ...
+                                 oo_.exo_simul,M_.params,oo_.steady_state, ...
+                                 options_.periods,M_.endo_nbr,i_cols, ...
+                                 i_cols_J1, i_cols_1, i_cols_T, i_cols_j, ...
+                                 M_.NNZDerivatives(1));
+                if all(imag(y)<.1*options_.dynatol.f)
+                    if ~isreal(y)
+                        y = real(y);
+                    end
+                else
+                    info = 1;
+                end
+                oo_.endo_simul = [y0 reshape(y,M_.endo_nbr,periods) yT];
+                if info == 1
+                    oo_.deterministic_simulation.status = false;
+                else
+                    oo_.deterministic_simulation.status = true;
+                end
+            end
+        end
+    end
+end
+
+if nargout>1
+    y0 = oo_.endo_simul(:,1);
+    yT = oo_.endo_simul(:,options_.periods+2);
+    yy  = oo_.endo_simul(:,2:options_.periods+1);
+    if ~exist('illi')
+        illi = M_.lead_lag_incidence';
+        [i_cols,junk,i_cols_j] = find(illi(:));
+        illi = illi(:,2:3);
+        [i_cols_J1,junk,i_cols_1] = find(illi(:));
+        i_cols_T = nonzeros(M_.lead_lag_incidence(1:2,:)');
+    end
+    if options_.block && ~options_.bytecode
+        maxerror = oo_.deterministic_simulation.error;
+    else
+        if options_.bytecode
+            [chck, residuals, junk]= bytecode('dynamic','evaluate', oo_.endo_simul, oo_.exo_simul, M_.params, oo_.steady_state, 1);
+        else
+            residuals = perfect_foresight_problem(yy(:),str2func([M_.fname '_dynamic']), y0, yT, ...
+                                                  oo_.exo_simul,M_.params,oo_.steady_state, ...
+                                                  options_.periods,M_.endo_nbr,i_cols, ...
+                                                  i_cols_J1, i_cols_1, i_cols_T, i_cols_j, ...
+                                                  M_.NNZDerivatives(1));
+        end
+        maxerror = max(max(abs(residuals)));
+    end
+end
diff --git a/matlab/sim1.m b/matlab/perfect-foresight-models/sim1.m
similarity index 60%
rename from matlab/sim1.m
rename to matlab/perfect-foresight-models/sim1.m
index bbf41d1936cae674da9d6569200dff1a9a519b5b..4e00befbe9ec6a951875fe6a1d0f0549597f3bd0 100644
--- a/matlab/sim1.m
+++ b/matlab/perfect-foresight-models/sim1.m
@@ -1,4 +1,4 @@
-function sim1()
+function oo_ = sim1(options_, M_, oo_)
 % function sim1
 % Performs deterministic simulations with lead or lag on one period.
 % Uses sparse matrices.
@@ -13,7 +13,7 @@ function sim1()
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 1996-2013 Dynare Team
+% Copyright (C) 1996-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -30,7 +30,7 @@ function sim1()
 % 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_
+verbose = options_.verbosity;
 
 endogenous_terminal_period = options_.endogenous_terminal_period;
 vperiods = options_.periods*ones(1,options_.simul.maxit);
@@ -40,6 +40,7 @@ lead_lag_incidence = M_.lead_lag_incidence;
 
 ny = M_.endo_nbr;
 
+maximum_lag = M_.maximum_lag;
 max_lag = M_.maximum_endo_lag;
 
 nyp = nnz(lead_lag_incidence(1,:)) ;
@@ -68,21 +69,23 @@ i_cols_A1 = find(lead_lag_incidence(2:3,:)');
 i_cols_T = nonzeros(lead_lag_incidence(1:2,:)');
 i_cols_0 = nonzeros(lead_lag_incidence(2,:)');
 i_cols_A0 = find(lead_lag_incidence(2,:)');
-i_cols_j = 1:nd;
-i_upd = ny+(1:periods*ny);
+i_cols_j = (1:nd)';
+i_upd = maximum_lag*ny+(1:periods*ny);
 
 Y = endo_simul(:);
 
-skipline()
-disp (['-----------------------------------------------------']) ;
-fprintf('MODEL SIMULATION:\n');
+if verbose
+    skipline()
+    printline(56)
+    disp('MODEL SIMULATION:')
+    skipline()
+end
 
 model_dynamic = str2func([M_.fname,'_dynamic']);
 z = Y(find(lead_lag_incidence'));
 [d1,jacobian] = model_dynamic(z,oo_.exo_simul, params, ...
-                              steady_state,M_.maximum_lag+1);
+                              steady_state,maximum_lag+1);
 
-A = sparse([],[],[],periods*ny,periods*ny,periods*nnz(jacobian));
 res = zeros(periods*ny,1);
 
 o_periods = periods;
@@ -90,33 +93,39 @@ o_periods = periods;
 ZERO = zeros(length(i_upd),1);
 
 h1 = clock ;
+iA = zeros(periods*M_.NNZDerivatives(1),3);
 for iter = 1:options_.simul.maxit
     h2 = clock ;
     
-    i_rows = 1:ny;
-    i_cols = find(lead_lag_incidence');
-    i_cols_A = i_cols;
-
-    for it = (M_.maximum_lag+1):(M_.maximum_lag+periods)
-
-        [d1,jacobian] = model_dynamic(Y(i_cols), exo_simul, params, steady_state,it);
-        if it == M_.maximum_lag+periods && it == M_.maximum_lag+1
-            A(i_rows,i_cols_A0) = jacobian(:,i_cols_0);
-        elseif it == M_.maximum_lag+periods
-            A(i_rows,i_cols_A(i_cols_T)) = jacobian(:,i_cols_T);
-        elseif it == M_.maximum_lag+1
-            A(i_rows,i_cols_A1) = jacobian(:,i_cols_1);
+    i_rows = (1:ny)';
+    i_cols_A = find(lead_lag_incidence');
+    i_cols = i_cols_A+(maximum_lag-1)*ny;
+    m = 0;
+    for it = (maximum_lag+1):(maximum_lag+periods)
+        [d1,jacobian] = model_dynamic(Y(i_cols), exo_simul, params, ...
+                                      steady_state,it);
+        if it == maximum_lag+periods && it == maximum_lag+1
+            [r,c,v] = find(jacobian(:,i_cols_0));
+            iA((1:length(v))+m,:) = [i_rows(r),i_cols_A0(c),v];
+        elseif it == maximum_lag+periods
+            [r,c,v] = find(jacobian(:,i_cols_T));
+            iA((1:length(v))+m,:) = [i_rows(r),i_cols_A(i_cols_T(c)),v];
+        elseif it == maximum_lag+1
+            [r,c,v] = find(jacobian(:,i_cols_1));
+            iA((1:length(v))+m,:) = [i_rows(r),i_cols_A1(c),v];
         else
-            A(i_rows,i_cols_A) = jacobian(:,i_cols_j);
+            [r,c,v] = find(jacobian(:,i_cols_j));
+            iA((1:length(v))+m,:) = [i_rows(r),i_cols_A(c),v];
         end
-
+        m = m + length(v);
+        
         res(i_rows) = d1;
         
         if endogenous_terminal_period && iter>1
             dr = max(abs(d1));
             if dr<azero
                 vperiods(iter) = it;
-                periods = it-M_.maximum_lag;
+                periods = it-maximum_lag;
                 break
             end
         end
@@ -124,7 +133,7 @@ for iter = 1:options_.simul.maxit
         i_rows = i_rows + ny;
         i_cols = i_cols + ny;
         
-        if it > M_.maximum_lag+1
+        if it > maximum_lag+1
             i_cols_A = i_cols_A + ny;
         end
     end
@@ -141,12 +150,21 @@ for iter = 1:options_.simul.maxit
         end        
         skipline()
     end
+
+    if verbose
+        str = sprintf('Iter: %s,\t err. = %s, \t time = %s',num2str(iter),num2str(err), num2str(etime(clock,h2)));
+        disp(str);
+    end
+
     
     if err < options_.dynatol.f
         stop = 1 ;
         break
     end
 
+    iA = iA(1:m,:);
+    A = sparse(iA(:,1),iA(:,2),iA(:,3),periods*ny,periods*ny);
+
     if endogenous_terminal_period && iter>1
         dy = ZERO;
         dy(1:i_rows(end)) = -A(1:i_rows(end),1:i_rows(end))\res(1:i_rows(end));
@@ -166,42 +184,47 @@ end
 
 if stop
     if any(isnan(res)) || any(isinf(res)) || any(isnan(Y)) || any(isinf(Y)) || ~isreal(res) || ~isreal(Y)
-        oo_.deterministic_simulation.status = 0;% NaN or Inf occurred
+        oo_.deterministic_simulation.status = false;% NaN or Inf occurred
         oo_.deterministic_simulation.error = err;
         oo_.deterministic_simulation.iterations = iter;
         oo_.deterministic_simulation.periods = vperiods(1:iter);
-        oo_.endo_simul = reshape(Y,ny,periods+2);
-        skipline();
-        fprintf('\nSimulation terminated after %d iterations.\n',iter);
-        fprintf('Total time of simulation: %16.13f\n',etime(clock,h1));
-        if ~isreal(res) || ~isreal(Y)
-            fprintf('WARNING: Simulation terminated with imaginary parts in the residuals or endogenous variables.\n');
-        else
-            fprintf('WARNING: Simulation terminated with NaN or Inf in the residuals or endogenous variables.\n');
+        oo_.endo_simul = reshape(Y,ny,periods+maximum_lag+M_.maximum_lead);
+        if verbose
+            skipline()
+            disp(sprintf('Total time of simulation: %s.', num2str(etime(clock,h1))))
+            if ~isreal(res) || ~isreal(Y)
+                disp('Simulation terminated with imaginary parts in the residuals or endogenous variables.')
+            else
+                disp('Simulation terminated with NaN or Inf in the residuals or endogenous variables.')
+            end
+            disp('There is most likely something wrong with your model. Try model_diagnostics or another simulation method.')
+            printline(105)
         end
-        fprintf('WARNING: There is most likely something wrong with your model. Try model_diagnostics.\n');
     else
-        skipline();
-        fprintf('\nSimulation concluded successfully after %d iterations.\n',iter);
-        fprintf('Total time of simulation: %16.13f\n',etime(clock,h1));
-        fprintf('Max. Abs. Error         : %16.13f\n',err);
-        fprintf('Convergency obtained!\n');
-        oo_.deterministic_simulation.status = 1;% Convergency obtained.
+        if verbose
+            skipline();
+            disp(sprintf('Total time of simulation: %s', num2str(etime(clock,h1))))
+            printline(56)
+        end
+        oo_.deterministic_simulation.status = true;% Convergency obtained.
         oo_.deterministic_simulation.error = err;
         oo_.deterministic_simulation.iterations = iter;
         oo_.deterministic_simulation.periods = vperiods(1:iter);
-        oo_.endo_simul = reshape(Y,ny,periods+2);
+        oo_.endo_simul = reshape(Y,ny,periods+maximum_lag+M_.maximum_lead);
     end
 elseif ~stop
-    skipline();
-    fprintf('\nSimulation terminated after %d iterations.\n',iter);
-    fprintf('Total time of simulation: %16.13f\n',etime(clock,h1));
-    fprintf('Max. Abs. Error         : %16.13f\n',err);
-    fprintf('WARNING : maximum number of iterations is reached (modify option maxit).\n') ;
-    oo_.deterministic_simulation.status = 0;% more iterations are needed.
+    if verbose
+        skipline();
+        disp(sprintf('Total time of simulation: %s.', num2str(etime(clock,h1))))
+        disp('Maximum number of iterations is reached (modify option maxit).')
+        printline(62)
+    end
+    oo_.deterministic_simulation.status = false;% more iterations are needed.
     oo_.deterministic_simulation.error = err;
     oo_.deterministic_simulation.periods = vperiods(1:iter);
     oo_.deterministic_simulation.iterations = options_.simul.maxit;
 end
-disp (['-----------------------------------------------------']) ;
-skipline();
\ No newline at end of file
+
+if verbose
+    skipline();
+end
diff --git a/matlab/sim1_lbj.m b/matlab/perfect-foresight-models/sim1_lbj.m
similarity index 82%
rename from matlab/sim1_lbj.m
rename to matlab/perfect-foresight-models/sim1_lbj.m
index e2039cc1a9fba9b17774a0e3caf17f26d6c51e4a..00f481a8467147d76749d33b4224ceb3dc16ec3e 100644
--- a/matlab/sim1_lbj.m
+++ b/matlab/perfect-foresight-models/sim1_lbj.m
@@ -1,4 +1,4 @@
-function sim1_lbj()
+function oo_ = sim1_lbj(options_, M_, oo_)
 % function sim1_lbj
 % performs deterministic simulations with lead or lag on one period
 % using the historical LBJ algorithm
@@ -16,7 +16,7 @@ function sim1_lbj()
 % SPECIAL REQUIREMENTS
 %   None.
 
-% Copyright (C) 1996-2012 Dynare Team
+% Copyright (C) 1996-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -33,8 +33,6 @@ function sim1_lbj()
 % 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_
-
 lead_lag_incidence = M_.lead_lag_incidence;
 
 ny = size(oo_.endo_simul,1) ;
@@ -51,9 +49,13 @@ isf1 = [nyp+ny+1:nyf+nyp+ny+1] ;
 stop = 0 ;
 iz = [1:ny+nyp+nyf];
 
-disp (['-----------------------------------------------------']) ;
-disp (['MODEL SIMULATION :']) ;
-fprintf('\n') ;
+verbose = options_.verbosity;
+
+if verbose
+    printline(56)
+    disp(['MODEL SIMULATION :'])
+    skipline()
+end
 
 it_init = M_.maximum_lag+1 ;
 
@@ -100,16 +102,18 @@ for iter = 1:options_.simul.maxit
     end
     
     err = max(max(abs(c./options_.scalv')));
-    disp([num2str(iter) ' -     err = ' num2str(err)]) ;
-    disp(['     Time of iteration       :' num2str(etime(clock,h2))]) ;
+
+    if verbose
+        str = sprintf('Iter: %s,\t err. = %s, \t time = %s',num2str(iter),num2str(err), num2str(etime(clock,h2)));
+        disp(str);
+    end
     
     if err < options_.dynatol.f
         stop = 1 ;
-        fprintf('\n') ;
-        disp([' Total time of simulation        :' num2str(etime(clock,h1))]) ;
-        fprintf('\n') ;
-        disp([' Convergency obtained.']) ;
-        fprintf('\n') ;
+        if verbose
+            skipline()
+            disp(sprintf('Total time of simulation: %s', num2str(etime(clock,h1))))
+        end
         oo_.deterministic_simulation.status = 1;% Convergency obtained.
         oo_.deterministic_simulation.error = err;
         oo_.deterministic_simulation.iterations = iter;
@@ -118,15 +122,21 @@ for iter = 1:options_.simul.maxit
 end
 
 if ~stop
-    fprintf('\n') ;
-    disp(['     Total time of simulation        :' num2str(etime(clock,h1))]) ;
-    fprintf('\n') ;
-    disp(['WARNING : maximum number of iterations is reached (modify options_.simul.maxit).']) ;
-    fprintf('\n') ;
+    if verbose
+        disp(sprintf('Total time of simulation: %s.', num2str(etime(clock,h1))))
+        disp('Maximum number of iterations is reached (modify option maxit).')
+    end
     oo_.deterministic_simulation.status = 0;% more iterations are needed.
     oo_.deterministic_simulation.error = err;
     oo_.deterministic_simulation.errors = c/abs(err);    
     oo_.deterministic_simulation.iterations = options_.simul.maxit;
 end
-disp (['-----------------------------------------------------']) ;
 
+if verbose
+    if stop
+        printline(56)
+    else
+        printline(62)
+    end
+    skipline()
+end
diff --git a/matlab/sim1_purely_backward.m b/matlab/perfect-foresight-models/sim1_purely_backward.m
similarity index 92%
rename from matlab/sim1_purely_backward.m
rename to matlab/perfect-foresight-models/sim1_purely_backward.m
index f5a47dfc7b74e3c68d3f53a00c259552b365fd2e..21866740f319f15f8596752692b6084ed2227e5d 100644
--- a/matlab/sim1_purely_backward.m
+++ b/matlab/perfect-foresight-models/sim1_purely_backward.m
@@ -1,7 +1,7 @@
-function sim1_purely_backward()
+function oo_ = sim1_purely_backward(options_, M_, oo_)
 % Performs deterministic simulation of a purely backward model
 
-% Copyright (C) 2012-2014 Dynare Team
+% Copyright (C) 2012-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -18,7 +18,6 @@ function sim1_purely_backward()
 % 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_
     if size(M_.lead_lag_incidence,1) > 1
         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
@@ -46,7 +45,7 @@ function sim1_purely_backward()
                               M_.endo_nbr, 1, options_.gstep, ...
                               options_.solve_tolf,options_.solve_tolx, ...
                               options_.simul.maxit,options_.debug,oo_.exo_simul, ...
-                              M_.params, oo_.steady_state, it);
+                              M_.params, oo_.steady_state, it+M_.maximum_lag-1);
 
         if check
             oo_.deterministic_simulation.status = 0;
@@ -54,4 +53,3 @@ function sim1_purely_backward()
 
         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/perfect-foresight-models/sim1_purely_forward.m
similarity index 92%
rename from matlab/sim1_purely_forward.m
rename to matlab/perfect-foresight-models/sim1_purely_forward.m
index e4ba8a7094c7da1066f97b50ee55851f8c484256..34b60f510edaaa54be67e4a4f4943ed66a9ee4f1 100644
--- a/matlab/sim1_purely_forward.m
+++ b/matlab/perfect-foresight-models/sim1_purely_forward.m
@@ -1,7 +1,7 @@
-function sim1_purely_forward()
+function oo_ = sim1_purely_forward(options_, M_, oo_)
 % Performs deterministic simulation of a purely forward model
 
-% Copyright (C) 2012-2014 Dynare Team
+% Copyright (C) 2012-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -18,8 +18,6 @@ function sim1_purely_forward()
 % 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
 
@@ -39,7 +37,7 @@ function sim1_purely_forward()
                              1, options_.gstep, options_.solve_tolf, ...
                              options_.solve_tolx, options_.simul.maxit, ...
                              options_.debug,oo_.exo_simul, M_.params, oo_.steady_state, ...
-                             it);
+                             it+M_.maximum_lag);
 
         if info
             oo_.deterministic_simulation.status = 0;
@@ -47,4 +45,3 @@ function sim1_purely_forward()
 
         oo_.endo_simul(:,it) = tmp(1:M_.endo_nbr);
     end
-    
\ No newline at end of file
diff --git a/matlab/perfect_foresight_solver.m b/matlab/perfect_foresight_solver.m
deleted file mode 100644
index bfeb16e4f309ef2e33dcb4953923df7d03a12f53..0000000000000000000000000000000000000000
--- a/matlab/perfect_foresight_solver.m
+++ /dev/null
@@ -1,230 +0,0 @@
-function perfect_foresight_solver()
-% Computes deterministic simulations
-%  
-% INPUTS
-%   None
-%  
-% OUTPUTS
-%   none
-%    
-% ALGORITHM
-%   
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 1996-2014 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_
-
-if options_.stack_solve_algo < 0 || options_.stack_solve_algo > 7
-    error('PERFECT_FORESIGHT_SOLVER: stack_solve_algo must be between 0 and 7')
-end
-
-if ~options_.block && ~options_.bytecode && options_.stack_solve_algo ~= 0 ...
-        && options_.stack_solve_algo ~= 6 && options_.stack_solve_algo ~= 7
-    error('PERFECT_FORESIGHT_SOLVER: 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('PERFECT_FORESIGHT_SOLVER: you can''t use stack_solve_algo = 5 without bytecode option')
-end
-
-if (options_.block || options_.bytecode) && options_.stack_solve_algo == 6
-    error('PERFECT_FORESIGHT_SOLVER: you can''t use stack_solve_algo = 6 with block or bytecode option')
-end
-
-if isoctave && options_.stack_solve_algo == 2
-    error('PERFECT_FORESIGHT_SOLVER: you can''t use stack_solve_algo = 2 under Octave')
-end
-
-
-if isempty(oo_.endo_simul) || any(size(oo_.endo_simul) ~= [ M_.endo_nbr, M_.maximum_endo_lag+options_.periods+M_.maximum_endo_lead ])
-    error('PERFECT_FORESIGHT_SOLVER: ''oo_.endo_simul'' has wrong size. Did you run ''perfect_foresight_setup'' ?')
-end
-
-if isempty(oo_.exo_simul) || any(size(oo_.exo_simul) ~= [ M_.maximum_lag+options_.periods+M_.maximum_lead, M_.exo_nbr ])
-    error('PERFECT_FORESIGHT_SOLVER: ''oo_.exo_simul'' has wrong size. Did you run ''perfect_foresight_setup'' ?')
-end
-
-
-if isempty(options_.scalv) || options_.scalv == 0
-    options_.scalv = oo_.steady_state;
-end
-
-options_.scalv= 1;
-
-if options_.debug
-    model_static = str2func([M_.fname,'_static']);
-    for ii=1:size(oo_.exo_simul,1)
-        [residual(:,ii)] = model_static(oo_.steady_state, oo_.exo_simul(ii,:),M_.params);
-    end
-    problematic_periods=find(any(isinf(residual)) | any(isnan(residual)))-M_.maximum_endo_lag;
-    if ~isempty(problematic_periods) 
-        period_string=num2str(problematic_periods(1));
-        for ii=2:length(problematic_periods)
-            period_string=[period_string, ', ', num2str(problematic_periods(ii))];
-        end
-        fprintf('\n\nWARNING: Value for the exogenous variable(s) in period(s) %s inconsistent with the static model.\n',period_string);   
-        fprintf('WARNING: Check for division by 0.\n')
-    end
-end
-
-% Effectively compute simulation, possibly with homotopy
-if options_.no_homotopy
-    simulation_core;
-else
-    exosim = oo_.exo_simul;
-    exoinit = repmat(oo_.exo_steady_state',M_.maximum_lag+options_.periods+M_.maximum_lead,1);
-    endosim = oo_.endo_simul;
-    endoinit = repmat(oo_.steady_state, 1,M_.maximum_endo_lag+options_.periods+M_.maximum_endo_lead);
-
-    current_weight = 0; % Current weight of target point in convex combination
-    step = 1;
-    success_counter = 0;
-
-    while (step > options_.dynatol.x)
-
-        new_weight = current_weight + step; % Try this weight, and see if it succeeds
-        if new_weight >= 1
-            new_weight = 1; % Don't go beyond target point
-            step = new_weight - current_weight;
-        end
-
-        % Compute convex combination for exo path and initial/terminal endo conditions
-        % But take care of not overwriting the computed part of oo_.endo_simul
-        oo_.exo_simul = exosim*new_weight + exoinit*(1-new_weight);
-        endocombi = endosim*new_weight + endoinit*(1-new_weight);
-        oo_.endo_simul(:,1:M_.maximum_endo_lag) = endocombi(:,1:M_.maximum_endo_lag);
-        oo_.endo_simul(:,(end-M_.maximum_endo_lead):end) = endocombi(:,(end-M_.maximum_endo_lead):end);
-
-        saved_endo_simul = oo_.endo_simul;
-
-        simulation_core;
-
-        if oo_.deterministic_simulation.status == 1
-            current_weight = new_weight;
-            if current_weight >= 1
-                break
-            end
-            success_counter = success_counter + 1;
-            if success_counter >= 3
-                success_counter = 0;
-                step = step * 2;
-                disp([ 'Homotopy step succeeded, doubling step size (completed ' sprintf('%.1f', current_weight*100) '%, step size ' sprintf('%.3g', step) ')' ])
-            else
-                disp([ 'Homotopy step succeeded (completed ' sprintf('%.1f', current_weight*100) '%, step size ' sprintf('%.3g', step) ')' ])
-            end
-        else
-            oo_.endo_simul = saved_endo_simul;
-            success_counter = 0;
-            step = step / 2;
-            disp([ 'Homotopy step failed, halving step size (completed ' sprintf('%.1f', current_weight*100) '%, step size ' sprintf('%.3g', step) ')' ])
-        end
-    end
-end
-
-if oo_.deterministic_simulation.status == 1
-    disp('Perfect foresight solution found.')
-else
-    warning('Failed to solve perfect foresight model')
-end
-
-dyn2vec;
-
-if isnan(options_.initial_period)
-    initial_period = dates(1,1);
-else
-    initial_period = options_.initial_period;
-end
-
-ts = dseries(transpose(oo_.endo_simul),initial_period,cellstr(M_.endo_names));
-assignin('base', 'Simulated_time_series', ts);
-
-end
-
-
-function simulation_core()
-
-global M_ oo_ options_
-
-if(options_.block)
-    if(options_.bytecode)
-        [info, oo_.endo_simul] = bytecode('dynamic');
-        if info == 1
-            oo_.deterministic_simulation.status = 0;
-        else
-            oo_.deterministic_simulation.status = 1;
-        end
-        mexErrCheck('bytecode', info);
-    else
-        eval([M_.fname '_dynamic']);
-    end
-else
-    if(options_.bytecode)
-        [info, oo_.endo_simul]=bytecode('dynamic');
-        if info == 1
-            oo_.deterministic_simulation.status = 0;
-        else
-            oo_.deterministic_simulation.status = 1;
-        end;
-        mexErrCheck('bytecode', info);
-    else
-        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;
-            elseif options_.stack_solve_algo == 6
-                sim1_lbj;
-            elseif options_.stack_solve_algo == 7
-                periods = options_.periods;
-                if ~isfield(options_.lmmcp,'lb')
-                    [lb,ub,pfm.eq_index] = get_complementarity_conditions(M_);
-                    options_.lmmcp.lb = repmat(lb,periods,1);
-                    options_.lmmcp.ub = repmat(ub,periods,1);
-                end
-
-                y = oo_.endo_simul;
-                y0 = y(:,1);
-                yT = y(:,periods+2);
-                z = y(:,2:periods+1);
-                illi = M_.lead_lag_incidence';
-                [i_cols,~,i_cols_j] = find(illi(:));
-                illi = illi(:,2:3);
-                [i_cols_J1,~,i_cols_1] = find(illi(:));
-                i_cols_T = nonzeros(M_.lead_lag_incidence(1:2,:)');
-                [y,info] = dynare_solve(@perfect_foresight_problem,z(:),1, ...
-                                 str2func([M_.fname '_dynamic']),y0,yT, ...
-                                 oo_.exo_simul,M_.params,oo_.steady_state, ...
-                                 options_.periods,M_.endo_nbr,i_cols, ...
-                                 i_cols_J1, i_cols_1, i_cols_T, i_cols_j, ...
-                                 M_.NNZDerivatives(1));
-                oo_.endo_simul = [y0 reshape(y,M_.endo_nbr,periods) yT];
-                if info == 1
-                    oo_.deterministic_simulation.status = 0;
-                else
-                    oo_.deterministic_simulation.status = 1;
-                end;
-            end
-        end
-    end
-end
-
-end
diff --git a/matlab/plot_identification.m b/matlab/plot_identification.m
index 4f9fcf98ac362410d2abc9157c68853aa7705276..549224ef0dfae6b783857acdd8e702353d916111 100644
--- a/matlab/plot_identification.m
+++ b/matlab/plot_identification.m
@@ -247,13 +247,30 @@ else
         hist(log10(idelre.cond))
         title('log10 of Condition number in the LRE model')
         dyn_saveas(hh,[IdentifDirectoryName '/' M_.fname '_ident_COND' ],options_);
+        options_mcf.pvalue_ks = 0.1;
+        options_mcf.pvalue_corr = 0.001;
+        options_mcf.alpha2 = 0;
+        options_mcf.param_names = name;
+        options_mcf.fname_ = M_.fname;
+        options_mcf.OutputDirectoryName = IdentifDirectoryName;
+        options_mcf.beha_title = 'LOW condition nbr';
+        options_mcf.nobeha_title = 'HIGH condition nbr';
+        options_mcf.amcf_name = 'MC_HighestCondNumberLRE';
+        options_mcf.amcf_title = 'MC Highest Condition Number LRE Model';
+        options_mcf.title = 'MC Highest Condition Number LRE Model';
         ncut=floor(SampleSize/10*9);
         [dum,is]=sort(idelre.cond);
-        [proba, dproba] = stab_map_1(params, is(1:ncut), is(ncut+1:end), 'MC_HighestCondNumberLRE', 1, [], IdentifDirectoryName, 0.1,'MC Highest Condition Number LRE Model');
+        mcf_analysis(params, is(1:ncut), is(ncut+1:end), options_mcf, options_);
+        options_mcf.amcf_name = 'MC_HighestCondNumberModel';
+        options_mcf.amcf_title = 'MC Highest Condition Number Model Solution';
+        options_mcf.title = 'MC Highest Condition Number Model Solution';
         [dum,is]=sort(idemodel.cond);
-        [proba, dproba] = stab_map_1(params, is(1:ncut), is(ncut+1:end), 'MC_HighestCondNumberModel', 1, [], IdentifDirectoryName, 0.1,'MC Highest Condition Number Model Solution');
+        mcf_analysis(params, is(1:ncut), is(ncut+1:end), options_mcf, options_);
+        options_mcf.amcf_name = 'MC_HighestCondNumberMoments';
+        options_mcf.amcf_title = 'MC Highest Condition Number Model Moments';
+        options_mcf.title = 'MC Highest Condition Number Model Moments';
         [dum,is]=sort(idemoments.cond);
-        [proba, dproba] = stab_map_1(params, is(1:ncut), is(ncut+1:end), 'MC_HighestCondNumberMoments', 1, [], IdentifDirectoryName, 0.1,'MC Highest Condition Number Model Moments');
+        mcf_analysis(params, is(1:ncut), is(ncut+1:end), options_mcf, options_);
 %         [proba, dproba] = stab_map_1(idemoments.Mco', is(1:ncut), is(ncut+1:end), 'HighestCondNumberMoments_vs_Mco', 1, [], IdentifDirectoryName);
 %         for j=1:nparam,
 % %             ibeh=find(idemoments.Mco(j,:)<0.9);
diff --git a/matlab/print_info.m b/matlab/print_info.m
index 0ec5e378884827ee3e9790ad901c4fb9c1db2e3f..91c2100c0a65a87ea2616fd281b101801474a992 100644
--- a/matlab/print_info.m
+++ b/matlab/print_info.m
@@ -88,6 +88,8 @@ if ~noprint
         error('Some updated params contain NaN or Inf')
       case 25
         error('The solution to the static equations is not a steady state of the dynamic model: verify that the equations tagged by [static] and [dynamic] are consistent')
+      case 26
+        error('The loglinearization of the model cannot be performed, because the steady state is not strictly positive.')
       case 30
         error('Variance can''t be computed')
       case 41
diff --git a/matlab/print_table_prior.m b/matlab/print_table_prior.m
new file mode 100644
index 0000000000000000000000000000000000000000..26e60fc4bf88b153d4e594c019ced08c042eef2c
--- /dev/null
+++ b/matlab/print_table_prior.m
@@ -0,0 +1,158 @@
+function print_table_prior(lb, ub, DynareOptions, ModelInfo, BayesInfo, EstimationInfo)
+
+% This routine prints in the command window some descriptive statistics about the prior distribution. 
+
+% Copyright (C) 2015 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+PriorNames = 'Beta';
+PriorNames = strvcat(PriorNames,'Gamma');
+PriorNames = strvcat(PriorNames,'Gaussian');
+PriorNames = strvcat(PriorNames,'Inverted Gamma');
+PriorNames = strvcat(PriorNames,'Uniform');
+PriorNames = strvcat(PriorNames,'Inverted Gamma -- 2');
+
+n = size(BayesInfo.name,1); % Numbe rof estimated parameters.
+
+l1 = printline(10, '-');
+T1 = strvcat(l1, 'PARAMETER ');
+T1 = strvcat(T1, l1);
+
+l2 = printline(133, '-');
+T2 = strvcat(l2, sprintf('Prior shape      \t Prior mean \t Prior mode \t Prior std. \t Prior lb \t Prior ub \t Prior HPD lb \t Prior HPH ub'));
+T2 = strvcat(T2, l2);
+
+prior_trunc_backup = DynareOptions.prior_trunc ;
+DynareOptions.prior_trunc = (1-DynareOptions.prior_interval)/2 ;
+PriorIntervals = prior_bounds(BayesInfo,DynareOptions) ;
+DynareOptions.prior_trunc = prior_trunc_backup ;
+
+RESIZE = false;
+
+for i=1:size(BayesInfo.name,1)
+    [Name,tmp] = get_the_name(i,1,ModelInfo,EstimationInfo,DynareOptions);
+    if length(Name)>size(T1,2)
+        resize = true;
+    else
+        resize = false;
+    end
+    T1 = strvcat(T1, Name);
+    if resize
+        RESIZE = true;
+        l1 = printline(length(Name));
+        T1(1,:) = l1;
+        T1(3,:) = l1;
+    end
+    PriorShape = PriorNames(BayesInfo.pshape(i),:);
+    PriorMean = BayesInfo.p1(i);
+    PriorMode = BayesInfo.p5(i);
+    PriorStandardDeviation = BayesInfo.p2(i);
+    switch BayesInfo.pshape(i)
+      case { 1 , 5 }
+        LowerBound = BayesInfo.p3(i);
+        UpperBound = BayesInfo.p4(i);
+        if ~isinf(lb(i))
+            LowerBound=max(LowerBound,lb(i));
+        end
+        if ~isinf(ub(i))
+            UpperBound=min(UpperBound,ub(i));
+        end
+      case { 2 , 4 , 6 }
+        LowerBound = BayesInfo.p3(i);
+        if ~isinf(lb(i))
+            LowerBound=max(LowerBound,lb(i));
+        end
+        if ~isinf(ub(i))
+            UpperBound=ub(i);
+        else
+            UpperBound = Inf;
+        end
+      case 3
+        if isinf(BayesInfo.p3(i)) && isinf(lb(i))
+            LowerBound = -Inf;
+        else
+            LowerBound = BayesInfo.p3(i);
+            if ~isinf(lb(i))
+                LowerBound=max(LowerBound,lb(i));
+            end
+        end
+        if isinf(BayesInfo.p4(i)) && isinf(ub(i))
+            UpperBound = Inf;
+        else
+            UpperBound = BayesInfo.p4(i);
+            if ~isinf(ub(i))
+                UpperBound=min(UpperBound,ub(i));
+            end
+        end
+      otherwise
+        error('get_prior_info:: Dynare bug!')
+    end
+    format_string = build_format_string(PriorMode, PriorStandardDeviation,LowerBound,UpperBound);
+    str = sprintf(format_string, ...
+                  PriorShape, ...
+                  PriorMean, ...
+                  PriorMode, ...
+                  PriorStandardDeviation, ...
+                  LowerBound, ...
+                  UpperBound, ...
+                  PriorIntervals.lb(i), ...
+                  PriorIntervals.ub(i) );
+    T2 = strvcat(T2, str);    
+end
+
+T1 = strvcat(T1, l1);
+T2 = strvcat(T2, l2);
+
+skipline(2)
+
+if RESIZE
+    l0 = printline(2);
+    T0 = strvcat(l0,'  ');
+    T0 = strvcat(T0, l0);
+    T0 = strvcat(T0, repmat('  ', n, 1));
+    T0 = strvcat(T0, l0);
+    disp([T1, T0, T2])
+else
+    disp([T1, T2])
+end
+
+skipline(2)
+
+
+function format_string = build_format_string(PriorMode,PriorStandardDeviation,LowerBound,UpperBound)
+    format_string = ['%s \t %6.4f \t'];
+    if isnan(PriorMode)
+        format_string = [ format_string , ' %s \t'];
+    else
+        format_string = [ format_string , ' %6.4f \t'];
+    end
+    if ~isnumeric(PriorStandardDeviation)
+        format_string = [ format_string , ' %s \t'];
+    else
+        format_string = [ format_string , ' %6.4f \t'];
+    end
+    if ~isnumeric(LowerBound)
+        format_string = [ format_string , ' %s \t'];
+    else
+        format_string = [ format_string , ' %6.4f \t'];
+    end
+    if ~isnumeric(UpperBound)
+        format_string = [ format_string , ' %s \t'];
+    else
+        format_string = [ format_string , ' %6.4f \t'];
+    end
+    format_string = [ format_string , ' %6.4f \t %6.4f'];
\ No newline at end of file
diff --git a/matlab/reports/@report_series/subsasgn.m b/matlab/printline.m
similarity index 52%
rename from matlab/reports/@report_series/subsasgn.m
rename to matlab/printline.m
index fdf0f7db57df94f63bbeb81723cb2bcd896d9450..c60d0906a90133b7b7574ac05439d163e48b1233 100644
--- a/matlab/reports/@report_series/subsasgn.m
+++ b/matlab/printline.m
@@ -1,7 +1,16 @@
-function B = subsasgn(A, S, V)
-% function B = subsasgn(A, S, V)
+function varargout = printline(n, s, fid)
+% This function print a line formed by replicating a symbol s.
+%
+% INPUTS 
+%
+%   n  [integer]    Length of the printed line
+%   s  [char]       Symbol used to draw the line (+, -, =, ...)
+%   f  [integer]    file id returned by fopen
+%    
+% OUTPUTS 
+%   None
 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -16,27 +25,26 @@ function B = subsasgn(A, S, V)
 % 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/>.
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.    
 
-B = A;
-if length(S) > 1
-    for i=1:(length(S)-1)
-        B = subsref(B, S(i));
+if nargin<3
+    f = 1;
+    if nargin<2
+        s = '-';
+        if ~nargin
+            error('printline: First argument is mandatory!')
+        end
     end
-    B = subsasgn(B, S(end), V);
-    B = subsasgn(A, S(1:(end-1)), B);
-    return
 end
 
-switch S.type
-    case '.'
-        switch S.subs
-            case fieldnames(A)
-                B.(S.subs) = V;
-            otherwise
-                error(['@report_series.subsasgn: field ' S.subs 'does not exist']);
-        end
-    otherwise
-        error('@report_series.subsasgn: syntax error');
+S = s;
+
+for i=2:n
+    S = sprintf('%s%s',S,s);
 end
+
+if nargout
+    varargout(1) = { sprintf('%s',S) };
+else
+    fprintf(f,sprintf('%s\n',S))
 end
\ No newline at end of file
diff --git a/matlab/prior_posterior_statistics.m b/matlab/prior_posterior_statistics.m
index 35a0b481f682cc8841b2d7bf7ea665d3f472f0ea..a2f43343e2ad992c4baae3df07a628d9b636cb8e 100644
--- a/matlab/prior_posterior_statistics.m
+++ b/matlab/prior_posterior_statistics.m
@@ -14,11 +14,11 @@ function prior_posterior_statistics(type,dataset,dataset_info)
 %
 % SPECIAL REQUIREMENTS
 %    none
-
+% 
 % PARALLEL CONTEXT
-% See the comments random_walk_metropolis_hastings.m funtion.
-
-
+% See the comments in the random_walk_metropolis_hastings.m funtion.
+% 
+% 
 % Copyright (C) 2005-2013 Dynare Team
 %
 % This file is part of Dynare.
@@ -98,13 +98,13 @@ MAX_ninno = min(B,ceil(MaxNumberOfBytes/(exo_nbr*gend)/8));
 MAX_nerro = min(B,ceil(MaxNumberOfBytes/(size(options_.varobs,1)*gend)/8));
 
 if naK
-    MAX_naK   = min(B,ceil(MaxNumberOfBytes/(length(options_.varobs)* ...
-                                             length(options_.filter_step_ahead)*gend)/8));
+    MAX_naK   = min(B,ceil(MaxNumberOfBytes/(endo_nbr* ...
+                                             length(options_.filter_step_ahead)*(gend+max(options_.filter_step_ahead)))/8));
 end
 
 if horizon
-    MAX_nforc1 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*horizon)/8));
-    MAX_nforc2 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*horizon)/ ...
+    MAX_nforc1 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/8));
+    MAX_nforc2 = min(B,ceil(MaxNumberOfBytes/((endo_nbr)*(horizon+maxlag))/ ...
                             8));
     IdObs    = bayestopt_.mfys;
 
diff --git a/matlab/prior_posterior_statistics_core.m b/matlab/prior_posterior_statistics_core.m
index ef8328c3577d132692e078cff232214cf21e1271..26b793c08cf05a923554c2b81e8c0cb311378b0f 100644
--- a/matlab/prior_posterior_statistics_core.m
+++ b/matlab/prior_posterior_statistics_core.m
@@ -273,6 +273,8 @@ for b=fpar:B
 
     if irun(5) > MAX_nruns || b == B
         stock = stock_param(1:irun(5)-1,:);
+        stock_logpo = stock_logpo(1:irun(5)-1);
+        stock_ys = stock_ys(1:irun(5)-1,:);
         ifil(5) = ifil(5) + 1;
         save([DirectoryName '/' M_.fname '_param' int2str(ifil(5)) '.mat'],'stock','stock_logpo','stock_ys');
         if RemoteFlag==1,
diff --git a/matlab/priordens.m b/matlab/priordens.m
index 02ba5c698719d613409a3d520a5b75cc22f1e05f..f3e5fd619dc3fdc0868aee0fdd2046412dfd8c7d 100644
--- a/matlab/priordens.m
+++ b/matlab/priordens.m
@@ -1,4 +1,4 @@
-function [logged_prior_density, dlprior, d2lprior] = priordens(x, pshape, p6, p7, p3, p4,initialization)
+function [logged_prior_density, dlprior, d2lprior, info] = priordens(x, pshape, p6, p7, p3, p4,initialization)
 % Computes a prior density for the structural parameters of DSGE models
 %
 % INPUTS 
@@ -12,6 +12,7 @@ function [logged_prior_density, dlprior, d2lprior] = priordens(x, pshape, p6, p7
 %    
 % OUTPUTS 
 %    logged_prior_density  [double]  scalar, log of the prior density evaluated at x.
+%    info                  [double]  error code for index of Inf-prior parameter
 %
 
 % Copyright (C) 2003-2012 Dynare Team
@@ -34,6 +35,8 @@ function [logged_prior_density, dlprior, d2lprior] = priordens(x, pshape, p6, p7
 persistent id1 id2 id3 id4 id5 id6
 persistent tt1 tt2 tt3 tt4 tt5 tt6
 
+info=0;
+
 if nargin > 6  && initialization == 1
     % Beta indices.
     tt1 = 1;
@@ -81,6 +84,9 @@ d2lprior = 0.0;
 if tt1
     logged_prior_density = logged_prior_density + sum(lpdfgbeta(x(id1),p6(id1),p7(id1),p3(id1),p4(id1))) ;
     if isinf(logged_prior_density)
+        if nargout ==4 
+            info=id1(isinf(lpdfgbeta(x(id1),p6(id1),p7(id1),p3(id1),p4(id1))));
+        end
         return
     end
     if nargout == 2,
@@ -93,6 +99,9 @@ end
 if tt2
     logged_prior_density = logged_prior_density + sum(lpdfgam(x(id2)-p3(id2),p6(id2),p7(id2))) ;
     if isinf(logged_prior_density)
+        if nargout ==4 
+            info=id2(isinf(lpdfgam(x(id2)-p3(id2),p6(id2),p7(id2))));
+        end
         return
     end
     if nargout == 2,
@@ -114,6 +123,9 @@ end
 if tt4
     logged_prior_density = logged_prior_density + sum(lpdfig1(x(id4)-p3(id4),p6(id4),p7(id4))) ;
     if isinf(logged_prior_density)
+        if nargout ==4 
+            info=id4(isinf(lpdfig1(x(id4)-p3(id4),p6(id4),p7(id4))));
+        end
         return
     end
     if nargout == 2,
@@ -126,6 +138,9 @@ end
 if tt5
     if any(x(id5)-p3(id5)<0) || any(x(id5)-p4(id5)>0)
         logged_prior_density = -Inf ;
+        if nargout ==4 
+            info=id5((x(id5)-p3(id5)<0) || (x(id5)-p4(id5)>0));
+        end
         return
     end
     logged_prior_density = logged_prior_density + sum(log(1./(p4(id5)-p3(id5)))) ;
@@ -140,6 +155,9 @@ end
 if tt6
     logged_prior_density = logged_prior_density + sum(lpdfig2(x(id6)-p3(id6),p6(id6),p7(id6))) ;
     if isinf(logged_prior_density)
+        if nargout ==4 
+            info=id6(isinf(lpdfig2(x(id6)-p3(id6),p6(id6),p7(id6))));
+        end
         return
     end
     if nargout == 2,
diff --git a/matlab/random_walk_metropolis_hastings.m b/matlab/random_walk_metropolis_hastings.m
index c2a49e7a29e22b194ee7ee4debfa0a2cdc725eb6..2092922ac65e464a640a327e4e241e8b9e17e30f 100644
--- a/matlab/random_walk_metropolis_hastings.m
+++ b/matlab/random_walk_metropolis_hastings.m
@@ -1,14 +1,17 @@
 function random_walk_metropolis_hastings(TargetFun,ProposalFun,xparam1,vv,mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_)
-%function record=random_walk_metropolis_hastings(TargetFun,ProposalFun,xparam1,vv,mh_bounds,dataset_,options_,M_,estim_params_,bayestopt_,oo_)
-% Random walk Metropolis-Hastings algorithm. 
+% function random_walk_metropolis_hastings(TargetFun,ProposalFun,xparam1,vv,mh_bounds,dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,oo_)
+% Random Walk Metropolis-Hastings algorithm. 
 % 
 % INPUTS 
 %   o TargetFun  [char]     string specifying the name of the objective
 %                           function (posterior kernel).
+%   o ProposalFun  [char]   string specifying the name of the proposal
+%                           density
 %   o xparam1    [double]   (p*1) vector of parameters to be estimated (initial values).
 %   o vv         [double]   (p*p) matrix, posterior covariance matrix (at the mode).
 %   o mh_bounds  [double]   (p*2) matrix defining lower and upper bounds for the parameters. 
 %   o dataset_              data structure
+%   o dataset_info          dataset info structure
 %   o options_              options structure
 %   o M_                    model structure
 %   o estim_params_         estimated parameters structure
@@ -16,27 +19,27 @@ function random_walk_metropolis_hastings(TargetFun,ProposalFun,xparam1,vv,mh_bou
 %   o oo_                   outputs structure
 %
 % ALGORITHM 
-%   Metropolis-Hastings.       
+%   Random-Walk Metropolis-Hastings.       
 %
 % SPECIAL REQUIREMENTS
 %   None.
 %
 % PARALLEL CONTEXT
 % The most computationally intensive part of this function may be executed
-% in parallel. The code sutable to be executed in
-% parallel on multi core or cluster machine (in general a 'for' cycle),
-% is removed from this function and placed in random_walk_metropolis_hastings_core.m funtion.
-% Then the DYNARE parallel package contain a set of pairs matlab functions that can be executed in
-% parallel and called name_function.m and name_function_core.m. 
-% In addition in parallel package we have second set of functions used
-% to manage the parallel computation.
+% in parallel. The code suitable to be executed in
+% parallel on multi core or cluster machine (in general a 'for' cycle)
+% has been removed from this function and been placed in the random_walk_metropolis_hastings_core.m funtion.
+% 
+% The DYNARE parallel packages comprise a i) set of pairs of Matlab functions that can be executed in
+% parallel and called name_function.m and name_function_core.m and ii) a second set of functions used
+% to manage the parallel computations.
 %
-% This function was the first function to be parallelized, later other
+% This function was the first function to be parallelized. Later, other
 % functions have been parallelized using the same methodology.
 % Then the comments write here can be used for all the other pairs of
-% parallel functions and also for management funtions.
+% parallel functions and also for management functions.
 
-% Copyright (C) 2006-2013 Dynare Team
+% Copyright (C) 2006-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -54,7 +57,7 @@ function random_walk_metropolis_hastings(TargetFun,ProposalFun,xparam1,vv,mh_bou
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 
-% In Metropolis, we set penalty to Inf to as to reject all parameter sets triggering error in target density computation
+% In Metropolis, we set penalty to Inf so as to reject all parameter sets triggering an error during target density computation
 global objective_function_penalty_base
 objective_function_penalty_base = Inf;
 
@@ -73,16 +76,16 @@ load_last_mh_history_file(MetropolisFolder, ModelName);
 % First run in serial mode, and then comment the follow line.
 %   save('recordSerial.mat','-struct', 'record');
 
-% For parllel runs after serial runs with the abobe line active.
+% For parallel runs after serial runs with the abobe line active.
 %   TempRecord=load('recordSerial.mat');
 %   record.Seeds=TempRecord.Seeds;
 
 
 
 % Snapshot of the current state of computing. It necessary for the parallel
-% execution (i.e. to execute in a corretct way portion of code remotely or
-% on many core). The mandatory variables for local/remote parallel
-% computing are stored in localVars struct.
+% execution (i.e. to execute in a corretct way a portion of code remotely or
+% on many cores). The mandatory variables for local/remote parallel
+% computing are stored in the localVars struct.
 
 localVars =   struct('TargetFun', TargetFun, ...
                      'ProposalFun', ProposalFun, ...
@@ -110,9 +113,8 @@ localVars =   struct('TargetFun', TargetFun, ...
                      'varargin',[]);
 
 
-% The user don't want to use parallel computing, or want to compute a
-% single chain. In this cases Random walk Metropolis-Hastings algorithm is
-% computed sequentially.
+% User doesn't want to use parallel computing, or wants to compute a
+% single chain compute Random walk Metropolis-Hastings algorithm sequentially.
 
 if isnumeric(options_.parallel) || (nblck-fblck)==0,
     fout = random_walk_metropolis_hastings_core(localVars, fblck, nblck, 0);
@@ -152,6 +154,7 @@ NewFile = fout(1).NewFile;
 
 update_last_mh_history_file(MetropolisFolder, ModelName, record);
 
+% Provide diagnostic output
 skipline()
 disp(['Estimation::mcmc: Number of mh files: ' int2str(NewFile(1)) ' per block.'])
 disp(['Estimation::mcmc: Total number of generated files: ' int2str(NewFile(1)*nblck) '.'])
diff --git a/matlab/random_walk_metropolis_hastings_core.m b/matlab/random_walk_metropolis_hastings_core.m
index 90c89e871d91aaf7fdbe76dc78fa55b82b9a562b..2c26de0e5c5cb53ce1ff5adb9041ca35390ecad4 100644
--- a/matlab/random_walk_metropolis_hastings_core.m
+++ b/matlab/random_walk_metropolis_hastings_core.m
@@ -1,25 +1,25 @@
 function myoutput = random_walk_metropolis_hastings_core(myinputs,fblck,nblck,whoiam, ThisMatlab)
-% PARALLEL CONTEXT
-% This function contain the most computationally intensive portion of code in
-% random_walk_metropolis_hastings (the 'for xxx = fblck:nblck' loop). The branches in 'for'
-% cycle and are completely independent than suitable to be executed in parallel way.
+% function myoutput = random_walk_metropolis_hastings_core(myinputs,fblck,nblck,whoiam, ThisMatlab)
+% Contains the most computationally intensive portion of code in
+% random_walk_metropolis_hastings (the 'for xxx = fblck:nblck' loop). The branches in  that 'for'
+% cycle are completely independent to be suitable for parallel execution.
 %
 % INPUTS
 %   o myimput            [struc]     The mandatory variables for local/remote
 %                                    parallel computing obtained from random_walk_metropolis_hastings.m
 %                                    function.
 %   o fblck and nblck    [integer]   The Metropolis-Hastings chains.
-%   o whoiam             [integer]   In concurrent programming a modality to refer to the differents thread running in parallel is needed.
+%   o whoiam             [integer]   In concurrent programming a modality to refer to the different threads running in parallel is needed.
 %                                    The integer whoaim is the integer that
 %                                    allows us to distinguish between them. Then it is the index number of this CPU among all CPUs in the
 %                                    cluster.
 %   o ThisMatlab         [integer]   Allows us to distinguish between the
-%                                    'main' matlab, the slave matlab worker, local matlab, remote matlab,
+%                                    'main' Matlab, the slave Matlab worker, local Matlab, remote Matlab,
 %                                     ... Then it is the index number of this slave machine in the cluster.
 % OUTPUTS
 %   o myoutput  [struc]
-%               If executed without parallel is the original output of 'for b =
-%               fblck:nblck' otherwise a portion of it computed on a specific core or
+%               If executed without parallel, this is the original output of 'for b =
+%               fblck:nblck'. Otherwise, it's a portion of it computed on a specific core or
 %               remote machine. In this case:
 %                               record;
 %                               irun;
@@ -31,23 +31,12 @@ function myoutput = random_walk_metropolis_hastings_core(myinputs,fblck,nblck,wh
 %
 % SPECIAL REQUIREMENTS.
 %   None.
-
+% 
 % PARALLEL CONTEXT
-% The most computationally intensive part of this function may be executed
-% in parallel. The code sutable to be executed in parallel on multi core or cluster machine,
-% is removed from this function and placed in random_walk_metropolis_hastings_core.m funtion.
-% Then the DYNARE parallel package contain a set of pairs matlab functios that can be executed in
-% parallel and called name_function.m and name_function_core.m.
-% In addition in the parallel package we have second set of functions used
-% to manage the parallel computation.
-%
-% This function was the first function to be parallelized, later other
-% functions have been parallelized using the same methodology.
-% Then the comments write here can be used for all the other pairs of
-% parallel functions and also for management funtions.
+% See the comments in the random_walk_metropolis_hastings.m funtion.
 
 
-% Copyright (C) 2006-2013 Dynare Team
+% Copyright (C) 2006-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -74,11 +63,9 @@ end
 TargetFun=myinputs.TargetFun;
 ProposalFun=myinputs.ProposalFun;
 xparam1=myinputs.xparam1;
-vv=myinputs.vv;
 mh_bounds=myinputs.mh_bounds;
-ix2=myinputs.ix2;
-ilogpo2=myinputs.ilogpo2;
-ModelName=myinputs.ModelName;
+last_draw=myinputs.ix2;
+last_posterior=myinputs.ilogpo2;
 fline=myinputs.fline;
 npar=myinputs.npar;
 nruns=myinputs.nruns;
@@ -94,11 +81,9 @@ estim_params_ = myinputs.estim_params_;
 options_ = myinputs.options_;
 M_ = myinputs.M_;
 oo_ = myinputs.oo_;
-varargin=myinputs.varargin;
 
 % Necessary only for remote computing!
 if whoiam
-    Parallel=myinputs.Parallel;
     % initialize persistent variables in priordens()
     priordens(xparam1,bayestopt_.pshape,bayestopt_.p6,bayestopt_.p7, bayestopt_.p3,bayestopt_.p4,1);
 end
@@ -116,53 +101,51 @@ elseif strcmpi(ProposalFun,'rand_multivariate_student')
 end
 
 %
-% NOW i run the (nblck-fblck+1) metropolis-hastings chains
+% Now I run the (nblck-fblck+1) Metropolis-Hastings chains
 %
 
 proposal_covariance_Cholesky_decomposition = d*diag(bayestopt_.jscale);
 
-jloop=0;
+block_iter=0;
 
-JSUM = 0;
-for b = fblck:nblck,
-    jloop=jloop+1;
+for curr_block = fblck:nblck,
+    block_iter=block_iter+1;
     try
-        % This will not work if the master uses a random generator not
+        % This will not work if the master uses a random number generator not
         % available in the slave (different Matlab version or
-        % Matlab/Octave cluster). Therefor the trap.
+        % Matlab/Octave cluster). Therefore the trap.
         %
-        % This set the random generator type (the seed is useless but
-        % needed by the function)
+        % Set the random number generator type (the seed is useless but needed by the function)
         set_dynare_seed(options_.DynareRandomStreams.algo, options_.DynareRandomStreams.seed);
-        % This set the state 
-        set_dynare_random_generator_state(record.InitialSeeds(b).Unifor, record.InitialSeeds(b).Normal);
+        % Set the state of the RNG
+        set_dynare_random_generator_state(record.InitialSeeds(curr_block).Unifor, record.InitialSeeds(curr_block).Normal);
     catch
-        % If the state set by master is incompatible with the slave, we
-        % only reseed 
-        set_dynare_seed(options_.DynareRandomStreams.seed+b);
+        % If the state set by master is incompatible with the slave, we only reseed 
+        set_dynare_seed(options_.DynareRandomStreams.seed+curr_block);
     end
-    if (options_.load_mh_file~=0) && (fline(b)>1) && OpenOldFile(b)
-        load([BaseName '_mh' int2str(NewFile(b)) '_blck' int2str(b) '.mat'])
-        x2 = [x2;zeros(InitSizeArray(b)-fline(b)+1,npar)];
-        logpo2 = [logpo2;zeros(InitSizeArray(b)-fline(b)+1,1)];
-        OpenOldFile(b) = 0;
+    if (options_.load_mh_file~=0) && (fline(curr_block)>1) && OpenOldFile(curr_block) %load previous draws and likelihood
+        load([BaseName '_mh' int2str(NewFile(curr_block)) '_blck' int2str(curr_block) '.mat'])
+        x2 = [x2;zeros(InitSizeArray(curr_block)-fline(curr_block)+1,npar)];
+        logpo2 = [logpo2;zeros(InitSizeArray(curr_block)-fline(curr_block)+1,1)];
+        OpenOldFile(curr_block) = 0;
     else
-        x2 = zeros(InitSizeArray(b),npar);
-        logpo2 = zeros(InitSizeArray(b),1);
+        x2 = zeros(InitSizeArray(curr_block),npar);
+        logpo2 = zeros(InitSizeArray(curr_block),1);
     end
+    %Prepare waiting bars
     if whoiam
-        prc0=(b-fblck)/(nblck-fblck+1)*(isoctave || options_.console_mode);
-        hh = dyn_waitbar({prc0,whoiam,options_.parallel(ThisMatlab)},['MH (' int2str(b) '/' int2str(options_.mh_nblck) ')...']);
+        prc0=(curr_block-fblck)/(nblck-fblck+1)*(isoctave || options_.console_mode);
+        hh = dyn_waitbar({prc0,whoiam,options_.parallel(ThisMatlab)},['MH (' int2str(curr_block) '/' int2str(options_.mh_nblck) ')...']);
     else
-        hh = dyn_waitbar(0,['Metropolis-Hastings (' int2str(b) '/' int2str(options_.mh_nblck) ')...']);
+        hh = dyn_waitbar(0,['Metropolis-Hastings (' int2str(curr_block) '/' int2str(options_.mh_nblck) ')...']);
         set(hh,'Name','Metropolis-Hastings');
     end
-    isux = 0;
-    jsux = 0;
-    irun = fline(b);
-    j = 1;
-    while j <= nruns(b)
-        par = feval(ProposalFun, ix2(b,:), proposal_covariance_Cholesky_decomposition, n);
+    accepted_draws_this_chain = 0;
+    accepted_draws_this_file = 0;
+    draw_index_current_file = fline(curr_block); %get location of first draw in current block
+    draw_iter = 1;
+    while draw_iter <= nruns(curr_block)
+        par = feval(ProposalFun, last_draw(curr_block,:), proposal_covariance_Cholesky_decomposition, n);
         if all( par(:) > mh_bounds.lb ) && all( par(:) < mh_bounds.ub )
             try
                 logpost = - feval(TargetFun, par(:),dataset_,dataset_info,options_,M_,estim_params_,bayestopt_,mh_bounds,oo_);
@@ -172,29 +155,29 @@ for b = fblck:nblck,
         else
             logpost = -inf;
         end
-        if (logpost > -inf) && (log(rand) < logpost-ilogpo2(b))
-            x2(irun,:) = par;
-            ix2(b,:) = par;
-            logpo2(irun) = logpost;
-            ilogpo2(b) = logpost;
-            isux = isux + 1;
-            jsux = jsux + 1;
+        if (logpost > -inf) && (log(rand) < logpost-last_posterior(curr_block))
+            x2(draw_index_current_file,:) = par;
+            last_draw(curr_block,:) = par;
+            logpo2(draw_index_current_file) = logpost;
+            last_posterior(curr_block) = logpost;
+            accepted_draws_this_chain = accepted_draws_this_chain + 1;
+            accepted_draws_this_file = accepted_draws_this_file + 1;
         else
-            x2(irun,:) = ix2(b,:);
-            logpo2(irun) = ilogpo2(b);
+            x2(draw_index_current_file,:) = last_draw(curr_block,:);
+            logpo2(draw_index_current_file) = last_posterior(curr_block);
         end
-        prtfrc = j/nruns(b);
-        if (mod(j, 3)==0 && ~whoiam) || (mod(j,50)==0 && whoiam)
-            dyn_waitbar(prtfrc,hh,[ 'MH (' int2str(b) '/' int2str(options_.mh_nblck) ') ' sprintf('Current acceptance ratio %4.3f', isux/j)]);
+        prtfrc = draw_iter/nruns(curr_block);
+        if (mod(draw_iter, 3)==0 && ~whoiam) || (mod(draw_iter,50)==0 && whoiam)
+            dyn_waitbar(prtfrc,hh,[ 'MH (' int2str(curr_block) '/' int2str(options_.mh_nblck) ') ' sprintf('Current acceptance ratio %4.3f', accepted_draws_this_chain/draw_iter)]);
         end
-        if (irun == InitSizeArray(b)) || (j == nruns(b)) % Now I save the simulations
-            save([BaseName '_mh' int2str(NewFile(b)) '_blck' int2str(b) '.mat'],'x2','logpo2');
+        if (draw_index_current_file == InitSizeArray(curr_block)) || (draw_iter == nruns(curr_block)) % Now I save the simulations, either because the current file is full or the chain is done
+            save([BaseName '_mh' int2str(NewFile(curr_block)) '_blck' int2str(curr_block) '.mat'],'x2','logpo2');
             fidlog = fopen([MetropolisFolder '/metropolis.log'],'a');
             fprintf(fidlog,['\n']);
-            fprintf(fidlog,['%% Mh' int2str(NewFile(b)) 'Blck' int2str(b) ' (' datestr(now,0) ')\n']);
+            fprintf(fidlog,['%% Mh' int2str(NewFile(curr_block)) 'Blck' int2str(curr_block) ' (' datestr(now,0) ')\n']);
             fprintf(fidlog,' \n');
             fprintf(fidlog,['  Number of simulations.: ' int2str(length(logpo2)) '\n']);
-            fprintf(fidlog,['  Acceptance ratio......: ' num2str(jsux/length(logpo2)) '\n']);
+            fprintf(fidlog,['  Acceptance ratio......: ' num2str(accepted_draws_this_file/length(logpo2)) '\n']);
             fprintf(fidlog,['  Posterior mean........:\n']);
             for i=1:length(x2(1,:))
                 fprintf(fidlog,['    params:' int2str(i) ': ' num2str(mean(x2(:,i))) '\n']);
@@ -212,32 +195,32 @@ for b = fblck:nblck,
             fprintf(fidlog,['    log2po:' num2str(max(logpo2)) '\n']);
             fprintf(fidlog,' \n');
             fclose(fidlog);
-            jsux = 0;
-            if j == nruns(b) % I record the last draw...
-                record.LastParameters(b,:) = x2(end,:);
-                record.LastLogPost(b) = logpo2(end);
+            accepted_draws_this_file = 0;
+            if draw_iter == nruns(curr_block) % I record the last draw...
+                record.LastParameters(curr_block,:) = x2(end,:);
+                record.LastLogPost(curr_block) = logpo2(end);
             end
-            % size of next file in chain b
-            InitSizeArray(b) = min(nruns(b)-j,MAX_nruns);
+            % size of next file in chain curr_block
+            InitSizeArray(curr_block) = min(nruns(curr_block)-draw_iter,MAX_nruns);
             % initialization of next file if necessary
-            if InitSizeArray(b)
-                x2 = zeros(InitSizeArray(b),npar);
-                logpo2 = zeros(InitSizeArray(b),1);
-                NewFile(b) = NewFile(b) + 1;
-                irun = 0;
+            if InitSizeArray(curr_block)
+                x2 = zeros(InitSizeArray(curr_block),npar);
+                logpo2 = zeros(InitSizeArray(curr_block),1);
+                NewFile(curr_block) = NewFile(curr_block) + 1;
+                draw_index_current_file = 0;
             end
         end
-        j=j+1;
-        irun = irun + 1;
+        draw_iter=draw_iter+1;
+        draw_index_current_file = draw_index_current_file + 1;
     end% End of the simulations for one mh-block.
-    record.AcceptanceRatio(b) = isux/j;
+    record.AcceptanceRatio(curr_block) = accepted_draws_this_chain/draw_iter;
     dyn_waitbar_close(hh);
-    [record.LastSeeds(b).Unifor, record.LastSeeds(b).Normal] = get_dynare_random_generator_state();
-    OutputFileName(jloop,:) = {[MetropolisFolder,filesep], [ModelName '_mh*_blck' int2str(b) '.mat']};
+    [record.LastSeeds(curr_block).Unifor, record.LastSeeds(curr_block).Normal] = get_dynare_random_generator_state();
+    OutputFileName(block_iter,:) = {[MetropolisFolder,filesep], [ModelName '_mh*_blck' int2str(curr_block) '.mat']};
 end% End of the loop over the mh-blocks.
 
 
 myoutput.record = record;
-myoutput.irun = irun;
+myoutput.irun = draw_index_current_file;
 myoutput.NewFile = NewFile;
 myoutput.OutputFileName = OutputFileName;
\ No newline at end of file
diff --git a/matlab/reports/@graph/addSeries.m b/matlab/reports/@graph/addSeries.m
deleted file mode 100644
index 6a0f6d23e5f9be920d63bad549fc38c9f6d14762..0000000000000000000000000000000000000000
--- a/matlab/reports/@graph/addSeries.m
+++ /dev/null
@@ -1,22 +0,0 @@
-function o = addSeries(o, varargin)
-% function o = addSeries(o, varargin)
-
-% Copyright (C) 2013-2014 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/>.
-
-o.series{end+1} = report_series(varargin{:});
-end
\ No newline at end of file
diff --git a/matlab/reports/@graph/display.m b/matlab/reports/@graph/display.m
deleted file mode 100644
index 02ad369e4539678585dab9be8af1a511ed0bb123..0000000000000000000000000000000000000000
--- a/matlab/reports/@graph/display.m
+++ /dev/null
@@ -1,32 +0,0 @@
-function display(o)
-%function display(o)
-% Display a Graph object
-%
-% INPUTS
-%   o   [graph] graph object
-%
-% OUTPUTS
-%   none
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-display_reporting_object(o);
-end
\ No newline at end of file
diff --git a/matlab/reports/@graph/end.m b/matlab/reports/@graph/end.m
deleted file mode 100644
index 9fd4da3a16e38a6681c80573f3ffdb00ba27cee7..0000000000000000000000000000000000000000
--- a/matlab/reports/@graph/end.m
+++ /dev/null
@@ -1,35 +0,0 @@
-function lastIndex = end(o, k, n)
-% function lastIndex = end(o, k, n)
-% End keyword
-%
-% INPUTS
-%   o              [graph]   graph object
-%   k              [integer] index where end appears
-%   n              [integer] number of indices
-%
-% OUTPUTS
-%   lastIndex      [integer] last graph index
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-assert(k==1 && n==1, '@graph/end: graph only has one dimension');
-lastIndex = length(o.series);
-end
\ No newline at end of file
diff --git a/matlab/reports/@graph/graph.m b/matlab/reports/@graph/graph.m
deleted file mode 100644
index 4d73da534628a657db480721dcd9d9c058374cd9..0000000000000000000000000000000000000000
--- a/matlab/reports/@graph/graph.m
+++ /dev/null
@@ -1,216 +0,0 @@
-function o = graph(varargin)
-%function o = graph(varargin)
-% Graph Class Constructor
-%
-% INPUTS
-%   varargin        0 args  : empty graph object
-%                   1 arg   : must be graph object (return a copy of arg)
-%                   > 1 args: option/value pairs (see structure below for
-%                   options)
-%
-% OUTPUTS
-%   o   [graph] graph object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-o = struct;
-
-o.series = {};
-
-o.title = '';
-o.titleFormat = '';
-o.titleFontSize = 'normalsize';
-o.ylabel = '';
-o.xlabel = '';
-
-o.axisShape = 'box';
-
-o.graphDirName = 'tmpRepDir';
-o.graphName = '';
-o.data = '';
-o.seriesToUse = '';
-o.xrange = '';
-o.xAxisTight = true;
-o.yrange = '';
-o.yAxisTight = false;
-
-o.shade = '';
-o.shadeColor = 'green';
-o.shadeOpacity = 20;
-
-o.showGrid = true;
-
-o.showLegend = false;
-o.showLegendBox = false;
-o.legendLocation = 'south east';
-o.legendOrientation = 'horizontal';
-o.legendFontSize = 'tiny';
-
-o.showZeroline = false;
-o.zeroLineColor = 'black';
-
-o.xTicks = [];
-o.xTickLabels = {};
-o.xTickLabelRotation = 0;
-o.xTickLabelAnchor = 'east';
-
-o.yTickLabelScaled = true;
-o.yTickLabelPrecision = 0;
-o.yTickLabelFixed = true;
-o.yTickLabelZeroFill = true;
-
-o.tickFontSize = 'normalsize';
-
-o.width = 6;
-o.height = 4.5;
-
-o.miscTikzPictureOptions = '';
-o.miscTikzAxisOptions = '';
-
-o.writeCSV = false;
-
-if nargin == 1
-    assert(isa(varargin{1}, 'graph'),['@graph.graph: with one arg you ' ...
-                        'must pass a graph object']);
-    o = varargin{1};
-    return;
-elseif nargin > 1
-    if round(nargin/2) ~= nargin/2
-        error(['@graph.graph: options must be supplied in name/value ' ...
-               'pairs.']);
-    end
-
-    optNames = fieldnames(o);
-
-    % overwrite default values
-    for pair = reshape(varargin, 2, [])
-        ind = find(strcmpi(optNames, pair{1}));
-        assert(isempty(ind) || length(ind) == 1);
-        if ~isempty(ind)
-            o.(optNames{ind}) = pair{2};
-        else
-            error('@graph.graph: %s is not a recognized option.', pair{1});
-        end
-    end
-end
-
-% Check options provided by user
-if ischar(o.title)
-    o.title = {o.title};
-end
-assert(iscellstr(o.title), '@graph.graph: title must be a cell array of string(s)');
-assert(ischar(o.titleFormat), '@graph.graph: titleFormat file must be a string');
-assert(ischar(o.xlabel), '@graph.graph: xlabel file must be a string');
-assert(ischar(o.ylabel), '@graph.graph: ylabel file must be a string');
-assert(ischar(o.miscTikzPictureOptions), '@graph.graph: miscTikzPictureOptions file must be a string');
-assert(ischar(o.miscTikzAxisOptions), '@graph.graph: miscTikzAxisOptions file must be a string');
-assert(ischar(o.graphName), '@graph.graph: graphName must be a string');
-assert(ischar(o.graphDirName), '@graph.graph: graphDirName must be a string');
-assert(islogical(o.showGrid), '@graph.graph: showGrid must be either true or false');
-assert(islogical(o.xAxisTight), '@graph.graph: xAxisTight must be either true or false');
-assert(islogical(o.yAxisTight), '@graph.graph: yAxisTight must be either true or false');
-assert(islogical(o.showLegend), '@graph.graph: showLegend must be either true or false');
-assert(islogical(o.showLegendBox), '@graph.graph: showLegendBox must be either true or false');
-assert(islogical(o.showZeroline), '@graph.graph: showZeroline must be either true or false');
-assert(isfloat(o.shadeOpacity) && length(o.shadeOpacity)==1 && ...
-       o.shadeOpacity >= 0 && o.shadeOpacity <= 100, ...
-       '@graph.graph: o.shadeOpacity must be a real in [0 100]');
-assert(isfloat(o.width), '@graph.graph: o.width must be a real number');
-assert(isfloat(o.height), '@graph.graph: o.height must be a real number');
-assert(isfloat(o.xTickLabelRotation), '@graph.graph: o.xTickLabelRotation must be a real number');
-assert(ischar(o.xTickLabelAnchor), '@graph.graph: xTickLabelAnchor must be a string');
-assert(isint(o.yTickLabelPrecision), '@graph.graph: o.yTickLabelPrecision must be an integer');
-assert(islogical(o.yTickLabelFixed), '@graph.graph: yTickLabelFixed must be either true or false');
-assert(islogical(o.yTickLabelZeroFill), '@graph.graph: yTickLabelZeroFill must be either true or false');
-assert(islogical(o.yTickLabelScaled), '@graph.graph: yTickLabelScaled must be either true or false');
-assert(islogical(o.writeCSV), '@graph.graph: writeCSV must be either true or false');
-assert(ischar(o.shadeColor), '@graph.graph: shadeColor must be a string');
-assert(ischar(o.zeroLineColor), '@graph.graph: zeroLineColor must be a string');
-assert(any(strcmp(o.axisShape, {'box', 'L'})), ['@graph.graph: axisShape ' ...
-                    'must be one of ''box'' or ''L''']);
-valid_legend_locations = ...
-    {'south west','south east','north west','north east','outer north east'};
-assert(any(strcmp(o.legendLocation, valid_legend_locations)), ...
-       ['@graph.graph: legendLocation must be one of ' strjoin(valid_legend_locations, ' ')]);
-
-valid_font_sizes = {'tiny', 'scriptsize', 'footnotesize', 'small', ...
-                    'normalsize', 'large', 'Large', 'LARGE', 'huge', 'Huge'};
-assert(any(strcmp(o.legendFontSize, valid_font_sizes)), ...
-       ['@graph.graph: legendFontSize must be one of ' strjoin(valid_font_sizes)]);
-assert(any(strcmp(o.titleFontSize, valid_font_sizes)), ...
-       ['@graph.graph: titleFontSize must be one of ' strjoin(valid_font_sizes)]);
-assert(any(strcmp(o.tickFontSize, valid_font_sizes)), ...
-       ['@graph.graph: tickFontSize must be one of ' strjoin(valid_font_sizes)]);
-
-valid_legend_orientations = {'vertical', 'horizontal'};
-assert(any(strcmp(o.legendOrientation, valid_legend_orientations)), ...
-       ['@graph.graph: legendOrientation must be one of ' strjoin(valid_legend_orientations, ' ')]);
-
-assert(isempty(o.shade) || (isdates(o.shade) && o.shade.ndat >= 2), ...
-       ['@graph.graph: shade is specified as a dates range, e.g. ' ...
-        '''dates(''1999q1''):dates(''1999q3'')''.']);
-assert(isempty(o.xrange) || (isdates(o.xrange) && o.xrange.ndat >= 2), ...
-       ['@graph.graph: xrange is specified as a dates range, e.g. ' ...
-        '''dates(''1999q1''):dates(''1999q3'')''.']);
-assert(isempty(o.yrange) || (isfloat(o.yrange) && length(o.yrange) == 2 && ...
-                             o.yrange(1) < o.yrange(2)), ...
-       ['@graph.graph: yrange is specified an array with two float entries, ' ...
-        'the lower bound and upper bound.']);
-assert(isempty(o.data) || isdseries(o.data), ['@graph.graph: data must ' ...
-                    'be a dseries']);
-assert(isempty(o.seriesToUse) || iscellstr(o.seriesToUse), ['@graph.graph: ' ...
-                    'seriesToUse must be a cell array of string(s)']);
-assert(isempty(o.xTicks) || isfloat(o.xTicks),...
-       '@graph.graph: xTicks must be a numerical array');
-assert(iscellstr(o.xTickLabels) || (ischar(o.xTickLabels) && strcmpi(o.xTickLabels, 'ALL')), ...
-       ['@graph.graph: xTickLabels must be a cell array of strings or ' ...
-        'equivalent to the string ''ALL''']);
-if ~isempty(o.xTickLabels)
-    assert((ischar(o.xTickLabels) && strcmpi(o.xTickLabels, 'ALL')) || ...
-            ~isempty(o.xTicks), ['@graph.graph: if you set xTickLabels and ' ...
-                        'it''s not equal to ''ALL'', you must set xTicks']);
-end
-if ~isempty(o.xTicks)
-    assert(~isempty(o.xTickLabels), '@graph.graph: if you set xTicks, you must set xTickLabels');
-end
-
-% using o.seriesToUse, create series objects and put them in o.series
-if ~isempty(o.data)
-    if isempty(o.seriesToUse)
-        for i=1:o.data.vobs
-            o.series{end+1} = report_series('data', o.data{o.data.name{i}});
-        end
-    else
-        for i=1:length(o.seriesToUse)
-            o.series{end+1} = report_series('data', o.data{o.seriesToUse{i}});
-        end
-    end
-end
-o = rmfield(o, 'seriesToUse');
-o = rmfield(o, 'data');
-
-if ~exist(o.graphDirName, 'file')
-    mkdir(o.graphDirName);
-end
-
-% Create graph object
-o = class(o, 'graph');
-end
\ No newline at end of file
diff --git a/matlab/reports/@graph/subsasgn.m b/matlab/reports/@graph/subsasgn.m
deleted file mode 100644
index 2048ab408cd5ec53f47add2acf95c770c76ff7d8..0000000000000000000000000000000000000000
--- a/matlab/reports/@graph/subsasgn.m
+++ /dev/null
@@ -1,49 +0,0 @@
-function B = subsasgn(A, S, V)
-% function B = subsasgn(A, S, V)
-
-% Copyright (C) 2013-2014 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/>.
-
-B = A;
-if length(S) > 1
-    for i=1:(length(S)-1)
-        B = subsref(B, S(i));
-    end
-    B = subsasgn(B, S(end), V);
-    B = subsasgn(A, S(1:(end-1)), B);
-    return
-end
-
-switch S.type
-    case '()'
-        index = S.subs{:};
-        assert(isnumeric(index));
-        B.series{index} = V;
-    case '.'
-        switch S.subs
-            case fieldnames(A)
-                B.(S.subs) = V;
-            otherwise
-                error(['@graph.subsasgn: field ' S.subs 'does not exist']);
-        end
-    case '{}'
-        assert(isint(S.subs{1}));
-        B{S.subs{1}} = V;
-    otherwise
-        error('@graph.subsasgn: syntax error');
-end
-end
\ No newline at end of file
diff --git a/matlab/reports/@graph/subsref.m b/matlab/reports/@graph/subsref.m
deleted file mode 100644
index 6643f3f56e9461d789be65475efdf3eb2bef4652..0000000000000000000000000000000000000000
--- a/matlab/reports/@graph/subsref.m
+++ /dev/null
@@ -1,53 +0,0 @@
-function A = subsref(A, S)
-%function A = subsref(A, S)
-
-% Copyright (C) 2013-2014 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/>.
-
-switch S(1).type
-    case '.'
-        switch S(1).subs
-            case fieldnames(A)
-                A = A.(S(1).subs);
-            case methods(A)
-                if areParensNext(S)
-                    A = feval(S(1).subs, A, S(2).subs{:});
-                    S = shiftS(S,1);
-                else
-                    A = feval(S(1).subs, A);
-                end
-            otherwise
-                error(['@graph.subsref: unknown field or method: ' S(1).subs]);
-        end
-    case '()'
-        if isempty(S(1).subs{:})
-            A = A.series;
-        else
-            assert(isnumeric(S(1).subs{:}));
-            A = A.series{S(1).subs{:}};
-        end
-    case '{}'
-        A = A.series{S(1).subs{:}};
-    otherwise
-        error('@graph.subsref: impossible case')
-end
-
-S = shiftS(S,1);
-if length(S) >= 1
-    A = subsref(A, S);
-end
-end
diff --git a/matlab/reports/@graph/write.m b/matlab/reports/@graph/write.m
deleted file mode 100644
index bdb91a117866e88d54cf0539e5ec330bd1ce9eff..0000000000000000000000000000000000000000
--- a/matlab/reports/@graph/write.m
+++ /dev/null
@@ -1,39 +0,0 @@
-function o = write(o, fid, pg, sec, row, col)
-%function o = write(o, fid, pg, sec, row, col)
-% Write a Graph object
-%
-% INPUTS
-%   o   [graph]   graph object
-%   fid [integer] file id
-%   pg  [integer] this page number
-%   sec [integer] this section number
-%   row [integer] this row number
-%   col [integer] this col number
-%
-% OUTPUTS
-%   o   [graph] graph object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-assert(fid ~= -1);
-o = writeGraphFile(o, pg, sec, row, col);
-fprintf(fid, '\\input{%s}', o.graphName);
-end
\ No newline at end of file
diff --git a/matlab/reports/@graph/writeGraphFile.m b/matlab/reports/@graph/writeGraphFile.m
deleted file mode 100644
index 85b09d41d3c2b8b3efc923d8758132e9f495e76d..0000000000000000000000000000000000000000
--- a/matlab/reports/@graph/writeGraphFile.m
+++ /dev/null
@@ -1,267 +0,0 @@
-function o = writeGraphFile(o, pg, sec, row, col)
-%function o = writeGraphFile(o, pg, sec, row, col)
-% Write the tikz file that contains the graph
-%
-% INPUTS
-%   o   [graph]   graph object
-%   pg  [integer] this page number
-%   sec [integer] this section number
-%   row [integer] this row number
-%   col [integer] this col number
-%
-% OUTPUTS
-%   o   [graph] graph object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-ne = length(o.series);
-if ne < 1
-    warning('@graph.writeGraphFile: no series to plot, returning');
-    return;
-end
-
-if isempty(o.graphName)
-    o.graphName = sprintf('%s/graph_pg%d_sec%d_row%d_col%d.tex', o.graphDirName, pg, sec, row, col);
-else
-    o.graphName = [o.graphDirName '/' o.graphName];
-end
-
-[fid, msg] = fopen(o.graphName, 'w');
-if fid == -1
-    error(['@graph.writeGraphFile: ' msg]);
-end
-
-fprintf(fid, '\\begin{tikzpicture}[baseline');
-if ~isempty(o.miscTikzPictureOptions)
-    fprintf(fid, ',%s', o.miscTikzPictureOptions);
-end
-fprintf(fid, ']');
-
-if isempty(o.xrange)
-    dd = getMaxRange(o.series);
-else
-    dd = o.xrange;
-end
-
-fprintf(fid, '\\begin{axis}[%%\n');
-% set tick labels
-if isempty(o.xTickLabels)
-    stringsdd = strings(dd);
-    if ~isempty(o.shade)
-        x1 = find(strcmpi(date2string(o.shade(1)), stringsdd));
-        x2 = find(strcmpi(date2string(o.shade(end)), stringsdd));
-        if x1 == 1
-            x = [1 x2 dd.ndat];
-            xTickLabels = [stringsdd(1) stringsdd(x2) stringsdd(end)];
-        elseif x2 == dd.ndat
-            x = [1 x1 dd.ndat];
-            xTickLabels = [stringsdd(1) stringsdd(x1) stringsdd(end)];
-        else
-            x = [1 x1 x2 dd.ndat];
-            xTickLabels = [stringsdd(1) stringsdd(x1) stringsdd(x2) stringsdd(end)];
-        end
-    else
-        x = [1 dd.ndat];
-        xTickLabels = [stringsdd(1) stringsdd(end)];
-    end
-    fprintf(fid, 'xminorticks=true,\nyminorticks=true,\n');
-elseif iscell(o.xTickLabels)
-    fprintf(fid,'minor xtick,\n');
-    x = o.xTicks;
-    xTickLabels = o.xTickLabels;
-else
-    x = [1:dd.ndat];
-    xTickLabels = strings(dd);
-end
-fprintf(fid, 'xticklabels={');
-xlen = length(x);
-for i = 1:xlen
-    fprintf(fid,'%s,',lower(xTickLabels{i}));
-end
-fprintf(fid, '},\nxtick={');
-for i = 1:xlen
-    fprintf(fid, '%d',x(i));
-    if i ~= length(x)
-        fprintf(fid,',');
-    end
-end
-fprintf(fid, '},\ny tick label style={\n/pgf/number format/.cd,\n');
-if o.yTickLabelFixed
-    fprintf(fid, 'fixed,\n');
-end
-if o.yTickLabelZeroFill
-    fprintf(fid, 'zerofill,\n');
-end
-fprintf(fid, 'precision=%d,\n/tikz/.cd\n},\n', o.yTickLabelPrecision);
-fprintf(fid, 'x tick label style={rotate=%f', o.xTickLabelRotation);
-if o.xTickLabelRotation ~= 0
-    fprintf(fid, ',anchor=%s', o.xTickLabelAnchor);
-end
-fprintf(fid, ['},\n',...
-              'width=%fin,\n'...
-              'height=%fin,\n'...
-              'scale only axis,\n'...
-              'unbounded coords=jump,\n'], o.width, o.height);
-
-if strcmpi(o.axisShape, 'box')
-    fprintf(fid, 'axis lines=box,\n');
-elseif strcmpi(o.axisShape, 'L')
-    fprintf(fid, 'axis x line=bottom,\naxis y line=left,\n');
-end
-
-if ~isempty(o.title{1})
-    fprintf(fid, 'title style={align=center');
-    if ~isempty(o.titleFormat)
-        fprintf(fid, ',font=%s', o.titleFormat);
-    end
-    fprintf(fid, '},\ntitle=');
-    nt = length(o.title);
-    for i=1:nt
-        fprintf(fid, '%s', o.title{i});
-        if i ~= nt
-            fprintf(fid, '\\\\');
-        end
-    end
-    fprintf(fid, ',\n');
-end
-
-if o.xAxisTight
-    fprintf(fid, 'enlarge x limits=false,\n');
-else
-    fprintf(fid, 'enlarge x limits=true,\n');
-end
-
-if isempty(o.yrange)
-    if o.yAxisTight
-        fprintf(fid, 'enlarge y limits=false,\n');
-    else
-        fprintf(fid, 'enlarge y limits=true,\n');
-    end
-else
-    fprintf(fid, 'ymin=%f,\nymax=%f,\n',o.yrange(1),o.yrange(2));
-end
-fprintf(fid, 'xmin = 1,\nxmax = %d,\n', length(dd));
-
-if o.showLegend
-    fprintf(fid, 'legend style={');
-    if ~o.showLegendBox
-        fprintf(fid, 'draw=none,');
-    end
-    fprintf(fid, 'font=\\%s,', o.legendFontSize);
-    if strcmp(o.legendOrientation, 'horizontal')
-        fprintf(fid,'legend columns=-1,');
-    end
-    fprintf(fid, '},\nlegend pos=%s,\n', o.legendLocation);
-end
-
-fprintf(fid, 'tick label style={font=\\%s},\n', o.tickFontSize);
-
-if o.showGrid
-    fprintf(fid, 'xmajorgrids=true,\nymajorgrids=true,\n');
-end
-
-if ~isempty(o.xlabel)
-    fprintf(fid, 'xlabel=%s,\n', o.xlabel);
-end
-
-if ~isempty(o.ylabel)
-    fprintf(fid, 'ylabel=%s,\n', o.ylabel);
-end
-
-if ~o.yTickLabelScaled
-    fprintf(fid, 'scaled y ticks = false,\n');
-end
-
-if ~isempty(o.miscTikzAxisOptions)
-    fprintf(fid, '%s', o.miscTikzAxisOptions);
-end
-fprintf(fid, ']\n');
-
-if ~isempty(o.title{1})
-    fprintf(fid, '\\pgfplotsset{every axis title/.append style={}}=[font=\\%s]\n', o.titleFontSize);
-end
-
-if ~isempty(o.shade)
-    fprintf(fid, '%%shading\n');
-    stringsdd = strings(dd);
-    x1 = find(strcmpi(date2string(o.shade(1)), stringsdd));
-    x2 = find(strcmpi(date2string(o.shade(end)), stringsdd));
-    assert(~isempty(x1) && ~isempty(x2), ['@graph.writeGraphFile: either ' ...
-                        date2string(o.shade(1)) ' or ' date2string(o.shade(end)) ' is not in the date ' ...
-                        'range of data selected.']);
-    if x1 == 1
-        fprintf(fid,['\\begin{pgfonlayer}{background0}\n\\fill[%s!%f]\n(axis ' ...
-                     'cs:\\pgfkeysvalueof{/pgfplots/xmin},\\pgfkeysvalueof{/pgfplots/ymin})\nrectangle (axis ' ...
-                     'cs:%f,\\pgfkeysvalueof{/pgfplots/ymax});\n\\end{pgfonlayer}\n'], ...
-                o.shadeColor, o.shadeOpacity, x2);
-    elseif x2 == dd.ndat
-        fprintf(fid,['\\begin{pgfonlayer}{background0}\n\\fill[%s!%f]\n(axis ' ...
-                     'cs:%f,\\pgfkeysvalueof{/pgfplots/ymin})\nrectangle (axis ' ...
-                     'cs:\\pgfkeysvalueof{/pgfplots/xmax},\\pgfkeysvalueof{/' ...
-                     'pgfplots/ymax});\n\\end{pgfonlayer}\n'], ...
-                o.shadeColor, o.shadeOpacity, x1);
-    else
-        fprintf(fid,['\\begin{pgfonlayer}{background0}\n\\fill[%s!%f]\n(axis ' ...
-                     'cs:%f,\\pgfkeysvalueof{/pgfplots/ymin})\nrectangle (axis ' ...
-                     'cs:%f,\\pgfkeysvalueof{/pgfplots/ymax});\n\\end{pgfonlayer}\n'], ...
-                o.shadeColor, o.shadeOpacity, x1, x2);
-    end
-end
-
-if o.showZeroline
-    fprintf(fid, '%%zeroline\n\\addplot[%s,line width=.5,forget plot] coordinates {(1,0)(%d,0)};\n', ...
-        o.zeroLineColor, dd.ndat);
-end
-
-if o.writeCSV
-    csvseries = dseries();
-end
-for i=1:ne
-    o.series{i}.writeSeriesForGraph(fid, dd);
-    if o.writeCSV
-        csvseries = [csvseries ...
-            o.series{i}.data(dd).set_names([...
-            o.series{i}.data.name{:} '_' ...
-            o.series{i}.graphLegendName '_' ...
-            o.series{i}.graphLineColor '_' ...
-            o.series{i}.graphLineStyle '_' ...
-            num2str(o.series{i}.graphLineWidth) '_' ...
-            o.series{i}.graphMarker '_' ...
-            o.series{i}.graphMarkerEdgeColor '_' ...
-            o.series{i}.graphMarkerFaceColor '_' ...
-            num2str(o.series{i}.graphMarkerSize)]) ...
-            ];
-    end
-    if o.showLegend
-        le = o.series{i}.getNameForLegend();
-        if ~isempty(le)
-            fprintf(fid, '\\addlegendentry{%s}\n', le);
-        end
-    end
-end
-if o.writeCSV
-    csvseries.save(strrep(o.graphName, '.tex', ''), 'csv');
-end
-fprintf(fid, '\\end{axis}\n\\end{tikzpicture}%%');
-if fclose(fid) == -1
-    error('@graph.writeGraphFile: closing %s\n', o.filename);
-end
-end
\ No newline at end of file
diff --git a/matlab/reports/@page/addSection.m b/matlab/reports/@page/addSection.m
deleted file mode 100644
index a99ffc22a95117b1a9def0b3feb69c929b2d6c51..0000000000000000000000000000000000000000
--- a/matlab/reports/@page/addSection.m
+++ /dev/null
@@ -1,34 +0,0 @@
-function p = addSection(p, varargin)
-%function p = addSection(p, varargin)
-% Add a section to the Cell Array of sections in the report
-%
-% INPUTS
-%   1 args => add empty section
-%   2 args => add given section
-%   3 args => add section at index
-%
-% OUTPUTS
-%   updated page object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-p.sections{end+1} = section(varargin{:});
-end
diff --git a/matlab/reports/@page/end.m b/matlab/reports/@page/end.m
deleted file mode 100644
index 073a271b44a9f008bb52975bbacef6bc54a7a129..0000000000000000000000000000000000000000
--- a/matlab/reports/@page/end.m
+++ /dev/null
@@ -1,35 +0,0 @@
-function lastIndex = end(o, k, n)
-% function lastIndex = end(o, k, n)
-% End keyword
-%
-% INPUTS
-%   o              [page]    page object
-%   k              [integer] index where end appears
-%   n              [integer] number of indices
-%
-% OUTPUTS
-%   lastIndex      [integer] last sections index
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013 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/>.
-
-assert(k==1 && n==1, '@page/end: page only has one dimension');
-lastIndex = numSections(o);
-end
\ No newline at end of file
diff --git a/matlab/reports/@page/numSections.m b/matlab/reports/@page/numSections.m
deleted file mode 100644
index aa0b0a1bed8052a87079e6bdfbd825041affa82e..0000000000000000000000000000000000000000
--- a/matlab/reports/@page/numSections.m
+++ /dev/null
@@ -1,32 +0,0 @@
-function ns = numSections(p)
-%function ns = numSections(p)
-% return the number of sections currently in the page
-%
-% INPUTS
-%   none
-%
-% OUTPUTS
-%   none
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-ns = length(p.sections);
-end
\ No newline at end of file
diff --git a/matlab/reports/@page/page.m b/matlab/reports/@page/page.m
deleted file mode 100644
index 99442c777a05f1c7b2309794ba48a673cbf8ac72..0000000000000000000000000000000000000000
--- a/matlab/reports/@page/page.m
+++ /dev/null
@@ -1,97 +0,0 @@
-function o = page(varargin)
-%function o = page(varargin)
-% Page Class Constructor
-%
-% INPUTS
-%   0 args => empty page
-%   1 arg (page class) => copy object
-%
-% OUTPUTS
-%   none
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-o = struct;
-o.paper = '';
-o.title = {''};
-titleFormatDefalut = {'\large\bfseries'};
-o.titleFormat = titleFormatDefalut;
-o.orientation = '';
-o.footnote = {};
-o.sections = {};
-
-if nargin == 1
-    assert(isa(varargin{1}, 'page'), ['@page.page: with one arg to Page ' ...
-                        'constructor, you must pass a page object']);
-    o = varargin{1};
-    return;
-elseif nargin > 1
-    if round(nargin/2) ~= nargin/2
-        error(['@page.page: options must be supplied in name/value ' ...
-               'pairs.']);
-    end
-
-    optNames = fieldnames(o);
-
-    % overwrite default values
-    for pair = reshape(varargin, 2, [])
-        ind = find(strcmpi(optNames, pair{1}));
-        assert(isempty(ind) || length(ind) == 1);
-        if ~isempty(ind)
-            o.(optNames{ind}) = pair{2};
-        else
-            error('@page.page: %s is not a recognized option.', pair{1});
-        end
-    end
-end
-
-% Check options provided by user
-if ischar(o.title)
-    o.title = {o.title};
-end
-if ischar(o.titleFormat)
-    o.titleFormat = {o.titleFormat};
-end
-if length(o.title) ~= length(o.titleFormat)
-    o.titleFormat = repmat(titleFormatDefalut, 1, length(o.title));
-end
-assert(iscellstr(o.title), ...
-       '@page.page: title must be a cell array of strings');
-assert(iscellstr(o.titleFormat), ...
-       '@page.page: titleFormat must be a cell array of strings');
-
-valid_paper = {'a4', 'letter'};
-assert(any(strcmp(o.paper, valid_paper)), ...
-       ['@page.page: paper must be one of ' strjoin(valid_paper, ' ')]);
-
-valid_orientation = {'portrait', 'landscape'};
-assert(any(strcmp(o.orientation, valid_orientation)), ...
-       ['@page.page: orientation must be one of ' strjoin(valid_orientation, ' ')]);
-
-if ischar(o.footnote)
-    o.footnote = {o.footnote};
-end
-assert(iscellstr(o.footnote), ...
-       '@page.page: footnote must be a cell array of string(s)');
-
-% Create page object
-o = class(o, 'page');
-end
diff --git a/matlab/reports/@page/subsasgn.m b/matlab/reports/@page/subsasgn.m
deleted file mode 100644
index 00e85ae2d325eef678942aef2970db4acbab0f90..0000000000000000000000000000000000000000
--- a/matlab/reports/@page/subsasgn.m
+++ /dev/null
@@ -1,46 +0,0 @@
-function B = subsasgn(A, S, V)
-% function B = subsasgn(A, S, V)
-
-% Copyright (C) 2013 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/>.
-
-B = A;
-if length(S) > 1
-    for i=1:(length(S)-1)
-        B = subsref(B, S(i));
-    end
-    B = subsasgn(B, S(end), V);
-    B = subsasgn(A, S(1:(end-1)), B);
-    return
-end
-
-switch S.type
-    case '()'
-        index = S.subs{:};
-        assert(isnumeric(index));
-        B{index} = V;
-    case '.'
-        switch S.subs
-            case fieldnames(A)
-                B.(S.subs) = V;
-            otherwise
-                error(['@page.subsasgn: field ' S.subs 'does not exist']);
-        end
-    otherwise
-        error('@page.subsasgn: syntax error');
-end
-end
\ No newline at end of file
diff --git a/matlab/reports/@page/subsref.m b/matlab/reports/@page/subsref.m
deleted file mode 100644
index 7ad0befc87629eabcd1497e7ab79ce9f6b23027d..0000000000000000000000000000000000000000
--- a/matlab/reports/@page/subsref.m
+++ /dev/null
@@ -1,48 +0,0 @@
-function A = subsref(A, S)
-%function A = subsref(A, S)
-
-% Copyright (C) 2013-2014 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/>.
-
-switch S(1).type
-    case '.'
-        switch S(1).subs
-            case fieldnames(A)
-                A = A.(S(1).subs);
-            case methods(A)
-                if areParensNext(S)
-                    A = feval(S(1).subs, A, S(2).subs{:});
-                    S = shiftS(S,1);
-                else
-                    A = feval(S(1).subs, A);
-                end
-            otherwise
-                error(['@page.subsref: unknown field or method: ' S(1).subs]);
-        end
-    case '()'
-        A = getSections(A, S(1).subs{:});
-    case '{}'
-        error(['@page.subsref: ' S(1).type ' indexing not supported.']);
-    otherwise
-        error('@page.subsref: impossible case')
-end
-
-S = shiftS(S,1);
-if length(S) >= 1
-    A = subsref(A, S);
-end
-end
diff --git a/matlab/reports/@page/write.m b/matlab/reports/@page/write.m
deleted file mode 100644
index 6ef822ae3fd5aac441fdf61d249c4553db2e155c..0000000000000000000000000000000000000000
--- a/matlab/reports/@page/write.m
+++ /dev/null
@@ -1,61 +0,0 @@
-function o = write(o, fid, pg)
-%function o = write(o, fid, pg)
-% Write a Page object
-%
-% INPUTS
-%   o              [page]     page object
-%   fid            [integer]  file id
-%   pg             [integer]  this page number
-%
-% OUTPUTS
-%   o              [page]     page object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-assert(fid ~= -1);
-
-fprintf(fid, '\n%% Page Object\n');
-if strcmpi(o.orientation, 'landscape')
-    fprintf(fid, '\\begin{landscape}\n');
-end
-
-for i=1:length(o.footnote)
-    fprintf(fid, '\\blfootnote{\\tiny %d. %s}', i, o.footnote{i});
-end
-fprintf(fid,'\n');
-
-fprintf(fid, '\\begin{tabular}[t]{c}\n');
-for i=1:length(o.title)
-    fprintf(fid,'\\multicolumn{1}{c}{%s %s}\\\\\n', o.titleFormat{i}, o.title{i});
-end
-
-nps = length(o.sections);
-for i=1:nps
-    o.sections{i}.write(fid, pg, i);
-end
-
-fprintf(fid, '\\end{tabular}\n');
-if strcmpi(o.orientation, 'landscape')
-    fprintf(fid, '\\end{landscape}\n');
-end
-fprintf(fid, '\\clearpage\n');
-fprintf(fid, '%% End Page Object\n\n');
-end
\ No newline at end of file
diff --git a/matlab/reports/@paragraph/display.m b/matlab/reports/@paragraph/display.m
deleted file mode 100644
index f731c9c5d90a7ea8b64f0711070e39a325d41143..0000000000000000000000000000000000000000
--- a/matlab/reports/@paragraph/display.m
+++ /dev/null
@@ -1,32 +0,0 @@
-function display(o)
-%function display(o)
-% Display a Paragraph object
-%
-% INPUTS
-%   o   [paragraph] paragraph object
-%
-% OUTPUTS
-%   none
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2014 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/>.
-
-display_reporting_object(o);
-end
\ No newline at end of file
diff --git a/matlab/reports/@paragraph/paragraph.m b/matlab/reports/@paragraph/paragraph.m
deleted file mode 100644
index 4cf6106b284bba91605dc86a45a1fb506a9beffd..0000000000000000000000000000000000000000
--- a/matlab/reports/@paragraph/paragraph.m
+++ /dev/null
@@ -1,63 +0,0 @@
-function o = paragraph(varargin)
-%function o = paragraph(varargin)
-% Instantiates a paragraph object
-
-% Copyright (C) 2014 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/>.
-
-o = struct;
-
-o.balancedCols = false;
-o.cols = 1;
-o.heading = '';
-o.indent = true;
-o.text = '';
-
-if nargin == 1
-    assert(isa(varargin{1}, 'paragraph'),['With one arg to Paragraph constructor, ' ...
-                        'you must pass a paragraph object']);
-    o = varargin{1};
-    return;
-elseif nargin > 1
-    if round(nargin/2) ~= nargin/2
-        error(['@paragraph.paragraph: options must be supplied in name/value ' ...
-               'pairs.']);
-    end
-
-    optNames = fieldnames(o);
-
-    % overwrite default values
-    for pair = reshape(varargin, 2, [])
-        ind = find(strcmpi(optNames, pair{1}));
-        assert(isempty(ind) || length(ind) == 1);
-        if ~isempty(ind)
-            o.(optNames{ind}) = pair{2};
-        else
-            error('@paragraph.paragraph: %s is not a recognized option.', pair{1});
-        end
-    end
-end
-
-assert(islogical(o.indent), '@paragraph.paragraph: indent must be either true or false');
-assert(islogical(o.balancedCols), '@paragraph.paragraph: balancedCols must be either true or false');
-assert(isint(o.cols), '@paragraph.paragraph: cols must be an integer');
-assert(ischar(o.text), '@paragraph.paragraph: text must be a string');
-assert(ischar(o.heading), '@paragraph.paragraph: heading must be a string');
-
-% Create paragraph object
-o = class(o, 'paragraph');
-end
diff --git a/matlab/reports/@paragraph/subsasgn.m b/matlab/reports/@paragraph/subsasgn.m
deleted file mode 100644
index 429c48ccdf26cb8ab2d7924d5511428f66018429..0000000000000000000000000000000000000000
--- a/matlab/reports/@paragraph/subsasgn.m
+++ /dev/null
@@ -1,50 +0,0 @@
-function B = subsasgn(A, S, V)
-% function B = subsasgn(A, S, V)
-
-% Copyright (C) 2014 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/>.
-
-B = A;
-if length(S) > 1
-    for i=1:(length(S)-1)
-        B = subsref(B, S(i));
-    end
-    B = subsasgn(B, S(end), V);
-    B = subsasgn(A, S(1:(end-1)), B);
-    return
-end
-
-switch S.type
-    case '()'
-        index = S.subs{:};
-        assert(isnumeric(index));
-        B.elements{index} = V;
-    case '{}'
-        index = S.subs{:};
-        assert(isnumeric(index));
-        B{index} = V;
-    case '.'
-        switch S.subs
-            case fieldnames(A)
-                B.(S.subs) = V;
-            otherwise
-                error(['@paragraph.subsasgn: field ' S.subs 'does not exist']);
-        end
-    otherwise
-        error('@paragraph.subsasgn: syntax error');
-end
-end
\ No newline at end of file
diff --git a/matlab/reports/@paragraph/subsref.m b/matlab/reports/@paragraph/subsref.m
deleted file mode 100644
index f3dd2c55be96135cdd3eb8bdc135db0214d3b675..0000000000000000000000000000000000000000
--- a/matlab/reports/@paragraph/subsref.m
+++ /dev/null
@@ -1,48 +0,0 @@
-function A = subsref(A, S)
-%function A = subsref(A, S)
-
-% Copyright (C) 2014 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/>.
-
-switch S(1).type
-    case '.'
-        switch S(1).subs
-            case fieldnames(A)
-                A = A.(S(1).subs);
-            case methods(A)
-                if areParensNext(S)
-                    A = feval(S(1).subs, A, S(2).subs{:});
-                    S = shiftS(S,1);
-                else
-                    A = feval(S(1).subs, A);
-                end
-            otherwise
-                error(['@paragraph.subsref: unknown field or method: ' S(1).subs]);
-        end
-    case '()'
-        A = A.elements{S(1).subs{:}};
-    case '{}'
-        error(['@paragraph.subsref: ' S(1).type ' indexing not supported.']);
-    otherwise
-        error('@paragraph.subsref: impossible case')
-end
-
-S = shiftS(S,1);
-if length(S) >= 1
-    A = subsref(A, S);
-end
-end
diff --git a/matlab/reports/@paragraph/write.m b/matlab/reports/@paragraph/write.m
deleted file mode 100644
index 3397b44a11d8a1cd9867c2d0e95015743e855339..0000000000000000000000000000000000000000
--- a/matlab/reports/@paragraph/write.m
+++ /dev/null
@@ -1,70 +0,0 @@
-function o = write(o, fid)
-%function o = write(o, fid)
-% Write Paragraph object
-%
-% INPUTS
-%   o         [paragraph] paragraph object
-%   fid       [integer] file id
-%
-% OUTPUTS
-%   o         [paragraph] paragraph object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2014 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/>.
-
-assert(fid ~= -1);
-fprintf(fid, '%% Paragraph Object\n\\multicolumn{1}{p{\\textwidth}}{%%\n');
-if o.cols ~= 1
-    bc = '';
-    if o.balancedCols
-        bc = '*';
-    end
-    fprintf(fid, '\\begin{multicols%s}{%d}%%\n', bc, o.cols);
-end
-
-if ~isempty(o.heading)
-    if o.cols ~= 1
-        fprintf(fid, '[%s\n]\n', o.heading);
-    else
-        fprintf(fid, '%s\\newline \\newline\n', o.heading);
-    end
-end
-
-if o.indent
-    fprintf(fid, '\\hspace{4ex}');
-end
-
-fprintf(fid, '%s', o.text);
-
-if o.cols ~= 1
-    fprintf(fid, '\\end{multicols%s}\n', bc);
-end
-fprintf(fid, '}\n%% End Paragraph Object\n\n');
-end
-
-
-%\multicolumn{1}{p{\textwidth}}
-%{\begin{multicols}{2}
-%Hello, here is some text without a meaning.  This text should show what 
-%a printed text will look like at this place.
-%\columnbreak
-%If you read this text, you will get no information.  Really?  Is there 
-%no information?  Is there...
-%\end{multicols}}\\
\ No newline at end of file
diff --git a/matlab/reports/@report/addGraph.m b/matlab/reports/@report/addGraph.m
deleted file mode 100644
index 9e0e691e88cad9e5adcb238c5c946388c7cb7520..0000000000000000000000000000000000000000
--- a/matlab/reports/@report/addGraph.m
+++ /dev/null
@@ -1,34 +0,0 @@
-function o = addGraph(o, varargin)
-%function o = addGraph(o, varargin)
-% Add a graph to the current section of the current page in the report
-%
-% INPUTS
-%   o          [report]  report object
-%   varargin             arguments to @section/addGraph.m
-%
-% OUTPUTS
-%   o          [report]  updated report object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-o.pages{end}.sections{end} = ...
-    o.pages{end}.sections{end}.addGraph(varargin{:});
-end
diff --git a/matlab/reports/@report/addPage.m b/matlab/reports/@report/addPage.m
deleted file mode 100644
index 0fd7aa48176ddd79aad8d8c6e73d8dcc10b3a854..0000000000000000000000000000000000000000
--- a/matlab/reports/@report/addPage.m
+++ /dev/null
@@ -1,37 +0,0 @@
-function o = addPage(o, varargin)
-%function o = addPage(o, varargin)
-% Add a page to the report
-%
-% INPUTS
-%   o          [report]  report object
-%   varargin             arguments to @section/addGraph.m
-%
-% OUTPUTS
-%   o          [report]  updated report object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-np = length(o.pages) + 1;
-if o.showOutput
-    fprintf(1, 'Adding Page: %d\n', np);
-end
-o.pages{np} = page('orientation', o.orientation, 'paper', o.paper, varargin{:});
-end
diff --git a/matlab/reports/@report/addParagraph.m b/matlab/reports/@report/addParagraph.m
deleted file mode 100644
index 4ec7209a35d524f1d2ed8c182b53c08be57091ab..0000000000000000000000000000000000000000
--- a/matlab/reports/@report/addParagraph.m
+++ /dev/null
@@ -1,34 +0,0 @@
-function o = addParagraph(o, varargin)
-%function o = addParagraph(o, varargin)
-% Add a paragraph to the current section of the current page in the report
-%
-% INPUTS
-%   o          [report]  report object
-%   varargin             arguments to @section/addGraph.m
-%
-% OUTPUTS
-%   o          [report]  updated report object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-o.pages{end}.sections{end} = ...
-    o.pages{end}.sections{end}.addParagraph(varargin{:});
-end
diff --git a/matlab/reports/@report/addSection.m b/matlab/reports/@report/addSection.m
deleted file mode 100644
index 3387b9466662585443e01420a974d8932e535956..0000000000000000000000000000000000000000
--- a/matlab/reports/@report/addSection.m
+++ /dev/null
@@ -1,33 +0,0 @@
-function o = addSection(o, varargin)
-%function o = addSection(o, varargin)
-% Add a section to the current page in the report
-%
-% INPUTS
-%   o          [report]  report object
-%   varargin             arguments to @section/addGraph.m
-%
-% OUTPUTS
-%   o          [report]  updated report object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-o.pages{end} = o.pages{end}.addSection(varargin{:});
-end
diff --git a/matlab/reports/@report/addSeries.m b/matlab/reports/@report/addSeries.m
deleted file mode 100644
index 459230bfe0c45cb07d89ce5174e38f58655389e1..0000000000000000000000000000000000000000
--- a/matlab/reports/@report/addSeries.m
+++ /dev/null
@@ -1,38 +0,0 @@
-function o = addSeries(o, varargin)
-%function o = addSeries(o, varargin)
-% Add a graph to the current section of the current page in the report
-%
-% INPUTS
-%   o          [report]  report object
-%   varargin             arguments to @graph/addSeries
-%
-% OUTPUTS
-%   o          [report]  updated report object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-assert(isa(o.pages{end}.sections{end}.elements{end}, 'graph') || ...
-       isa(o.pages{end}.sections{end}.elements{end}, 'report_table'), ...
-       '@report.addSeries: you can only add a series to a report_table or graph object');
-
-o.pages{end}.sections{end}.elements{end} = ...
-    o.pages{end}.sections{end}.elements{end}.addSeries(varargin{:});
-end
diff --git a/matlab/reports/@report/addTable.m b/matlab/reports/@report/addTable.m
deleted file mode 100644
index 4b1f8c0d4d7812f9faa2c1787d931e31b058650b..0000000000000000000000000000000000000000
--- a/matlab/reports/@report/addTable.m
+++ /dev/null
@@ -1,34 +0,0 @@
-function o = addTable(o, varargin)
-%function o = addTable(o, varargin)
-% Add a table to the current section of the current page in the report
-%
-% INPUTS
-%   o          [report]  report object
-%   varargin             arguments to @section/addTable.m
-%
-% OUTPUTS
-%   o          [report]  updated report object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-o.pages{end}.sections{end} = ...
-    o.pages{end}.sections{end}.addTable(varargin{:});
-end
diff --git a/matlab/reports/@report/addVspace.m b/matlab/reports/@report/addVspace.m
deleted file mode 100644
index f4ca186d6c6296d6c92356a0c28b630a6d6c99fb..0000000000000000000000000000000000000000
--- a/matlab/reports/@report/addVspace.m
+++ /dev/null
@@ -1,34 +0,0 @@
-function o = addVspace(o, varargin)
-%function o = addVspace(o, varargin)
-% Add a vspace to the current section of the current page in the report
-%
-% INPUTS
-%   o          [report]  report object
-%   varargin             arguments to @section/addVspace.m
-%
-% OUTPUTS
-%   o          [report]  updated report object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-o.pages{end}.sections{end} = ...
-    o.pages{end}.sections{end}.addVspace(varargin{:});
-end
diff --git a/matlab/reports/@report/compile.m b/matlab/reports/@report/compile.m
deleted file mode 100644
index 3b3077b587d2b016d7cc04c2b63bad8c19bbf73b..0000000000000000000000000000000000000000
--- a/matlab/reports/@report/compile.m
+++ /dev/null
@@ -1,122 +0,0 @@
-function o = compile(o, varargin)
-%function o = compile(o)
-% Compile Report Object
-%
-% INPUTS
-%   o            [report]  report object
-%   varargin     [char]    allows user to change report compiler for a
-%                          given run of compile.
-%
-% OUTPUTS
-%   o     [report]  report object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-opts.compiler = o.compiler;
-opts.showReport = true;
-opts.showOutput = o.showOutput;
-
-if nargin > 1
-    if round((nargin-1)/2) ~= (nargin-1)/2
-        error('@report.compile: options must be supplied in name/value pairs');
-    end
-
-    optNames = fieldnames(opts);
-
-    % overwrite default values
-    for pair = reshape(varargin, 2, [])
-        ind = find(strcmpi(optNames, pair{1}));
-        assert(isempty(ind) || length(ind) == 1);
-        if ~isempty(ind)
-            opts.(optNames{ind}) = pair{2};
-        else
-            error('@report.compile: %s is not a recognized option.', pair{1});
-        end
-    end
-end
-
-assert(ischar(opts.compiler), '@report.compile: compiler file must be a string');
-assert(islogical(opts.showReport), '@report.compile: showReport must be either true or false');
-assert(islogical(opts.showOutput), '@report.compile: showOutput must be either true or false');
-
-if ~exist(o.fileName, 'file')
-    o.write();
-end
-
-middle = ' ./';
-options = '-synctex=1';
-if isoctave
-    echo = 1;
-else
-    echo = '-echo';
-end
-if isempty(opts.compiler)
-    if strncmp(computer, 'MACI', 4) || ~isempty(regexpi(computer, '.*apple.*', 'once'))
-        % Add most likely places for pdflatex to exist outside of default $PATH
-        if opts.showOutput
-            [status, opts.compiler] = ...
-                system(['PATH=$PATH:/usr/texbin:/usr/local/bin:/usr/local/sbin;' ...
-                        'which pdflatex'], echo);
-        else
-            [status, opts.compiler] = ...
-                system('PATH=$PATH:/usr/texbin:/usr/local/bin:/usr/local/sbin;which pdflatex');
-        end
-    elseif strcmp(computer, 'PCWIN') || strcmp(computer, 'PCWIN64')
-        if opts.showOutput
-            [status, opts.compiler] = system('findtexmf --file-type=exe pdflatex', echo);
-        else
-            [status, opts.compiler] = system('findtexmf --file-type=exe pdflatex');
-        end
-        middle = ' ';
-        opts.compiler = ['"' strtrim(opts.compiler) '"'];
-    else % gnu/linux
-        if opts.showOutput
-            [status, opts.compiler] = system('which pdflatex', echo);
-        else
-            [status, opts.compiler] = system('which pdflatex');
-        end
-    end
-    assert(status == 0, ...
-           '@report.compile: Could not find a tex compiler on your system');
-    opts.compiler = strtrim(opts.compiler);
-    o.compiler = opts.compiler;
-end
-
-if opts.showOutput
-    status = system([opts.compiler ' ' options middle o.fileName], echo);
-else
-    [status, junk] = system([opts.compiler ' ' options middle o.fileName]);
-end
-[junk, rfn, junk] = fileparts(o.fileName);
-
-if status ~= 0
-    error(['@report.compile: There was an error in compiling ' rfn '.pdf.' ...
-          '  ' compiler ' returned the error code: ' num2str(status)]);
-end
-if o.showOutput || opts.showOutput
-    fprintf(1, 'Done.\n');
-    disp('Your compiled report is located here:');
-    disp(['     ' pwd filesep rfn '.pdf']);
-end
-if opts.showReport && ~isoctave
-    open([pwd filesep rfn '.pdf']);
-end
-end
\ No newline at end of file
diff --git a/matlab/reports/@report/display.m b/matlab/reports/@report/display.m
deleted file mode 100644
index 1f4a535c53278602edd8893d04195702f90830f0..0000000000000000000000000000000000000000
--- a/matlab/reports/@report/display.m
+++ /dev/null
@@ -1,32 +0,0 @@
-function display(o)
-%function display(o)
-% Display a Report object
-%
-% INPUTS
-%   o     [report]  report object
-%
-% OUTPUTS
-%   none
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-display_reporting_object(o);
-end
\ No newline at end of file
diff --git a/matlab/reports/@report/numPages.m b/matlab/reports/@report/numPages.m
deleted file mode 100644
index 98f4b8900da4d6cd0a6b6f6308352d2939bc7305..0000000000000000000000000000000000000000
--- a/matlab/reports/@report/numPages.m
+++ /dev/null
@@ -1,32 +0,0 @@
-function n = numPages(o)
-%function n = numPages(o)
-% return the number of pages currently in the report
-%
-% INPUTS
-%   o     [report]  report object
-%
-% OUTPUTS
-%   n     [integer] number of pages in the report object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-n = length(o.pages);
-end
\ No newline at end of file
diff --git a/matlab/reports/@report/report.m b/matlab/reports/@report/report.m
deleted file mode 100644
index cf4a6160375dea968ae14b0e1332e293e44f5f25..0000000000000000000000000000000000000000
--- a/matlab/reports/@report/report.m
+++ /dev/null
@@ -1,93 +0,0 @@
-function o = report(varargin)
-%function o = report(varargin)
-% Report Class Constructor
-%
-% INPUTS
-%   varargin        0 args  : empty report object
-%                   1 arg   : must be report object (return a copy of arg)
-%                   > 1 args: option/value pairs (see structure below for options)
-%
-% OUTPUTS
-%   o     [report]  report object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-% default values
-o = struct;
-o.title = '';
-o.orientation = 'portrait';
-o.paper = 'a4';
-o.margin = 2.5;
-o.marginUnit = 'cm';
-o.pages = {};
-o.fileName = 'report.tex';
-o.showDate = true;
-o.compiler = '';
-o.showOutput = true;
-
-if nargin == 1
-    assert(isa(varargin{1}, 'report'), ['@report.report: with one arg, ' ...
-                        'you must pass a report object']);
-    r = varargin{1};
-    return;
-elseif nargin > 1
-    if round(nargin/2) ~= nargin/2
-        error(['@report.report: options must be supplied in name/value ' ...
-               'pairs']);
-    end
-
-    optNames = fieldnames(o);
-
-    % overwrite default values
-    for pair = reshape(varargin, 2, [])
-        ind = find(strcmpi(optNames, pair{1}));
-        assert(isempty(ind) || length(ind) == 1);
-        if ~isempty(ind)
-            o.(optNames{ind}) = pair{2};
-        else
-            error('@report.report: %s is not a recognized option.', pair{1});
-        end
-    end
-end
-
-% Check options provided by user
-assert(ischar(o.title), '@report.report: title must be a string');
-assert(ischar(o.fileName), '@report.report: fileName must be a string');
-assert(ischar(o.compiler), '@report.report: compiler file must be a string');
-assert(islogical(o.showDate), '@report.report: showDate must be either true or false');
-assert(islogical(o.showOutput), '@report.report: showOutput must be either true or false');
-assert(isfloat(o.margin) && o.margin > 0, '@report.report: margin must be a float > 0.');
-
-valid_margin_unit = {'cm', 'in'};
-assert(any(strcmp(o.marginUnit, valid_margin_unit)), ...
-       ['@report.report: marginUnit must be one of ' strjoin(valid_margin_unit, ' ')]);
-
-valid_paper = {'a4', 'letter'};
-assert(any(strcmp(o.paper, valid_paper)), ...
-       ['@report.report: paper must be one of ' strjoin(valid_paper, ' ')]);
-
-valid_orientation = {'portrait', 'landscape'};
-assert(any(strcmp(o.orientation, valid_orientation)), ...
-       ['@report.report: orientation must be one of ' strjoin(valid_orientation, ' ')]);
-
-% Create report object
-o = class(o, 'report');
-end
\ No newline at end of file
diff --git a/matlab/reports/@report/subsasgn.m b/matlab/reports/@report/subsasgn.m
deleted file mode 100644
index 515a1ded927c1df646277315a7e9793908fbec79..0000000000000000000000000000000000000000
--- a/matlab/reports/@report/subsasgn.m
+++ /dev/null
@@ -1,46 +0,0 @@
-function B = subsasgn(A, S, V)
-% function B = subsasgn(A, S, V)
-
-% Copyright (C) 2013-2014 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/>.
-
-B = A;
-if length(S) > 1
-    for i=1:(length(S)-1)
-        B = subsref(B, S(i));
-    end
-    B = subsasgn(B, S(end), V);
-    B = subsasgn(A, S(1:(end-1)), B);
-    return
-end
-
-switch S.type
-    case '()'
-        index = S.subs{:};
-        assert(isnumeric(index));
-        B.pages{index} = V;
-    case '.'
-        switch S.subs
-            case fieldnames(A)
-                B.(S.subs) = V;
-            otherwise
-                error(['@report.subsasgn: field ' S.subs 'does not exist']);
-        end
-    otherwise
-        error('@report.subsasgn: syntax error');
-end
-end
\ No newline at end of file
diff --git a/matlab/reports/@report/subsref.m b/matlab/reports/@report/subsref.m
deleted file mode 100644
index 29b7156bebbdfe4c39559363191b0a1babbd57e6..0000000000000000000000000000000000000000
--- a/matlab/reports/@report/subsref.m
+++ /dev/null
@@ -1,48 +0,0 @@
-function A = subsref(A, S)
-%function A = subsref(A, S)
-
-% Copyright (C) 2013-2014 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/>.
-
-switch S(1).type
-    case '.'
-        switch S(1).subs
-            case fieldnames(A)
-                A = A.(S(1).subs);
-            case methods(A)
-                if areParensNext(S)
-                    A = feval(S(1).subs, A, S(2).subs{:});
-                    S = shiftS(S,1);
-                else
-                    A = feval(S(1).subs, A);
-                end
-            otherwise
-                error(['@report.subsasgn: unknown field or method: ' S(1).subs]);
-        end
-    case '()'
-        A = A.pages{S(1).subs{:}};
-    case '{}'
-        error(['@report.subsasgn: ' S(1).type ' indexing not supported.']);
-    otherwise
-        error('@report.subsasgn: impossible case');
-end
-
-S = shiftS(S,1);
-if length(S) >= 1
-    A = subsref(A, S);
-end
-end
diff --git a/matlab/reports/@report/write.m b/matlab/reports/@report/write.m
deleted file mode 100644
index fce1a2e7a36d16c7b7484fe70f326104d552a31c..0000000000000000000000000000000000000000
--- a/matlab/reports/@report/write.m
+++ /dev/null
@@ -1,98 +0,0 @@
-function o = write(o)
-%function o = write(o)
-% Write Report object
-%
-% INPUTS
-%   o     [report]  report object
-%
-% OUTPUTS
-%   o     [report]  report object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-[fid, msg] = fopen(o.fileName, 'w');
-if fid == -1
-    error(['@report.write: ' msg]);
-end
-
-fprintf(fid, '%% Report Object\n');
-fprintf(fid, '\\documentclass[11pt]{article}\n');
-
-fprintf(fid, '\\usepackage[%spaper,margin=%f%s', o.paper, o.margin, o.marginUnit);
-if strcmpi(o.orientation, 'landscape')
-    fprintf(fid, ',landscape');
-end
-fprintf(fid, ']{geometry}\n');
-fprintf(fid, '\\usepackage{pdflscape, booktabs, pgfplots, colortbl, adjustbox, multicol}\n');
-fprintf(fid, '\\pgfplotsset{compat=1.5.1}');
-fprintf(fid, ['\\makeatletter\n' ...
-              '\\def\\blfootnote{\\gdef\\@thefnmark{}\\@footnotetext}\n' ...
-              '\\makeatother\n']);
-
-if isoctave && isempty(regexpi(computer, '.*apple.*', 'once'))
-    fprintf(fid, '\\usepackage[T1]{fontenc}\n');
-    fprintf(fid, '\\usepackage[utf8x]{inputenc}\n');
-    fprintf(fid, '\\usepackage{gnuplot-lua-tikz}\n');
-end
-
-fprintf(fid, '\\definecolor{LightCyan}{rgb}{0.88,1,1}\n');
-fprintf(fid, '\\definecolor{Gray}{gray}{0.9}\n');
-if o.showDate
-    fprintf(fid, '\\usepackage{fancyhdr, datetime}\n');
-    fprintf(fid, '\\newdateformat{reportdate}{\\THEDAY\\ \\shortmonthname\\ \\THEYEAR}\n');
-    fprintf(fid, '\\pagestyle{fancy}\n');
-    fprintf(fid, '\\renewcommand{\\headrulewidth}{0pt}\n');
-    fprintf(fid, '\\renewcommand{\\footrulewidth}{0.5pt}\n');
-    fprintf(fid, '\\rfoot{\\scriptsize\\reportdate\\today\\ -- \\currenttime}\n');
-end
-
-% May not need these.....
-fprintf(fid, '\\renewcommand{\\textfraction}{0.05}\n');
-fprintf(fid, '\\renewcommand{\\topfraction}{0.8}\n');
-fprintf(fid, '\\renewcommand{\\bottomfraction}{0.8}\n');
-fprintf(fid, '\\setlength{\\parindent}{0in}\n');
-fprintf(fid, '\\setlength{\\tabcolsep}{1em}\n');
-fprintf(fid, '\\newlength\\sectionheight\n');
-fprintf(fid, '\\begin{document}\n');
-fprintf(fid, '\\pgfdeclarelayer{background0}\n');
-fprintf(fid, '\\pgfdeclarelayer{background1}\n');
-fprintf(fid, '\\pgfsetlayers{background0,background1,main}\n');
-fprintf(fid, '\\pgfplotsset{tick scale binop={\\times},\ntrim axis left}\n');
-fprintf(fid, '\\centering\n');
-
-nps = length(o.pages);
-for i=1:nps
-    if o.showOutput
-        fprintf(1, 'Writing Page: %d\n', i);
-    end
-    o.pages{i}.write(fid, i);
-end
-
-fprintf(fid, '\\end{document}\n');
-fprintf(fid, '%% End Report Object\n');
-status = fclose(fid);
-if status == -1
-    error('@report.write: closing %s\n', o.fileName);
-end
-if o.showOutput
-    disp('Finished Writing Report!');
-end
-end
diff --git a/matlab/reports/@report_series/display.m b/matlab/reports/@report_series/display.m
deleted file mode 100644
index d4e0ba5e64d8460fb4da89d862d7a21a2c98463d..0000000000000000000000000000000000000000
--- a/matlab/reports/@report_series/display.m
+++ /dev/null
@@ -1,32 +0,0 @@
-function display(o)
-%function display(o)
-% Display a Report_Series object
-%
-% INPUTS
-%   o   [report_series] report_series object
-%
-% OUTPUTS
-%   none
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-display_reporting_object(o);
-end
\ No newline at end of file
diff --git a/matlab/reports/@report_series/getNameForLegend.m b/matlab/reports/@report_series/getNameForLegend.m
deleted file mode 100644
index 0748a8de2967e53ace463e8f8ce2ca74220c4587..0000000000000000000000000000000000000000
--- a/matlab/reports/@report_series/getNameForLegend.m
+++ /dev/null
@@ -1,31 +0,0 @@
-function s = getNameForLegend(o)
-%function s = getNameForLegend(o)
-
-% Copyright (C) 2014 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 isempty(o.data) || ~o.graphShowInLegend
-    % for the case when there is no data in the series
-    % e.g. graphVline was passed
-    % or when the user does not want this series shown in
-    % the legend
-    s = '';
-else
-    assert(size(o.data,2) == 1);
-    s = o.data.tex{:};
-end
-end
\ No newline at end of file
diff --git a/matlab/reports/@report_series/getRange.m b/matlab/reports/@report_series/getRange.m
deleted file mode 100644
index a0d1fd8077df1bde09c977fdbfad11ff1466f400..0000000000000000000000000000000000000000
--- a/matlab/reports/@report_series/getRange.m
+++ /dev/null
@@ -1,27 +0,0 @@
-function dd = getRange(o)
-%function dd = getRange(o)
-
-% Copyright (C) 2013 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 isempty(o.data)
-    dd = dates();
-else
-    assert(size(o.data, 2) == 1);
-    dd = o.data.dates;
-end
-end
\ No newline at end of file
diff --git a/matlab/reports/@report_series/getTexName.m b/matlab/reports/@report_series/getTexName.m
deleted file mode 100644
index 0672508f9bbffbf2b2f0fe2263ec181e1c5e52ff..0000000000000000000000000000000000000000
--- a/matlab/reports/@report_series/getTexName.m
+++ /dev/null
@@ -1,29 +0,0 @@
-function s = getTexName(o)
-%function s = getTexName(o)
-
-% Copyright (C) 2013-2014 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 isempty(o.data)
-    % for the case when there is no data in the series
-    % e.g. graphVline was passed
-    s = '';
-else
-    assert(size(o.data,2) == 1);
-    s = o.data.tex{:};
-end
-end
\ No newline at end of file
diff --git a/matlab/reports/@report_series/printSeries.m b/matlab/reports/@report_series/printSeries.m
deleted file mode 100644
index e1a6f0b49cd48890bfb3cee4fe31d2a01f6d9377..0000000000000000000000000000000000000000
--- a/matlab/reports/@report_series/printSeries.m
+++ /dev/null
@@ -1,57 +0,0 @@
-function o = printSeries(o, fid, dser, dates, precision)
-%function printSeries(o, fid, dser, dates, precision)
-% function to print a row of data, contained in dser
-%
-% INPUTS
-%   fid          [int]              file id
-%   dser         [string]           name of data series to be printed
-%   dates        [dates]            dates for report_series slice
-%   precision    [float]            precision with which to print the data
-%
-%
-% OUTPUTS
-%   o            [report_series]    report_series object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2014 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/>.
-
-dataString = sprintf('%%.%df', precision);
-precision  = 10^precision;
-
-data = dser(dates);
-data = setDataToZeroFromZeroTol(o, data);
-for i=1:size(data,1)
-    fprintf(fid, '&');
-    if o.tableShowMarkers
-        if data(i) < -o.tableMarkerLimit
-            fprintf(fid, '\\color{%s}', o.tableNegColor);
-        elseif data(i) > o.tableMarkerLimit
-            fprintf(fid, '\\color{%s}', o.tablePosColor);
-        end
-        fprintf(fid, '[');
-    end
-
-    fprintf(fid, dataString, round(data(i)*precision)/precision);
-
-    if o.tableShowMarkers
-        fprintf(fid, ']');
-    end
-end
-end
\ No newline at end of file
diff --git a/matlab/reports/@report_series/report_series.m b/matlab/reports/@report_series/report_series.m
deleted file mode 100644
index 0fcb611370a5790f877bfef54985b7d25d4c4f0f..0000000000000000000000000000000000000000
--- a/matlab/reports/@report_series/report_series.m
+++ /dev/null
@@ -1,102 +0,0 @@
-function o = report_series(varargin)
-%function o = report_series(varargin)
-% Report_Series Class Constructor
-%
-% INPUTS
-%   varargin        0 args  : empty report_series object
-%                   1 arg   : must be report_series object (return a copy of arg)
-%                   > 1 args: option/value pairs (see structure below for
-%                   options)
-%
-% OUTPUTS
-%   o   [report_series] report_series object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-o = struct;
-
-o.data = '';
-
-o.graphLegendName = '';
-
-o.graphLineColor = 'black';
-o.graphLineStyle = 'solid';
-o.graphLineWidth = 0.5;
-
-o.graphShowInLegend = true;
-
-o.graphMarker = '';
-o.graphMarkerEdgeColor = '';
-o.graphMarkerFaceColor = '';
-o.graphMarkerSize = 1;
-
-o.graphMiscTikzAddPlotOptions = '';
-
-o.graphHline = {};
-o.graphVline = dates();
-
-o.tableShowMarkers = false;
-o.tableNegColor = 'red';
-o.tablePosColor = 'blue';
-o.tableMarkerLimit = 1e-4;
-
-o.tableSubSectionHeader = '';
-o.tableAlignRight = false;
-
-o.tableRowColor = 'white';
-o.tableRowIndent = 0;
-
-o.tableDataRhs = '';
-
-o.zeroTol = 1e-6;
-
-if nargin == 1
-    assert(isa(varargin{1}, 'report_series'),['@report_series.report_series: with one arg you ' ...
-                        'must pass a report_series object']);
-    o = varargin{1};
-    return;
-elseif nargin > 1
-    if round(nargin/2) ~= nargin/2
-        error(['@report_series.report_series: options must be supplied in name/value ' ...
-               'pairs.']);
-    end
-
-    optNames = fieldnames(o);
-
-    % overwrite default values
-    for pair = reshape(varargin, 2, [])
-        ind = find(strcmpi(optNames, pair{1}));
-        assert(isempty(ind) || length(ind) == 1);
-        if ~isempty(ind)
-            o.(optNames{ind}) = pair{2};
-        else
-            error('@report_series.report_series: %s is not a recognized option.', pair{1});
-        end
-    end
-end
-
-if ~isempty(o.graphLegendName)
-    o.data = o.data.tex_rename(o.graphLegendName);
-end
-
-% Create report_series object
-o = class(o, 'report_series');
-end
\ No newline at end of file
diff --git a/matlab/reports/@report_series/setDataToZeroFromZeroTol.m b/matlab/reports/@report_series/setDataToZeroFromZeroTol.m
deleted file mode 100644
index 25daeb15f14bec623ca314ce058fa80c67264aa7..0000000000000000000000000000000000000000
--- a/matlab/reports/@report_series/setDataToZeroFromZeroTol.m
+++ /dev/null
@@ -1,28 +0,0 @@
-function d = setDataToZeroFromZeroTol(o, ds)
-%function d = setDataToZeroFromZeroTol(o, ds)
-
-% Copyright (C) 2014 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 = ds.data;
-stz = bsxfun(@and, ...
-             bsxfun(@lt, d, o.zeroTol), ...
-             bsxfun(@gt, d, -o.zeroTol));
-if any(stz)
-    d(stz) = 0;
-end
-end
\ No newline at end of file
diff --git a/matlab/reports/@report_series/subsref.m b/matlab/reports/@report_series/subsref.m
deleted file mode 100644
index 938b9f4b78723d31a8b934e6fa9c4dfe0af67704..0000000000000000000000000000000000000000
--- a/matlab/reports/@report_series/subsref.m
+++ /dev/null
@@ -1,46 +0,0 @@
-function A = subsref(A, S)
-%function A = subsref(A, S)
-
-% Copyright (C) 2013-2014 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/>.
-
-switch S(1).type
-    case '.'
-        switch S(1).subs
-            case fieldnames(A)
-                A = A.(S(1).subs);
-            case methods(A)
-                if areParensNext(S)
-                    A = feval(S(1).subs, A, S(2).subs{:});
-                    S = shiftS(S,1);
-                else
-                    A = feval(S(1).subs, A);
-                end
-            otherwise
-                error(['@report_series.subsref: unknown field or method: ' S(1).subs]);
-        end
-    case {'()', '{}'}
-        error(['@report_series.subsref: ' S(1).type ' indexing not supported.']);
-    otherwise
-        error('@report_series.subsref: impossible case')
-end
-
-S = shiftS(S,1);
-if length(S) >= 1
-    A = subsref(A, S);
-end
-end
diff --git a/matlab/reports/@report_series/writeSeriesForGraph.m b/matlab/reports/@report_series/writeSeriesForGraph.m
deleted file mode 100644
index 39192bb44823bbfb0863ba6e524853f8109c2bbd..0000000000000000000000000000000000000000
--- a/matlab/reports/@report_series/writeSeriesForGraph.m
+++ /dev/null
@@ -1,132 +0,0 @@
-function o = writeSeriesForGraph(o, fid, xrange)
-%function o = writeSeriesForGraph(o, fid, xrange)
-% Print a TikZ line
-%
-% INPUTS
-%   o       [report_series]    series object
-%   xrange  [dates]            range of x values for line
-%
-% OUTPUTS
-%   NONE
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2014 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/>.
-
-%% Validate options provided by user
-if isempty(o.graphVline) && isempty(o.graphHline)
-    assert(~isempty(o.data) && isdseries(o.data), ['@report_series.writeSeriesForGraph: must ' ...
-                        'provide data as a dseries']);
-end
-
-assert(ischar(o.graphMiscTikzAddPlotOptions), ['@report_series.writeSeriesForGraph: ' ...
-                    'graphMiscTikzAddPlotOptions file must be a string']);
-assert(islogical(o.graphShowInLegend), '@graph.graph: graphShowInLegend must be either true or false');
-
-% Line
-assert(ischar(o.graphLineColor), '@report_series.writeSeriesForGraph: graphLineColor must be a string');
-assert(ischar(o.graphLineStyle), '@report_series.writeSeriesForGraph: graphLineStyle must be a string');
-assert(isfloat(o.graphLineWidth) && o.graphLineWidth > 0, ...
-                    '@report_series.writeSeriesForGraph: graphLineWidth must be a positive number');
-
-% GraphMarker
-valid_graphMarker = {'x', '+', '-', '|', 'o', 'asterisk', 'star', '10-pointed star', 'oplus', ...
-                    'oplus*', 'otimes', 'otimes*', 'square', 'square*', 'triangle', 'triangle*', 'diamond', ...
-                    'diamond*', 'halfdiamond*', 'halfsquare*', 'halfsquare right*', ...
-                    'halfsquare left*','Mercedes star','Mercedes star flipped','halfcircle',...
-                    'halfcircle*','pentagon','pentagon star'};
-assert(isempty(o.graphMarker) || any(strcmp(o.graphMarker, valid_graphMarker)), ...
-       ['@report_series.writeSeriesForGraph: graphMarker must be one of ' strjoin(valid_graphMarker)]);
-
-assert(ischar(o.graphMarkerEdgeColor), '@report_series.writeSeriesForGraph: graphMarkerEdgeColor must be a string');
-assert(ischar(o.graphMarkerFaceColor), '@report_series.writeSeriesForGraph: graphMarkerFaceColor must be a string');
-assert(isfloat(o.graphMarkerSize) && o.graphMarkerSize > 0, ...
-                    '@report_series.writeSeriesForGraph: graphMarkerSize must be a positive number');
-
-% Marker & Line
-assert(~(strcmp(o.graphLineStyle, 'none') && isempty(o.graphMarker)), ['@report_series.writeSeriesForGraph: ' ...
-                    'you must provide at least one of graphLineStyle and graphMarker']);
-
-% Validate graphVline
-assert(isempty(o.graphVline) || (isdates(o.graphVline) && o.graphVline.ndat == 1), ...
-    '@report_series.writeSeriesForGraph: graphVline must be a dates of size one');
-assert(isempty(o.graphHline) || isnumeric(o.graphHline), ...
-    '@report_series.writeSeriesForGraph: graphHline must a single numeric value');
-
-% Zero tolerance
-assert(isfloat(o.zeroTol), '@report_series.write: zeroTol must be a float');
-
-%% graphVline && graphHline
-if ~isempty(o.graphVline)
-    fprintf(fid, '%%Vertical Line\n\\begin{pgfonlayer}{background1}\n\\draw');
-    writeLineOptions(o, fid);
-    stringsdd = strings(xrange);
-    x = find(strcmpi(date2string(o.graphVline), stringsdd));
-    fprintf(fid, ['(axis cs:%d,\\pgfkeysvalueof{/pgfplots/ymin}) -- (axis ' ...
-        'cs:%d,\\pgfkeysvalueof{/pgfplots/ymax});\n\\end{pgfonlayer}\n'], ...
-        x, x);
-end
-if ~isempty(o.graphHline)
-    fprintf(fid, '%%Horizontal Line\n\\begin{pgfonlayer}{background1}\n\\addplot');
-    writeLineOptions(o, fid);
-    fprintf(fid, ['coordinates {(\\pgfkeysvalueof{/pgfplots/xmin},%f)' ...
-                  '(\\pgfkeysvalueof{/pgfplots/xmax},%f)};\n\\end{pgfonlayer}\n'], ...
-            o.graphHline, o.graphHline);
-end
-if ~isempty(o.graphVline) || ~isempty(o.graphHline)
-    % return since the code below assumes that o.data exists
-    return
-end
-
-%%
-if isempty(xrange) || all(xrange == o.data.dates)
-    ds = o.data;
-else
-    ds = o.data(xrange);
-end
-
-thedata = setDataToZeroFromZeroTol(o, ds);
-fprintf(fid, '%%series %s\n\\addplot', o.data.name{:});
-writeLineOptions(o, fid);
-fprintf(fid,'\ntable[row sep=crcr]{\nx y\\\\\n');
-for i=1:ds.dates.ndat
-    fprintf(fid, '%d %f\\\\\n', i, thedata(i));
-end
-fprintf(fid,'};\n');
-end
-
-function writeLineOptions(o, fid)
-fprintf(fid, '[color=%s,%s,line width=%fpt,line join=round',...
-    o.graphLineColor, o.graphLineStyle, o.graphLineWidth);
-
-if ~isempty(o.graphMarker)
-    if isempty(o.graphMarkerEdgeColor)
-        o.graphMarkerEdgeColor = o.graphLineColor;
-    end
-    if isempty(o.graphMarkerFaceColor)
-        o.graphMarkerFaceColor = o.graphLineColor;
-    end
-    fprintf(fid, ',mark=%s,mark size=%f,every mark/.append style={draw=%s,fill=%s}',...
-        o.graphMarker,o.graphMarkerSize,o.graphMarkerEdgeColor,o.graphMarkerFaceColor);
-end
-if ~isempty(o.graphMiscTikzAddPlotOptions)
-    fprintf(fid, ',%s', o.graphMiscTikzAddPlotOptions);
-end
-fprintf(fid,']');
-end
diff --git a/matlab/reports/@report_series/writeSeriesForTable.m b/matlab/reports/@report_series/writeSeriesForTable.m
deleted file mode 100644
index 77bc82a3b1704944a5394b7b777fdf4ceba66078..0000000000000000000000000000000000000000
--- a/matlab/reports/@report_series/writeSeriesForTable.m
+++ /dev/null
@@ -1,105 +0,0 @@
-function o = writeSeriesForTable(o, fid, dates, precision, ncols, rowcolor)
-%function o = writeSeriesForTable(o, fid, dates, precision, ncols, rowcolor)
-% Write Table Row
-%
-% INPUTS
-%   o            [report_series]    report_series object
-%   fid          [int]              file id
-%   dates        [dates]            dates for report_series slice
-%   precision    [float]            precision with which to print the data
-%   ncols        [int]              total number of columns in table
-%   rowcolor     [string]           string to color this row
-%
-%
-% OUTPUTS
-%   o            [report_series]    report_series object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-%% Validate options passed to function
-assert(fid ~= -1);
-for i=1:length(dates)
-    assert(isdates(dates{i}));
-end
-assert(isint(precision));
-
-%% Validate options provided by user
-assert(ischar(o.tableSubSectionHeader), '@report_series.writeSeriesForTable: tableSubSectionHeader must be a string');
-if isempty(o.tableSubSectionHeader)
-    assert(~isempty(o.data) && isdseries(o.data), ...
-           '@report_series.writeSeriesForTable: must provide data as a dseries');
-
-    if ~isempty(o.tableDataRhs)
-        assert(~isempty(o.tableDataRhs) && isdseries(o.tableDataRhs), ...
-               '@report_series.writeSeriesForTable: must provide tableDataRhs as a dseries');
-        assert(iscell(dates) && length(dates) == 2, ...
-               '@report_series.writeSeriesForTable: must provide second range with tableDataRhs');
-    end
-end
-
-assert(ischar(o.tableNegColor), '@report_series.writeSeriesForTable: tableNegColor must be a string');
-assert(ischar(o.tablePosColor), '@report_series.writeSeriesForTable: tablePosColor must be a string');
-assert(ischar(o.tableRowColor), '@report_series.writeSeriesForTable: tableRowColor must be a string');
-assert(isint(o.tableRowIndent) && o.tableRowIndent >= 0, ...
-       '@report_series.writeSeriesForTable: tableRowIndent must be an integer >= 0');
-assert(islogical(o.tableShowMarkers), '@report_series.writeSeriesForTable: tableShowMarkers must be true or false');
-assert(islogical(o.tableAlignRight), '@report_series.writeSeriesForTable: tableAlignRight must be true or false');
-assert(isfloat(o.tableMarkerLimit), '@report_series.writeSeriesForTable: tableMarkerLimit must be a float');
-
-%% Write Output
-fprintf(fid, '%% Table Row (report_series)\n');
-if ~isempty(o.tableRowColor) && ~strcmpi(o.tableRowColor, 'white')
-    fprintf(fid, '\\rowcolor{%s}', o.tableRowColor);
-elseif ~isempty(rowcolor)
-    fprintf(fid, '\\rowcolor{%s}', rowcolor);
-else
-    fprintf(fid, '\\rowcolor{%s}', o.tableRowColor);
-end
-if ~isempty(o.tableSubSectionHeader)
-    fprintf(fid, '\\textbf{%s}', o.tableSubSectionHeader);
-    for i=1:ncols-1
-        fprintf(fid, ' &');
-    end
-    fprintf(fid, '\\\\%%\n');
-    return;
-end
-if o.tableAlignRight
-    fprintf(fid, '\\multicolumn{1}{r}{');
-end
-if o.tableRowIndent == 0
-    fprintf(fid, '\\noindent');
-else
-    for i=1:o.tableRowIndent
-        fprintf(fid,'\\indent');
-    end
-end
-fprintf(fid, ' %s', o.data.tex{:});
-if o.tableAlignRight
-    fprintf(fid, '}');
-end
-
-printSeries(o, fid, o.data, dates{1}, precision);
-if ~isempty(o.tableDataRhs)
-    printSeries(o, fid, o.tableDataRhs, dates{2}, precision);
-end
-
-fprintf(fid, '\\\\%%\n');
-end
diff --git a/matlab/reports/@report_series/ymax.m b/matlab/reports/@report_series/ymax.m
deleted file mode 100644
index eac0aaad15afc263b6b72eca8a7eb54afe319633..0000000000000000000000000000000000000000
--- a/matlab/reports/@report_series/ymax.m
+++ /dev/null
@@ -1,23 +0,0 @@
-function ymax = ymax(o, dd)
-%function ymax = ymax(o, dd)
-
-% Copyright (C) 2014 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/>.
-
-assert(~isempty(o.data) && size(o.data, 2) == 1);
-ymax = max(o.data(dd).data);
-end
\ No newline at end of file
diff --git a/matlab/reports/@report_series/ymin.m b/matlab/reports/@report_series/ymin.m
deleted file mode 100644
index 21754604777c9d10f7f5cb57a1b7804d92fa5ca6..0000000000000000000000000000000000000000
--- a/matlab/reports/@report_series/ymin.m
+++ /dev/null
@@ -1,23 +0,0 @@
-function ymin = ymin(o, dd)
-%function ymin = ymin(o, dd)
-
-% Copyright (C) 2014 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/>.
-
-assert(~isempty(o.data) && size(o.data, 2) == 1);
-ymin = min(o.data(dd).data);
-end
\ No newline at end of file
diff --git a/matlab/reports/@report_table/addSeries.m b/matlab/reports/@report_table/addSeries.m
deleted file mode 100644
index 6a0f6d23e5f9be920d63bad549fc38c9f6d14762..0000000000000000000000000000000000000000
--- a/matlab/reports/@report_table/addSeries.m
+++ /dev/null
@@ -1,22 +0,0 @@
-function o = addSeries(o, varargin)
-% function o = addSeries(o, varargin)
-
-% Copyright (C) 2013-2014 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/>.
-
-o.series{end+1} = report_series(varargin{:});
-end
\ No newline at end of file
diff --git a/matlab/reports/@report_table/display.m b/matlab/reports/@report_table/display.m
deleted file mode 100644
index f5bcf888c677f66e17889b6931554bb58a21fdef..0000000000000000000000000000000000000000
--- a/matlab/reports/@report_table/display.m
+++ /dev/null
@@ -1,32 +0,0 @@
-function display(o)
-%function display(o)
-% Display a Report_Table object
-%
-% INPUTS
-%   o   [report_table] report_table object
-%
-% OUTPUTS
-%   none
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-display_reporting_object(o);
-end
\ No newline at end of file
diff --git a/matlab/reports/@report_table/report_table.m b/matlab/reports/@report_table/report_table.m
deleted file mode 100644
index effd07e517b97963cdcee638c0351ce40c486cd7..0000000000000000000000000000000000000000
--- a/matlab/reports/@report_table/report_table.m
+++ /dev/null
@@ -1,145 +0,0 @@
-function o = report_table(varargin)
-%function o = report_table(varargin)
-% Report_Table Class Constructor
-%
-% INPUTS
-%   0 args => empty report_table
-%   1 arg (report_table class) => copy object
-%
-% OUTPUTS
-%   none
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-o = struct;
-
-o.tableDirName = 'tmpRepDir';
-o.tableName = '';
-
-o.series = {};
-
-o.title = {''};
-titleFormatDefalut = {'\large'};
-o.titleFormat = titleFormatDefalut;
-
-o.showHlines = false;
-o.showVlines = false;
-o.vlineAfter = '';
-o.vlineAfterEndOfPeriod = false;
-
-o.data = '';
-o.seriesToUse = '';
-o.range = {};
-o.precision = 1;
-o.writeCSV = false;
-
-o.highlightRows = {''};
-
-if nargin == 1
-    assert(isa(varargin{1}, 'report_table'),['With one arg to Report_Table constructor, ' ...
-                        'you must pass a report_table object']);
-    o = varargin{1};
-    return;
-elseif nargin > 1
-    if round(nargin/2) ~= nargin/2
-        error(['Options to Report_Table constructor must be supplied in name/value ' ...
-               'pairs.']);
-    end
-
-    optNames = fieldnames(o);
-
-    % overwrite default values
-    for pair = reshape(varargin, 2, [])
-        ind = find(strcmpi(optNames, pair{1}));
-        assert(isempty(ind) || length(ind) == 1);
-        if ~isempty(ind)
-            o.(optNames{ind}) = pair{2};
-        else
-            error('%s is not a recognized option to the Report_Table constructor.', pair{1});
-        end
-    end
-end
-if ~iscell(o.range)
-    o.range = {o.range};
-end
-
-if isdates(o.vlineAfter)
-    o.vlineAfter = {o.vlineAfter};
-end
-
-% Check options provided by user
-if ischar(o.title)
-    o.title = {o.title};
-end
-if ischar(o.titleFormat)
-    o.titleFormat = {o.titleFormat};
-end
-if length(o.title) ~= length(o.titleFormat)
-    o.titleFormat = repmat(titleFormatDefalut, 1, length(o.title));
-end
-assert(islogical(o.showHlines), '@report_table.report_table: showHlines must be true or false');
-assert(islogical(o.showVlines), '@report_table.report_table: showVlines must be true or false');
-assert(isint(o.precision), '@report_table.report_table: precision must be an int');
-assert(isempty(o.range) || length(o.range) <=2 && allCellsAreDatesRange(o.range), ...
-       ['@report_table.report_table: range is specified as a dates range, e.g. ' ...
-        '''dates(''1999q1''):dates(''1999q3'')''.']);
-assert(isempty(o.data) || isdseries(o.data), ...
-       '@report_table.report_table: data must be a dseries');
-assert(isempty(o.seriesToUse) || iscellstr(o.seriesToUse), ...
-       '@report_table.report_table: seriesToUse must be a cell array of string(s)');
-assert(isempty(o.vlineAfter) || allCellsAreDates(o.vlineAfter), ...
-       '@report_table.report_table: vlineAfter must be a dates');
-if o.showVlines
-    o.vlineAfter = '';
-end
-assert(islogical(o.vlineAfterEndOfPeriod), ...
-       '@report_table.report_table: vlineAfterEndOfPeriod must be true or false');
-assert(iscellstr(o.title), ...
-       '@report_table.report_table: title must be a cell array of string(s)');
-assert(iscellstr(o.titleFormat), ...
-       '@report_table.report_table: titleFormat must be a cell array of string(s)');
-assert(ischar(o.tableName), '@report_table.report_table: tableName must be a string');
-assert(ischar(o.tableDirName), '@report_table.report_table: tableDirName must be a string');
-assert(islogical(o.writeCSV), '@report_table.report_table: writeCSV must be either true or false');
-assert(iscellstr(o.highlightRows), '@report_table.report_table: highlightRowsmust be a cell string');
-
-% using o.seriesToUse, create series objects and put them in o.series
-if ~isempty(o.data)
-    if isempty(o.seriesToUse)
-        for i=1:o.data.vobs
-            o.series{end+1} = report_series('data', o.data{o.data.name{i}});
-        end
-    else
-        for i=1:length(o.seriesToUse)
-            o.series{end+1} = report_series('data', o.data{o.seriesToUse{i}});
-        end
-    end
-end
-o = rmfield(o, 'seriesToUse');
-o = rmfield(o, 'data');
-
-if ~exist(o.tableDirName, 'file')
-    mkdir(o.tableDirName);
-end
-
-% Create report_table object
-o = class(o, 'report_table');
-end
\ No newline at end of file
diff --git a/matlab/reports/@report_table/subsasgn.m b/matlab/reports/@report_table/subsasgn.m
deleted file mode 100644
index 9ea3b0b76d5a13eab9ec13952986cde38b833ed6..0000000000000000000000000000000000000000
--- a/matlab/reports/@report_table/subsasgn.m
+++ /dev/null
@@ -1,45 +0,0 @@
-function B = subsasgn(A, S, V)
-% function B = subsasgn(A, S, V)
-
-% Copyright (C) 2013 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/>.
-
-B = A;
-if length(S) > 1
-    for i=1:(length(S)-1)
-        B = subsref(B, S(i));
-    end
-    B = subsasgn(B, S(end), V);
-    B = subsasgn(A, S(1:(end-1)), B);
-    return
-end
-
-switch S.type
-    case '.'
-        switch S.subs
-            case fieldnames(A)
-                B.(S.subs) = V;
-            otherwise
-                error(['@report_table.subsasgn: field ' S.subs 'does not exist in the report_table class'])
-        end
-    case '{}'
-        assert(isint(S.subs{1}));
-        B{S.subs{1}} = V;
-    otherwise
-        error('@report_table.subsasgn: syntax error')
-end
-end
\ No newline at end of file
diff --git a/matlab/reports/@report_table/subsref.m b/matlab/reports/@report_table/subsref.m
deleted file mode 100644
index 97962ec41607396ebec30c7adc0f1c821c923d1c..0000000000000000000000000000000000000000
--- a/matlab/reports/@report_table/subsref.m
+++ /dev/null
@@ -1,46 +0,0 @@
-function A = subsref(A, S)
-%function A = subsref(A, S)
-
-% Copyright (C) 2013-2014 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/>.
-
-switch S(1).type
-    case '.'
-        switch S(1).subs
-            case fieldnames(A)
-                A = A.(S(1).subs);
-            case methods(A)
-                if areParensNext(S)
-                    A = feval(S(1).subs, A, S(2).subs{:});
-                    S = shiftS(S,1);
-                else
-                    A = feval(S(1).subs, A);
-                end
-            otherwise
-                error(['@report_table.subsref: unknown field or method: ' S(1).subs]);
-        end
-    case {'()', '{}'}
-        error(['@report_table.subsref: ' S(1).type ' indexing not supported.']);
-    otherwise
-        error('@report_table.subsref: subsref.m impossible case')
-end
-
-S = shiftS(S,1);
-if length(S) >= 1
-    A = subsref(A, S);
-end
-end
diff --git a/matlab/reports/@report_table/write.m b/matlab/reports/@report_table/write.m
deleted file mode 100644
index adc6dd9686ebb5294762f0d50c65646277b36027..0000000000000000000000000000000000000000
--- a/matlab/reports/@report_table/write.m
+++ /dev/null
@@ -1,39 +0,0 @@
-function o = write(o, fid, pg, sec, row, col)
-%function o = write(o, fid, pg, sec, row, col)
-% Write a Table object
-%
-% INPUTS
-%   o   [table]   table object
-%   fid [integer] file id
-%   pg  [integer] this page number
-%   sec [integer] this section number
-%   row [integer] this row number
-%   col [integer] this col number
-%
-% OUTPUTS
-%   o   [table] table object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-assert(fid ~= -1);
-o = writeTableFile(o, pg, sec, row, col);
-fprintf(fid, '\\input{%s}', o.tableName);
-end
diff --git a/matlab/reports/@report_table/writeTableFile.m b/matlab/reports/@report_table/writeTableFile.m
deleted file mode 100644
index 01e04adaa58fa4417a43be9d5408ec1a885e98a5..0000000000000000000000000000000000000000
--- a/matlab/reports/@report_table/writeTableFile.m
+++ /dev/null
@@ -1,200 +0,0 @@
-function o = writeTableFile(o, pg, sec, row, col)
-%function o = writeTableFile(o, pg, sec, row, col)
-% Write a Report_Table object
-%
-% INPUTS
-%   o   [report_table]    report_table object
-%   pg  [integer] this page number
-%   sec [integer] this section number
-%   row [integer] this row number
-%   col [integer] this col number
-%
-% OUTPUTS
-%   o   [report_table]    report_table object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-ne = length(o.series);
-if ne == 0
-    warning('@report_table.write: no series to plot, returning');
-    return;
-end
-
-if isempty(o.tableName)
-    o.tableName = sprintf('%s/table_pg%d_sec%d_row%d_col%d.tex', o.tableDirName, pg, sec, row, col);
-else
-    o.tableName = [o.tableDirName '/' o.tableName];
-end
-
-[fid, msg] = fopen(o.tableName, 'w');
-if fid == -1
-    error(['@report_table.writeTableFile: ' msg]);
-end
-
-%number of left-hand columns, 1 until we allow the user to group data,
-% e.g.: GDP Europe
-%         GDP France
-%         GDP Germany
-% this example would be two lh columns, with GDP Europe spanning both
-nlhc = 1;
-
-if isempty(o.range)
-    dates = getMaxRange(o.series);
-    o.range = {dates};
-else
-    dates = o.range{1};
-end
-ndates = dates.ndat;
-
-fprintf(fid, '%% Report_Table Object\n');
-fprintf(fid, '\\setlength{\\parindent}{6pt}\n');
-fprintf(fid, '\\setlength{\\tabcolsep}{4pt}\n');
-fprintf(fid, '\\begin{tabular}{@{}l');
-
-for i=1:ndates
-    fprintf(fid, 'r');
-    if o.showVlines
-        fprintf(fid, '|');
-    elseif o.vlineAfterEndOfPeriod && dates(i).time(2) == dates(i).freq
-        fprintf(fid, '|');
-    elseif ~isempty(o.vlineAfter)
-        for j=1:length(o.vlineAfter)
-            if dates(i) == o.vlineAfter{j}
-                fprintf(fid, '|');
-            end
-        end
-    end
-end
-datedata = dates.time;
-years = unique(datedata(:, 1));
-if length(o.range) > 1
-    rhscols = strings(o.range{2});
-    if o.range{2}.freq == 1
-        rhscols = strrep(rhscols, 'Y', '');
-    end
-else
-    rhscols = {};
-end
-for i=1:length(rhscols)
-    fprintf(fid, 'r');
-    if o.showVlines
-        fprintf(fid, '|');
-    end
-end
-nrhc = length(rhscols);
-ncols = ndates+nlhc+nrhc;
-fprintf(fid, '@{}}%%\n');
-for i=1:length(o.title)
-    if ~isempty(o.title{i})
-        fprintf(fid, '\\multicolumn{%d}{c}{%s %s}\\\\\n', ...
-                ncols, o.titleFormat{i}, o.title{i});
-    end
-end
-fprintf(fid, '\\toprule%%\n');
-
-% Column Headers
-thdr = num2cell(years, size(years, 1));
-if dates.freq == 1
-    for i=1:size(thdr, 1)
-        fprintf(fid, ' & %d', thdr{i, 1});
-    end
-    for i=1:length(rhscols)
-        fprintf(fid, ' & %s', rhscols{i});
-    end
-else
-    thdr{1, 2} = datedata(:, 2)';
-    if size(thdr, 1) > 1
-        for i=2:size(thdr, 1)
-            split = find(thdr{i-1, 2} == dates.freq, 1, 'first');
-            assert(~isempty(split), '@report_table.writeTableFile: Shouldn''t arrive here');
-            thdr{i, 2} = thdr{i-1, 2}(split+1:end);
-            thdr{i-1, 2} = thdr{i-1, 2}(1:split);
-        end
-    end
-    for i=1:size(thdr, 1)
-        fprintf(fid, ' & \\multicolumn{%d}{c}{%d}', size(thdr{i,2}, 2), thdr{i,1});
-    end
-    for i=1:length(rhscols)
-        fprintf(fid, ' & %s', rhscols{i});
-    end
-    fprintf(fid, '\\\\\n');
-    switch dates.freq
-        case 4
-            sep = 'Q';
-        case 12
-            sep = 'M';
-        case 52
-            sep = 'W';
-        otherwise
-            error('@report_table.writeTableFile: Invalid frequency.');
-    end
-    for i=1:size(thdr, 1)
-        period = thdr{i, 2};
-        for j=1:size(period, 2)
-            fprintf(fid, ' & \\multicolumn{1}{c');
-            if o.showVlines
-                fprintf(fid, '|');
-            elseif o.vlineAfterEndOfPeriod && j == size(period, 2)
-                fprintf(fid, '|');
-            elseif ~isempty(o.vlineAfter)
-                for k=1:length(o.vlineAfter)
-                    if o.vlineAfter{k}.time(1) == thdr{i} && ...
-                            o.vlineAfter{k}.time(2) == period(j)
-                        fprintf(fid, '|');
-                    end
-                end
-            end
-            fprintf(fid, '}{%s%d}', sep, period(j));
-        end
-    end
-end
-fprintf(fid, '\\\\[-2pt]%%\n');
-fprintf(fid, '\\hline%%\n');
-fprintf(fid, '%%\n');
-
-% Write Report_Table Data
-if o.writeCSV
-    csvseries = dseries();
-end
-for i=1:ne
-    o.series{i}.writeSeriesForTable(fid, o.range, o.precision, ncols, o.highlightRows{mod(i,length(o.highlightRows))+1});
-    if o.writeCSV
-        if isempty(o.series{i}.tableSubSectionHeader)
-            csvseries = [csvseries ...
-                o.series{i}.data(dates).set_names([...
-                num2str(i) '_' ...
-                o.series{i}.data.name{:}])];
-        end
-    end
-    if o.showHlines
-        fprintf(fid, '\\hline\n');
-    end
-end
-if o.writeCSV
-    csvseries.save(strrep(o.tableName, '.tex', ''), 'csv');
-end
-fprintf(fid, '\\bottomrule\n');
-fprintf(fid, '\\end{tabular}\\setlength{\\parindent}{0pt}\n \\par \\medskip\n\n');
-fprintf(fid, '%% End Report_Table Object\n');
-if fclose(fid) == -1
-    error('@report_table.writeTableFile: closing %s\n', o.filename);
-end
-end
diff --git a/matlab/reports/@section/addGraph.m b/matlab/reports/@section/addGraph.m
deleted file mode 100644
index c3675764fd3c9f02e9ad197a815a3fa23103c8c6..0000000000000000000000000000000000000000
--- a/matlab/reports/@section/addGraph.m
+++ /dev/null
@@ -1,38 +0,0 @@
-function o = addGraph(o, varargin)
-%function o = addGraph(o, varargin)
-% Add a graph to the Cell Array of graphs in the report
-%
-% INPUTS
-%   1 args => add empty graph
-%   2 args => add given graph
-%   3 args => add graph at index
-%
-% OUTPUTS
-%   updated section object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-for i=1:length(o.elements)
-    assert(~isa(o.elements{i}, 'paragraph'), ...
-           '@addGraph: A Section that contains a Paragraph cannot contain a Graph');
-end
-o.elements{end+1} = graph(varargin{:});
-end
diff --git a/matlab/reports/@section/addParagraph.m b/matlab/reports/@section/addParagraph.m
deleted file mode 100644
index 11c228de2d986dcd4cc3aba711abb7fa92a5f115..0000000000000000000000000000000000000000
--- a/matlab/reports/@section/addParagraph.m
+++ /dev/null
@@ -1,42 +0,0 @@
-function o = addParagraph(o, varargin)
-%function o = addParagraph(o, varargin)
-% Add a paragraph to the Cell Array of elements in this section
-%
-% INPUTS
-%   1 args => add empty paragraph
-%   2 args => add given paragraph
-%   3 args => add paragraph at index
-%
-% OUTPUTS
-%   updated page object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2014 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/>.
-
-assert(o.cols == 1, ...
-    ['@addParagraph: you can only add a paragraph to a Section that ' ...
-    'contains one column']);
-for i=1:length(o.elements)
-    assert(isa(o.elements{i}, 'paragraph'), ...
-           ['@addParagraph: you can only add a paragraph to a Section that ' ...
-            'contains only paragraphs']);
-end
-o.elements{end+1} = paragraph(varargin{:});
-end
diff --git a/matlab/reports/@section/addVspace.m b/matlab/reports/@section/addVspace.m
deleted file mode 100644
index be40daab2b4a07fba2035d5abb88a5819ac33f45..0000000000000000000000000000000000000000
--- a/matlab/reports/@section/addVspace.m
+++ /dev/null
@@ -1,37 +0,0 @@
-function o = addVspace(o, varargin)
-%function o = addVspace(o, varargin)
-% Add a vspace to the Cell Array of vspaces in the report
-%
-% INPUTS
-%   1 args => add empty vspace
-%   2 args => add given vspace
-%
-% OUTPUTS
-%   updated section object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-for i=1:length(o.elements)
-    assert(~isa(o.elements{i}, 'paragraph'), ...
-           '@addVspace: A Section that contains a Paragraph cannot contain a Vspace');
-end
-o.elements{end+1} = vspace(varargin{:});
-end
diff --git a/matlab/reports/@section/display.m b/matlab/reports/@section/display.m
deleted file mode 100644
index 476d6a1195d2ed23c49d577e854459cde35a639a..0000000000000000000000000000000000000000
--- a/matlab/reports/@section/display.m
+++ /dev/null
@@ -1,32 +0,0 @@
-function display(o)
-%function display(o)
-% Display a Section object
-%
-% INPUTS
-%   o   [section] section object
-%
-% OUTPUTS
-%   none
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-display_reporting_object(o);
-end
\ No newline at end of file
diff --git a/matlab/reports/@section/end.m b/matlab/reports/@section/end.m
deleted file mode 100644
index 0017c4b314bb1fd94f281b5f393542561b04bb98..0000000000000000000000000000000000000000
--- a/matlab/reports/@section/end.m
+++ /dev/null
@@ -1,35 +0,0 @@
-function lastIndex = end(o, k, n)
-% function lastIndex = end(o, k, n)
-% End keyword
-%
-% INPUTS
-%   o              [section] section object
-%   k              [integer] index where end appears
-%   n              [integer] number of indices
-%
-% OUTPUTS
-%   lastIndex      [integer] last section index
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013 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/>.
-
-assert(k==1 && n==1, '@section/end: section only has one dimension');
-lastIndex = numElements(o);
-end
\ No newline at end of file
diff --git a/matlab/reports/@section/numElements.m b/matlab/reports/@section/numElements.m
deleted file mode 100644
index b72393015440edf0b07a3eeb9cc3b513643e9d83..0000000000000000000000000000000000000000
--- a/matlab/reports/@section/numElements.m
+++ /dev/null
@@ -1,22 +0,0 @@
-function n = numElements(o)
-% function n = numElements(o)
-
-% Copyright (C) 2013-2014 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/>.
-
-n = length(o.elements);
-end
\ No newline at end of file
diff --git a/matlab/reports/@section/section.m b/matlab/reports/@section/section.m
deleted file mode 100644
index 5042d94d06c30f0f735b40a20cb834ffcdabc93b..0000000000000000000000000000000000000000
--- a/matlab/reports/@section/section.m
+++ /dev/null
@@ -1,60 +0,0 @@
-function o = section(varargin)
-%function o = section(varargin)
-
-% Section produces a latex minipage
-
-% Copyright (C) 2013-2014 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/>.
-
-o = struct;
-o.elements = {};
-o.cols = 1;
-o.height = '';
-
-if nargin == 1
-    assert(isa(varargin{1}, 'section'),['With one arg to Section constructor, ' ...
-                        'you must pass a section object']);
-    o = varargin{1};
-    return;
-elseif nargin > 1
-    if round(nargin/2) ~= nargin/2
-        error(['@section.section: options must be supplied in name/value ' ...
-               'pairs.']);
-    end
-
-    optNames = fieldnames(o);
-
-    % overwrite default values
-    for pair = reshape(varargin, 2, [])
-        ind = find(strcmpi(optNames, pair{1}));
-        assert(isempty(ind) || length(ind) == 1);
-        if ~isempty(ind)
-            o.(optNames{ind}) = pair{2};
-        else
-            error('@section.section: %s is not a recognized option.', pair{1});
-        end
-    end
-end
-
-% Check options provided by user
-assert(isint(o.cols), '@section.section: cols must be an integer');
-assert(isempty(o.height) || ischar(o.height), ...
-       '@section.section: cols must be a string');
-
-% Create section object
-o = class(o, 'section');
-end
diff --git a/matlab/reports/@section/subsasgn.m b/matlab/reports/@section/subsasgn.m
deleted file mode 100644
index 24dc92fbc07ea727dd3e6db43662f16ee69c777b..0000000000000000000000000000000000000000
--- a/matlab/reports/@section/subsasgn.m
+++ /dev/null
@@ -1,50 +0,0 @@
-function B = subsasgn(A, S, V)
-% function B = subsasgn(A, S, V)
-
-% Copyright (C) 2013-2014 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/>.
-
-B = A;
-if length(S) > 1
-    for i=1:(length(S)-1)
-        B = subsref(B, S(i));
-    end
-    B = subsasgn(B, S(end), V);
-    B = subsasgn(A, S(1:(end-1)), B);
-    return
-end
-
-switch S.type
-    case '()'
-        index = S.subs{:};
-        assert(isnumeric(index));
-        B.elements{index} = V;
-    case '{}'
-        index = S.subs{:};
-        assert(isnumeric(index));
-        B{index} = V;
-    case '.'
-        switch S.subs
-            case fieldnames(A)
-                B.(S.subs) = V;
-            otherwise
-                error(['@section.subsasgn: field ' S.subs 'does not exist']);
-        end
-    otherwise
-        error('@section.subsasgn: syntax error');
-end
-end
\ No newline at end of file
diff --git a/matlab/reports/@section/subsref.m b/matlab/reports/@section/subsref.m
deleted file mode 100644
index 74573e564ead116bb11f27b4b872f6377355af2e..0000000000000000000000000000000000000000
--- a/matlab/reports/@section/subsref.m
+++ /dev/null
@@ -1,48 +0,0 @@
-function A = subsref(A, S)
-%function A = subsref(A, S)
-
-% Copyright (C) 2013-2014 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/>.
-
-switch S(1).type
-    case '.'
-        switch S(1).subs
-            case fieldnames(A)
-                A = A.(S(1).subs);
-            case methods(A)
-                if areParensNext(S)
-                    A = feval(S(1).subs, A, S(2).subs{:});
-                    S = shiftS(S,1);
-                else
-                    A = feval(S(1).subs, A);
-                end
-            otherwise
-                error(['@section.subsref: unknown field or method: ' S(1).subs]);
-        end
-    case '()'
-        A = A.elements{S(1).subs{:}};
-    case '{}'
-        error(['@section.subsref: ' S(1).type ' indexing not supported.']);
-    otherwise
-        error('@section.subsref: impossible case')
-end
-
-S = shiftS(S,1);
-if length(S) >= 1
-    A = subsref(A, S);
-end
-end
diff --git a/matlab/reports/@section/write.m b/matlab/reports/@section/write.m
deleted file mode 100644
index 00a34f75c266f8468be97a46792bd0062f25dbcd..0000000000000000000000000000000000000000
--- a/matlab/reports/@section/write.m
+++ /dev/null
@@ -1,89 +0,0 @@
-function o = write(o, fid, pg, sec)
-%function o = write(o, fid, pg, sec)
-% Write Section object
-%
-% INPUTS
-%   o         [section] section object
-%   fid       [integer] file id
-%   pg        [integer] this page number
-%   sec       [integer] this section number
-%
-% OUTPUTS
-%   o         [section] section object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-assert(fid ~= -1);
-fprintf(fid, '%% Section Object\n');
-
-if ~isempty(o.height)
-    fprintf(fid, '\\setlength\\sectionheight{%s}%%\n', o.height);
-end
-fprintf(fid, '\\maxsizebox{\\textwidth}{');
-if isempty(o.height)
-    fprintf(fid, '!');
-else
-    fprintf(fid, '\\sectionheight');
-end
-fprintf(fid, '}{%%\n');
-fprintf(fid, '\\begin{tabular}[t]{');
-for i=1:o.cols
-    if ~isa(o.elements{1}, 'paragraph')
-        % if one element is a paragraph, they all are
-        % due to check in add*.m functions
-        fprintf(fid, 'l');
-    else
-        fprintf(fid, 'c');
-    end
-end
-fprintf(fid, '}\n');
-
-ne = numElements(o);
-row = 1;
-col = 1;
-for i=1:ne
-    if isa(o.elements{i}, 'vspace')
-        o.elements{i}.write(fid);
-        fprintf(fid, '\\\\\n');
-        if col ~= o.cols
-            fprintf(fid, '\\end{tabular}}\\\\\n');
-            fprintf(fid, '%% End Section Object\n\n');
-            return;
-        end
-    else
-        if isa(o.elements{i}, 'paragraph')
-            o.elements{i}.write(fid);
-        else
-            o.elements{i}.write(fid, pg, sec, row, col);
-        end
-        if col ~= o.cols
-            fprintf(fid, ' & ');
-            col = col + 1;
-        else
-            fprintf(fid, '\\\\\n');
-            row = row + 1;
-            col = 1;
-        end
-    end
-end
-fprintf(fid, '\\end{tabular}}\\\\\n');
-fprintf(fid, '%% End Section Object\n\n');
-end
\ No newline at end of file
diff --git a/matlab/reports/@vspace/display.m b/matlab/reports/@vspace/display.m
deleted file mode 100644
index 9d22a5f41ffb73dab606455c2f0c01e902e53852..0000000000000000000000000000000000000000
--- a/matlab/reports/@vspace/display.m
+++ /dev/null
@@ -1,32 +0,0 @@
-function display(o)
-%function display(o)
-% Display a Vspace object
-%
-% INPUTS
-%   o   [vspace] vspace object
-%
-% OUTPUTS
-%   none
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-display_reporting_object(o);
-end
\ No newline at end of file
diff --git a/matlab/reports/@vspace/subsasgn.m b/matlab/reports/@vspace/subsasgn.m
deleted file mode 100644
index 3b9cbe82fc5c17f39b2eff1e26fc1f9f51e4bb4f..0000000000000000000000000000000000000000
--- a/matlab/reports/@vspace/subsasgn.m
+++ /dev/null
@@ -1,49 +0,0 @@
-function B = subsasgn(A, S, V)
-% function B = subsasgn(A, S, V)
-
-% Copyright (C) 2013 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/>.
-
-B = A;
-if length(S) > 1
-    for i=1:(length(S)-1)
-        B = subsref(B, S(i));
-    end
-    B = subsasgn(B, S(end), V);
-    B = subsasgn(A, S(1:(end-1)), B);
-    return
-end
-
-switch S.type
-    case '()'
-        index = S.subs{:};
-        assert(isnumeric(index));
-        B{index} = V;
-    case '.'
-        switch S.subs
-            case fieldnames(A)
-                B.(S.subs) = V;
-            otherwise
-                error(['@vspace.subsasgn: field ' S.subs 'does not exist']);
-        end
-    case '{}'
-        assert(isint(S.subs{1}));
-        B{S.subs{1}} = V;
-    otherwise
-        error('@vspace.subsasgn: syntax error');
-end
-end
\ No newline at end of file
diff --git a/matlab/reports/@vspace/subsref.m b/matlab/reports/@vspace/subsref.m
deleted file mode 100644
index 618b985ffc08431cec9f781aaa0454024a53285b..0000000000000000000000000000000000000000
--- a/matlab/reports/@vspace/subsref.m
+++ /dev/null
@@ -1,48 +0,0 @@
-function A = subsref(A, S)
-%function A = subsref(A, S)
-
-% Copyright (C) 2013-2014 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/>.
-
-switch S(1).type
-    case '.'
-        switch S(1).subs
-            case fieldnames(A)
-                A = A.(S(1).subs);
-            case methods(A)
-                if areParensNext(S)
-                    A = feval(S(1).subs, A, S(2).subs{:});
-                    S = shiftS(S,1);
-                else
-                    A = feval(S(1).subs, A);
-                end
-            otherwise
-                error(['@vspace.subsref: unknown field or method: ' S(1).subs]);
-        end
-    case '()'
-        A = getSections(A, S(1).subs{:});
-    case '{}'
-        error(['@vspace.subsref: ' S(1).type ' indexing not supported.']);
-    otherwise
-        error('@vspace.subsref: impossible case')
-end
-
-S = shiftS(S,1);
-if length(S) >= 1
-    A = subsref(A, S);
-end
-end
diff --git a/matlab/reports/@vspace/vspace.m b/matlab/reports/@vspace/vspace.m
deleted file mode 100644
index a3aa809daf2a70444023773a022ae303f0f9791b..0000000000000000000000000000000000000000
--- a/matlab/reports/@vspace/vspace.m
+++ /dev/null
@@ -1,67 +0,0 @@
-function o = vspace(varargin)
-%function o = vspace(varargin)
-% Vspace Class Constructor
-%
-% INPUTS
-%   0 args => empty vspace
-%   1 arg (vspace class) => copy object
-%
-% OUTPUTS
-%   none
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-o = struct;
-o.number = 1;
-o.hline = 0;
-
-if nargin == 1
-    assert(isa(varargin{1}, 'vspace'), ['@vspace.vspace: with one arg to Vspace ' ...
-                        'constructor, you must pass a vspace object']);
-    o = varargin{1};
-    return;
-elseif nargin > 1
-    if round(nargin/2) ~= nargin/2
-        error(['@vspace.vspace: options must be supplied in name/value ' ...
-               'pairs.']);
-    end
-
-    optNames = fieldnames(o);
-
-    % overwrite default values
-    for pair = reshape(varargin, 2, [])
-        ind = find(strcmpi(optNames, pair{1}));
-        assert(isempty(ind) || length(ind) == 1);
-        if ~isempty(ind)
-            o.(optNames{ind}) = pair{2};
-        else
-            error('@vspace.vspace: %s is not a recognized option.', pair{1});
-        end
-    end
-end
-
-% Check options provided by user
-assert(isint(o.number), '@vspace.vspace: number must be an integer');
-assert(isint(o.hline), '@vspace.vspace: hline must be an integer');
-
-% Create vspace object
-o = class(o, 'vspace');
-end
diff --git a/matlab/reports/allCellsAreDates.m b/matlab/reports/allCellsAreDates.m
deleted file mode 100644
index 7beca1b000f817671ef32080fa7787c9dbe1c40e..0000000000000000000000000000000000000000
--- a/matlab/reports/allCellsAreDates.m
+++ /dev/null
@@ -1,39 +0,0 @@
-function tf = allCellsAreDates(dcell)
-%function tf = allCellsAreDates(dcell)
-% Determines if all the elements of dcell are dates objects
-%
-% INPUTS
-%   dcell     cell of dates objects
-%
-% OUTPUTS
-%   tf        true if every entry of dcell is a dates object
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2014 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/>.
-
-assert(iscell(dcell));
-tf = true;
-for i=1:length(dcell)
-    if ~isdates(dcell{i})
-        tf = false;
-        return;
-    end
-end
-end
\ No newline at end of file
diff --git a/matlab/reports/allCellsAreDatesRange.m b/matlab/reports/allCellsAreDatesRange.m
deleted file mode 100644
index fd3e111d851367dde03e5a297f1b65db474b43c9..0000000000000000000000000000000000000000
--- a/matlab/reports/allCellsAreDatesRange.m
+++ /dev/null
@@ -1,39 +0,0 @@
-function tf = allCellsAreDatesRange(dcell)
-%function tf = allCellsAreDatesRange(dcell)
-% Determines if all the elements of dcell are a range of dates
-%
-% INPUTS
-%   dcell     cell of dates
-%
-% OUTPUTS
-%   tf        true if every entry of dcell is a range of dates
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2014 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/>.
-
-assert(iscell(dcell));
-tf = true;
-for i=1:length(dcell)
-    if ~(isdates(dcell{i}) && dcell{i}.ndat >= 2)
-        tf = false;
-        return;
-    end
-end
-end
\ No newline at end of file
diff --git a/matlab/reports/display_reporting_object.m b/matlab/reports/display_reporting_object.m
deleted file mode 100644
index fc7ba46d081c424648b696bbb733e6224045a79f..0000000000000000000000000000000000000000
--- a/matlab/reports/display_reporting_object.m
+++ /dev/null
@@ -1,95 +0,0 @@
-function display_reporting_object(o)
-%function display_reporting_object(o)
-% Display a Reporting Object
-%   i.e., one of: graph
-%                 page
-%                 report
-%                 report_series
-%                 report_table
-%                 section
-%                 vspace
-%
-% INPUTS
-%   o   [object] reporting object
-%
-% OUTPUTS
-%   none
-%
-% SPECIAL REQUIREMENTS
-%   none
-
-% Copyright (C) 2013-2014 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/>.
-
-fprintf('\n%s Object = \n\n', upper(class(o)));
-fields = fieldnames(o);
-for i=1:length(fields)
-    fprintf('    %s: ', fields{i});
-    val = o.(fields{i});
-    if iscell(val)
-        fprintf('{');
-        for j=1:length(val)
-            if ischar(val{j});
-                fprintf('''%s''', val{j});
-                if j~=length(val)
-                    fprintf(', ');
-                end
-            else
-                if strcmp(fields{i}, 'pages') || strcmp(fields{i}, 'sections')
-                    fprintf('%d', length(val));
-                    break;
-                else
-                    fprintf('fix this');
-                end
-            end
-        end
-        fprintf('}');
-    elseif ischar(val)
-        fprintf('''%s''', val);
-    elseif isnumeric(val)
-        fprintf('%s', num2str(val));
-    elseif islogical(val)
-        if val
-            fprintf('true');
-        else
-            fprintf('false');
-        end
-    elseif isobject(val)
-        if isdates(val)
-            if isempty(val)
-                fprintf('<dates: empty>');
-            else
-                fprintf('<dates: %s, ..., %s>', ...
-                    date2string(val(1)), date2string(val(end)));
-            end
-        elseif isdseries(val)
-            if numel(val) == 1
-                fprintf('<dseries: %s>', val.name{1});
-            else
-                fprintf('%s', class(val));
-            end
-        else
-            cl = class(val);
-            fprintf('%d', val.(['num' upper(cl(1)) cl(2:end)]));
-        end
-    else
-        fprintf('fix this');
-    end
-    fprintf('\n');
-end
-fprintf('\n');
-end
\ No newline at end of file
diff --git a/matlab/reports/getMaxRange.m b/matlab/reports/getMaxRange.m
deleted file mode 100644
index 1a578083ca1ab836e897997a5b045db478d2322f..0000000000000000000000000000000000000000
--- a/matlab/reports/getMaxRange.m
+++ /dev/null
@@ -1,36 +0,0 @@
-function dd = getMaxRange(cellser)
-% function dd = getMaxRange(cellser)
-
-% Copyright (C) 2013-2014 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/>.
-
-ddmin = dates();
-ddmax = dates();
-ne = length(cellser);
-for i=1:ne
-    ddt = cellser{i}.getRange();
-    if ~isempty(ddt)
-        if isempty(ddmin)
-            ddmin = ddt(1);
-            ddmax = ddt(end);
-        else
-            ddmin = min(ddt(1), ddmin);
-            ddmax = max(ddt(end), ddmax);
-        end
-    end
-end
-dd = ddmin:ddmax;
\ No newline at end of file
diff --git a/matlab/resol.m b/matlab/resol.m
index 92c775806782913052368174b1042aa847fc1eca..52618e6e86edb56a0c16a2ee37b447c1f9050593 100644
--- a/matlab/resol.m
+++ b/matlab/resol.m
@@ -4,7 +4,7 @@ function [dr,info,M,options,oo] = resol(check_flag,M,options,oo)
 %! @deftypefn {Function File} {[@var{dr},@var{info},@var{M},@var{options},@var{oo}] =} resol (@var{check_flag},@var{M},@var{options},@var{oo})
 %! @anchor{resol}
 %! @sp 1
-%! Computes first and second order reduced form of the DSGE model.
+%! Computes the perturbation-based decisions rules of the DSGE model (orders 1 to 3).
 %! @sp 2
 %! @strong{Inputs}
 %! @sp 1
@@ -111,23 +111,27 @@ if options.loglinear
     % Find variables with non positive steady state.
     idx = find(dr.ys<1e-9);
     if length(idx)
-        variables_with_non_positive_steady_state = M.endo_names(idx,:);
-        skipline()
-        fprintf('You are attempting to simulate/estimate a loglinear approximation of a model, but\n')
-        fprintf('the steady state level of the following variables is not strictly positive:\n')
-        for var_iter=1:length(idx)
-            fprintf(' - %s (%s)\n',deblank(variables_with_non_positive_steady_state(var_iter,:)), num2str(dr.ys(idx(var_iter))))
+        if options.debug
+            variables_with_non_positive_steady_state = M.endo_names(idx,:);
+            skipline()
+            fprintf('You are attempting to simulate/estimate a loglinear approximation of a model, but\n')
+            fprintf('the steady state level of the following variables is not strictly positive:\n')
+            for var_iter=1:length(idx)
+                fprintf(' - %s (%s)\n',deblank(variables_with_non_positive_steady_state(var_iter,:)), num2str(dr.ys(idx(var_iter))))
+            end
+            if isestimation()
+                fprintf('You should check that the priors and/or bounds over the deep parameters are such\n')
+                fprintf('that the steady state levels of all the variables are strictly positive, or consider\n')
+                fprintf('a linearization of the model instead of a log linearization.\n')
+            else
+                fprintf('You should check that the calibration of the deep parameters is such that the\n')
+                fprintf('steady state levels of all the variables are strictly positive, or consider\n')
+                fprintf('a linearization of the model instead of a log linearization.\n')
+            end
         end
-        if isestimation()
-            fprintf('You should check that the priors and/or bounds over the deep parameters are such\n')
-            fprintf('that the steady state levels of all the variables are strictly positive, or consider\n')
-            fprintf('a linearization of the model instead of a log linearization.\n')
-        else
-            fprintf('You should check that the calibration of the deep parameters is such that the\n')
-            fprintf('steady state levels of all the variables are strictly positive, or consider\n')
-            fprintf('a linearization of the model instead of a log linearization.\n')
-        end
-        error('stoch_simul::resol: The loglinearization of the model cannot be performed, because the steady state is not strictly positive!')
+        info(1)=26;
+        info(2)=sum(dr.ys(dr.ys<1e-9).^2);
+        return
     end
 end
 
diff --git a/matlab/rndprior.m b/matlab/rndprior.m
deleted file mode 100644
index 3ff7f6e0bb7b4f6a7850b31c289312f07a412bc6..0000000000000000000000000000000000000000
--- a/matlab/rndprior.m
+++ /dev/null
@@ -1,57 +0,0 @@
-function y = rndprior(bayestopt_)
-% function y = rndprior(bayestopt_)
-% Draws random number from the prior density
-%
-% INPUTS
-%   bayestopt_:    structure characterizing priors
-%    
-% OUTPUTS
-%   y:             drawn numbers vector              
-%
-% SPECIAL REQUIREMENTS
-%    none
-
-% Copyright (C) 2003-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/licenses/>.
-
-pshape=bayestopt_.pshape;
-p3=bayestopt_.p3;
-p4=bayestopt_.p4;
-p6=bayestopt_.p6;
-p7=bayestopt_.p7;
-
-y = NaN(1,length(pshape)); 
-
-for i=1:length(pshape)
-    switch pshape(i)
-      case 1 % Beta
-        y(i) = betarnd(p6(i),p7(i));
-        y(i) = y(1,i) * (p4(i)-p3(i)) + p3(i);
-      case 2 % Generalized gamma
-        y(i) = gamrnd(p6(i),p7(i)) + p3(i);
-      case 3 % Gaussian
-        y(i) = randn*p7(i) + p6(i) ;
-      case 4 % Inverse-gamma type 1
-        y(i) = 1/sqrt(gamrnd(p7(i)/2, 2/p6(i))) + p3(i);
-      case 5 % Uniform
-        y(i) = rand*(p4(i)-p3(i)) + p3(i);
-      case 6 % Inverse-gamma type 2
-        y(i) = 1/gamrnd(p7(i)/2, 2/p6(i)) + p3(i); 
-      otherwise
-        error(sprintf('rndprior: unknown distribution shape (index %d, type %d)', i, pshape(i)));
-    end
-end
\ No newline at end of file
diff --git a/matlab/schur_statespace_transformation.m b/matlab/schur_statespace_transformation.m
index cef99ed78e4e4318090244703d708da109c7e10b..c9bdec8a9baeb4c93fb90cd7eb94238ff95c7229 100644
--- a/matlab/schur_statespace_transformation.m
+++ b/matlab/schur_statespace_transformation.m
@@ -1,8 +1,15 @@
-function [Z,ST,R1,QT,Pstar,Pinf] = schur_statespace_transformation(mf,T,R,Q,qz_criterium)
-% function [Z,ST,QT,R1,Pstar,Pinf] = schur_statespace(mf,T,R,Q,qz_criterium)
+function [Z,ST,R1,QT,Pstar,Pinf] = schur_statespace_transformation(mf,T,R,Q,qz_criterium, restrict_columns)
+% function [Z,ST,QT,R1,Pstar,Pinf] = schur_statespace_transformation(mf,T,R,Q,qz_criterium, restrict_columns)
 % Kitagawa transformation of state space system with a quasi-triangular
-% transition matrix with unit roots at the top. Computation of Pstar and
-% Pinf for Durbin and Koopman Diffuse filter
+% transition matrix with unit roots at the top, but excluding zero columns of the transition matrix. 
+% Computation of Pstar and Pinf for Durbin and Koopman Diffuse filter
+%
+% The transformed state space is 
+%     y = [ss; z; x];
+%     s = static variables (zero columns of T)
+%     z = unit roots
+%     x = stable roots
+%     ss = s - z = stationarized static variables
 % 
 % INPUTS 
 %   mf           [integer]    vector of indices of observed variables in
@@ -44,6 +51,20 @@ function [Z,ST,R1,QT,Pstar,Pinf] = schur_statespace_transformation(mf,T,R,Q,qz_c
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
+np = size(T,1);
+if nargin == 6,
+    indx = restrict_columns;
+    indx0=find(~ismember([1:np],indx));
+else
+    indx=(find(max(abs(T))>0));
+    indx0=(find(max(abs(T))==0));
+end
+T0=T(indx0,indx); %static variables vs. dynamic ones
+R0=R(indx0,:); % matrix of shocks for static variables
+
+% perform Kitagawa transformation only for non-zero columns of T
+T=T(indx,indx);
+R=R(indx,:);
 np = size(T,1);
 [QT,ST] = schur(T);
 e1 = abs(ordeig(ST)) > 2-qz_criterium;
@@ -93,14 +114,40 @@ if i == nk+1
     Pstar(nk1,nk1)=(B(nk1,nk1)+c)/(1-ST(nk1,nk1)*ST(nk1,nk1));
 end
 
-Z = QT(mf,:);
 R1 = QT'*R;
+ST1=ST;
+
+% now I recover stationarized static variables
+% using 
+% ss = s-z and
+% z-z(-1) (growth rates of unit roots) only depends on stationary variables
+np0=length(indx0);
+Pstar = blkdiag(zeros(np0),Pstar);
+ST = [zeros(length(Pstar),length(indx0)) [T0*QT ;ST]];
+R1 = [R0; R1];
+ST0=ST;
+ST0(:,1:np0+nk)=0;
+ST0(np0+1:np0+nk,:)=0;
+ST0(1:np0,np0+nk+1:end) = ST(1:np0,np0+nk+1:end)-ST(1:np0,np0+1:np0+nk)*ST(np0+1:np0+nk,np0+nk+1:end);
+R10 = R1;
+R10(np0+1:np0+nk,:)=0;
+R10(1:np0,:) = R1(1:np0,:)-ST(1:np0,np0+1:np0+nk)*R1(np0+1:np0+nk,:);
+Pstar = ...
+     ST0*Pstar*ST0'+ ...
+         R10*Q*R10';
+QT = blkdiag(eye(np0),QT);
+QT(1:np0,np0+1:np0+nk) = QT(1:np0,np0+1:np0+nk)+ST(1:np0,np0+1:np0+nk);
+% reorder QT entries 
+QT([indx0(:); indx(:)],:) = QT; 
+Z = QT(mf,:);
+ST(1:np0,:) = ST0(1:np0,:);
+R1(1:np0,:) = R10(1:np0,:);
 
 % stochastic trends with no influence on observed variables are
 % arbitrarily initialized to zero
 Pinf = zeros(np,np);
 Pinf(1:nk,1:nk) = eye(nk);
-[QQ,RR,EE] = qr(Z*ST(:,1:nk),0);
+[QQ,RR,EE] = qr(Z*ST(:,1+np0:nk+np0),0);
 k = find(abs(diag([RR; zeros(nk-size(Z,1),size(RR,2))])) < 1e-8);
 if length(k) > 0
     k1 = EE(:,k);
@@ -108,3 +155,5 @@ if length(k) > 0
     dd(k1) = zeros(length(k1),1);
     Pinf(1:nk,1:nk) = diag(dd);
 end
+Pinf = blkdiag(zeros(np0),Pinf);
+
diff --git a/matlab/set_prior.m b/matlab/set_prior.m
index 9fcbd10b3e99aefdd90812b545598862538c3da4..a72a6204d63e1b4a37ea72e7ba2424db52bc9019 100644
--- a/matlab/set_prior.m
+++ b/matlab/set_prior.m
@@ -155,6 +155,12 @@ end
 bayestopt_.p6 = NaN(size(bayestopt_.p1)) ;
 bayestopt_.p7 = bayestopt_.p6 ;
 
+%% check for point priors and disallow them as they do not work with MCMC
+if any(bayestopt_.p2 ==0)
+    error(sprintf(['Error in prior for %s: you cannot use a point prior in estimation. Either increase the prior standard deviation',...
+        ' or fix the parameter completely.'], bayestopt_.name{bayestopt_.p2 ==0}))
+end
+
 % generalized location parameters by default for beta distribution
 k = find(bayestopt_.pshape == 1);
 k1 = find(isnan(bayestopt_.p3(k)));
@@ -179,7 +185,7 @@ for i=1:length(k)
         bayestopt_.p5(k(i)) = m;
     else
         disp(['Prior distribution for parameter ' bayestopt_.name{k(i)}  ' has two modes!'])
-        bayestopt_.p5(k(i)) = bayestopt_.p1(k(i)) ; 
+        bayestopt_.p5(k(i)) = m(1); 
     end
 end
 
diff --git a/matlab/simult_.m b/matlab/simult_.m
index 73f0959f31a57a7bbd7b0801c51f8db5052cac0a..a4ebe4dba3cf703a81be678f4d90451afd321658 100644
--- a/matlab/simult_.m
+++ b/matlab/simult_.m
@@ -15,7 +15,7 @@ function y_=simult_(y0,dr,ex_,iorder)
 % SPECIAL REQUIREMENTS
 %    none
 
-% Copyright (C) 2001-2013 Dynare Team
+% Copyright (C) 2001-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -41,12 +41,6 @@ exo_nbr = M_.exo_nbr;
 y_ = zeros(size(y0,1),iter+M_.maximum_lag);
 y_(:,1) = y0;
 
-% stoch_simul sets k_order_solver=1 if order=3, but does so only locally, so we
-% have to do it here also
-if options_.order == 3
-    options_.k_order_solver = 1;
-end
-
 if ~options_.k_order_solver || (options_.k_order_solver && options_.pruning) %if k_order_pert is not used or if we do not use Dynare++ with k_order_pert
     if iorder==1
         y_(:,1) = y_(:,1)-dr.ys;
diff --git a/matlab/skipline.m b/matlab/skipline.m
index 6eadae93a57b1305430e7a9b810b79a7b65f0be3..5b311ab937d912f690dc50ede578e3855e6dda4b 100644
--- a/matlab/skipline.m
+++ b/matlab/skipline.m
@@ -1,5 +1,4 @@
 function skipline(n, fid)
-% function skipline(n, fid)
 % This function prints n newlines to fid
 %
 % INPUTS 
@@ -29,13 +28,12 @@ function skipline(n, fid)
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.    
 
 if nargin < 2
-	fid = 1;
-	if nargin < 1
-		n = 1;
-	end
+    fid = 1;
+    if nargin < 1
+        n = 1;
+    end
 end
 
 for i=1:n
-	fprintf(fid,'\n');
-end
+    fprintf(fid,'\n');
 end
\ No newline at end of file
diff --git a/matlab/solve_one_boundary.m b/matlab/solve_one_boundary.m
index 304b81892851dbbbcbbd1fc3d0733b2e076762ce..b1a7ed7934a64a37f10a60cd109acbc3b1da3967 100644
--- a/matlab/solve_one_boundary.m
+++ b/matlab/solve_one_boundary.m
@@ -55,7 +55,7 @@ function [y, info] = solve_one_boundary(fname, y, x, params, steady_state, ...
 %   none.
 %  
 
-% Copyright (C) 1996-2013 Dynare Team
+% Copyright (C) 1996-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -80,7 +80,7 @@ correcting_factor=0.01;
 ilu_setup.droptol=1e-10;
 max_resa=1e100;
 reduced = 0;
-if(forward_backward)
+if forward_backward
     incr = 1;
     start = y_kmin+1;
     finish = periods+y_kmin;
@@ -89,140 +89,113 @@ else
     start = periods+y_kmin;
     finish = y_kmin+1;
 end
-%lambda=1;
+
 for it_=start:incr:finish
     cvg=0;
     iter=0;
     g1=spalloc( Blck_size, Blck_size, nze);
-    while ~(cvg==1 || iter>maxit_),
-        if(is_dynamic)
-            [r, y, g1, g2, g3] = feval(fname, y, x, params, steady_state, ...
-                                       it_, 0);
+    while ~(cvg==1 || iter>maxit_)
+        if is_dynamic
+            [r, y, g1, g2, g3] = feval(fname, y, x, params, steady_state, it_, 0);
         else
             [r, y, g1] = feval(fname, y, x, params);
-        end;
-        if(~isreal(r))
+        end
+        if ~isreal(r)
             max_res=(-(max(max(abs(r))))^2)^0.5;
         else
             max_res=max(max(abs(r)));
-        end;
-        %['max_res=' num2str(max_res) ' Block_Num=' int2str(Block_Num) ' it_=' int2str(it_)]
-        %disp(['iteration : ' int2str(iter+1) ' => ' num2str(max_res) ' time = ' int2str(it_)]);
-        
-        %     fjac = zeros(Blck_size, Blck_size);
-        %     disp(['Blck_size=' int2str(Blck_size) ' it_=' int2str(it_)]);
-        %     dh = max(abs(y(it_, y_index_eq)),options_.gstep*ones(1, Blck_size))*eps^(1/3);
-        %     fvec = r;
-        %       for j = 1:Blck_size
-        %         ydh = y ;
-        %           ydh(it_, y_index_eq(j)) = ydh(it_, y_index_eq(j)) + dh(j)  ;
-        %           [t, y1, g11, g21, g31]=feval(fname, ydh, x, params, it_, 0);
-        %           fjac(:,j) = (t - fvec)./dh(j) ;
-        %       end;
-        %     diff = g1 -fjac;
-        %     diff
-        %     disp('g1');
-        %     disp([num2str(g1,'%4.5f')]);
-        %     disp('fjac');
-        %     disp([num2str(fjac,'%4.5f')]);
-        %     [c_max, i_c_max] = max(abs(diff));
-        %     [l_c_max, i_r_max] = max(c_max);
-        %     disp(['maximum element row=' int2str(i_c_max(i_r_max)) ' and column=' int2str(i_r_max) ' value = ' num2str(l_c_max)]);
-        %     equation = i_c_max(i_r_max);
-        %     variable = i_r_max;
-        %     variable
-        %     mod(variable, Blck_size)
-        %     disp(['equation ' int2str(equation) ' and variable ' int2str(y_index_eq(variable)) ' ' M_.endo_names(y_index_eq(variable), :)]);
-        %     disp(['g1(' int2str(equation) ', ' int2str(variable) ')=' num2str(g1(equation, variable),'%3.10f') ' fjac(' int2str(equation) ', ' int2str(variable) ')=' num2str(fjac(equation, variable), '%3.10f') ' y(' int2str(it_) ', ' int2str(variable) ')=' num2str(y(it_, variable))]);
-        %     %return;
-        %     %g1 = fjac;
-
-        
-        
-        
-        
-        if(verbose==1)
-            disp(['iteration : ' int2str(iter+1) ' => ' num2str(max_res) ' time = ' int2str(it_)]);
-            if(is_dynamic)
-                disp([M.endo_names(y_index_eq,:) num2str([y(it_,y_index_eq)' r g1])]);
+        end
+        if verbose==1
+            disp(['iteration : ' int2str(iter+1) ' => ' num2str(max_res) ' time = ' int2str(it_)])
+            if is_dynamic
+                disp([M.endo_names(y_index_eq,:) num2str([y(it_,y_index_eq)' r g1])])
             else
-                disp([M.endo_names(y_index_eq,:) num2str([y(y_index_eq) r g1])]);
-            end;
-        end;
-        if(~isreal(max_res) || isnan(max_res))
+                disp([M.endo_names(y_index_eq,:) num2str([y(y_index_eq) r g1])])
+            end
+        end
+        if ~isreal(max_res) || isnan(max_res)
             cvg = 0;
-        elseif(is_linear && iter>0)
+        elseif is_linear && iter>0
             cvg = 1;
         else
             cvg=(max_res<solve_tolf);
-        end;
-        if(~cvg)
-            if(iter>0)
-                if(~isreal(max_res) || isnan(max_res) || (max_resa<max_res && iter>1))
-                    if(isnan(max_res) || (max_resa<max_res && iter>0))
+        end
+        if ~cvg
+            if iter>0
+                if ~isreal(max_res) || isnan(max_res) || (max_resa<max_res && iter>1)
+                    if isnan(max_res) || (max_resa<max_res && iter>0)
                         detJ=det(g1a);
                         if(abs(detJ)<1e-7)
                             max_factor=max(max(abs(g1a)));
                             ze_elem=sum(diag(g1a)<cutoff);
-                            disp([num2str(full(ze_elem),'%d') ' elements on the Jacobian diagonal are below the cutoff (' num2str(cutoff,'%f') ')']);
-                            if(correcting_factor<max_factor)
+                            if verbose
+                                disp([num2str(full(ze_elem),'%d') ' elements on the Jacobian diagonal are below the cutoff (' num2str(cutoff,'%f') ')'])
+                            end
+                            if correcting_factor<max_factor
                                 correcting_factor=correcting_factor*4;
-                                disp(['The Jacobain matrix is singular, det(Jacobian)=' num2str(detJ,'%f') '.']);
-                                disp(['    trying to correct the Jacobian matrix:']);
-                                disp(['    correcting_factor=' num2str(correcting_factor,'%f') ' max(Jacobian)=' num2str(full(max_factor),'%f')]);
+                                if verbose
+                                    disp(['The Jacobain matrix is singular, det(Jacobian)=' num2str(detJ,'%f') '.'])
+                                    disp(['    trying to correct the Jacobian matrix:'])
+                                    disp(['    correcting_factor=' num2str(correcting_factor,'%f') ' max(Jacobian)=' num2str(full(max_factor),'%f')])
+                                end
                                 dx = - r/(g1+correcting_factor*speye(Blck_size));
-                                %dx = -b'/(g1+correcting_factor*speye(Blck_size))-ya_save;
                                 y(it_,y_index_eq)=ya_save+lambda*dx;
-                                continue;
+                                continue
                             else
-                                disp('The singularity of the jacobian matrix could not be corrected');
+                                if verbose
+                                    disp('The singularity of the jacobian matrix could not be corrected')
+                                end
                                 info = -Block_Num*10;
-                                return;
-                            end;
-                        end;
-                    elseif(lambda>1e-8)
+                                return
+                            end
+                        end
+                    elseif lambda>1e-8
                         lambda=lambda/2;
                         reduced = 1;
-                        disp(['reducing the path length: lambda=' num2str(lambda,'%f')]);
-                        if(is_dynamic)
+                        if verbose
+                            disp(['reducing the path length: lambda=' num2str(lambda,'%f')])
+                        end
+                        if is_dynamic
                             y(it_,y_index_eq)=ya_save-lambda*dx;
                         else
                             y(y_index_eq)=ya_save-lambda*dx;
-                        end;
-                        continue;
+                        end
+                        continue
                     else
-                        if(cutoff == 0)
-                            fprintf('Error in simul: Convergence not achieved in block %d, at time %d, after %d iterations.\n Increase "options_.simul.maxit".\n',Block_Num, it_, iter);
-                        else
-                            fprintf('Error in simul: Convergence not achieved in block %d, at time %d, after %d iterations.\n Increase "options_.simul.maxit" or set "cutoff=0" in model options.\n',Block_Num, it_, iter);
-                        end;
-                        if(is_dynamic)
+                        if verbose
+                            if cutoff==0
+                                fprintf('Error in simul: Convergence not achieved in block %d, at time %d, after %d iterations.\n Increase "options_.simul.maxit".\n',Block_Num, it_, iter);
+                            else
+                                fprintf('Error in simul: Convergence not achieved in block %d, at time %d, after %d iterations.\n Increase "options_.simul.maxit" or set "cutoff=0" in model options.\n',Block_Num, it_, iter);
+                            end
+                        end
+                        if is_dynamic
                             oo_.deterministic_simulation.status = 0;
                             oo_.deterministic_simulation.error = max_res;
                             oo_.deterministic_simulation.iterations = iter;
                             oo_.deterministic_simulation.block(Block_Num).status = 0;% Convergency failed.
                             oo_.deterministic_simulation.block(Block_Num).error = max_res;
                             oo_.deterministic_simulation.block(Block_Num).iterations = iter;
-                        end;
+                        end
                         info = -Block_Num*10;
-                        return;
-                    end;
+                        return
+                    end
                 else
-                    if(lambda<1)
+                    if lambda<1
                         lambda=max(lambda*2, 1);
-                    end;
-                end;
-            end;
-            if(is_dynamic)
+                    end
+                end
+            end
+            if is_dynamic
                 ya = y(it_,y_index_eq)';
             else
                 ya = y(y_index_eq);
-            end;
+            end
             ya_save=ya;
             g1a=g1;
-            if(~is_dynamic && options.solve_algo == 0)
-                if (verbose == 1)
-                    disp('steady: fsolve');
+            if ~is_dynamic && options.solve_algo==0
+                if verbose
+                    disp('steady: fsolve')
                 end
                 if ~isoctave
                     if ~user_has_matlab_license('optimization_toolbox')
@@ -248,31 +221,30 @@ for it_=start:incr:finish
                     else
                         yn = y(y_index_eq);
                         exitval = 3;
-                    end;
+                    end
                 end
-                    
                 y(y_index_eq) = yn;
                 if exitval > 0
                     info = 0;
                 else
                     info = -Block_Num*10;
                 end
-            elseif((~is_dynamic && options.solve_algo==2) || (is_dynamic && stack_solve_algo==4))
-                if (verbose == 1 && ~is_dynamic)
-                    disp('steady: LU + lnsrch1');
+            elseif (~is_dynamic && options.solve_algo==2) || (is_dynamic && stack_solve_algo==4)
+                if verbose==1 && ~is_dynamic
+                    disp('steady: LU + lnsrch1')
                 end
                 lambda=1;
                 stpmx = 100 ;
-                if (is_dynamic)
+                if is_dynamic
                     stpmax = stpmx*max([sqrt(ya'*ya);size(y_index_eq,2)]);
                 else
                     stpmax = stpmx*max([sqrt(ya'*ya);size(y_index_eq,2)]);
-                end;
+                end
                 nn=1:size(y_index_eq,2);
                 g = (r'*g1)';
                 f = 0.5*r'*r;
                 p = -g1\r ;
-                if (is_dynamic)
+                if is_dynamic
                     [ya,f,r,check]=lnsrch1(y(it_,:)',f,g,p,stpmax, ...
                                            'lnsrch1_wrapper_one_boundary',nn, ...
                                            y_index_eq, y_index_eq, fname, y, x, params, steady_state, it_);
@@ -281,126 +253,133 @@ for it_=start:incr:finish
                     [ya,f,r,check]=lnsrch1(y,f,g,p,stpmax,fname,nn,y_index_eq,x, ...
                                            params, steady_state,0);
                     dx = ya - y(y_index_eq);
-                end;
-                
-                if(is_dynamic)
+                end
+                if is_dynamic
                     y(it_,:) = ya';
                 else
                     y = ya';
-                end;
-            elseif(~is_dynamic && options.solve_algo==3)
-                if (verbose == 1)
-                    disp('steady: csolve');
+                end
+            elseif ~is_dynamic && options.solve_algo==3
+                if verbose==1
+                    disp('steady: csolve')
                 end
                 [yn,info] = csolve(@local_fname, y(y_index_eq),@ ...
                                    local_fname,1e-6,500, x, params, steady_state, y, y_index_eq, fname, 1);
                 dx = ya - yn;
                 y(y_index_eq) = yn;
-            elseif((stack_solve_algo==1 && is_dynamic) || (stack_solve_algo==0 && is_dynamic) || (~is_dynamic && (options.solve_algo==1 || options.solve_algo==6))),
-                if (verbose == 1 && ~is_dynamic)
-                    disp('steady: Sparse LU ');
+            elseif (stack_solve_algo==1 && is_dynamic) || (stack_solve_algo==0 && is_dynamic) || (~is_dynamic && (options.solve_algo==1 || options.solve_algo==6))
+                if verbose==1 && ~is_dynamic
+                    disp('steady: Sparse LU ')
                 end
                 dx =  g1\r;
                 ya = ya - lambda*dx;
-                if(is_dynamic)
+                if is_dynamic
                     y(it_,y_index_eq) = ya';
                 else
                     y(y_index_eq) = ya;
-                end;
-            elseif((stack_solve_algo==2 && is_dynamic) || (options.solve_algo==7 && ~is_dynamic)),
+                end
+            elseif (stack_solve_algo==2 && is_dynamic) || (options.solve_algo==7 && ~is_dynamic)
                 flag1=1;
                 if isoctave
                     error('SOLVE_ONE_BOUNDARY: you can''t use solve_algo=7 since GMRES is not implemented in Octave')
                 end
-                if (verbose == 1 && ~is_dynamic)
-                    disp('steady: GMRES ');
+                if verbose == 1 && ~is_dynamic
+                    disp('steady: GMRES ')
                 end
-                while(flag1>0)
+                while flag1>0
                     [L1, U1]=ilu(g1,ilu_setup);
                     [dx,flag1] = gmres(g1,-r,Blck_size,1e-6,Blck_size,L1,U1);
-                    if (flag1>0 || reduced)
-                        if(flag1==1)
-                            disp(['Error in simul: No convergence inside GMRES after ' num2str(iter,'%6d') ' iterations, in block' num2str(Block_Num,'%3d')]);
-                        elseif(flag1==2)
-                            disp(['Error in simul: Preconditioner is ill-conditioned, in block' num2str(Block_Num,'%3d')]);
-                        elseif(flag1==3)
-                            disp(['Error in simul: GMRES stagnated (Two consecutive iterates were the same.), in block' num2str(Block_Num,'%3d')]);
-                        end;
+                    if  flag1>0 || reduced
+                        if verbose
+                            if flag1==1
+                                disp(['Error in simul: No convergence inside GMRES after ' num2str(iter,'%6d') ' iterations, in block' num2str(Block_Num,'%3d')])
+                            elseif(flag1==2)
+                                disp(['Error in simul: Preconditioner is ill-conditioned, in block' num2str(Block_Num,'%3d')])
+                            elseif(flag1==3)
+                                disp(['Error in simul: GMRES stagnated (Two consecutive iterates were the same.), in block' num2str(Block_Num,'%3d')])
+                            end
+                        end
                         ilu_setup.droptol = ilu_setup.droptol/10;
                         reduced = 0;
                     else
                         ya = ya + lambda*dx;
-                        if(is_dynamic)
+                        if is_dynamic
                             y(it_,y_index_eq) = ya';
                         else
                             y(y_index_eq) = ya';
-                        end;
-                    end;
-                end;
-            elseif((stack_solve_algo==3 && is_dynamic) || (options.solve_algo==8 && ~is_dynamic)),
+                        end
+                    end
+                end
+            elseif (stack_solve_algo==3 && is_dynamic) || (options.solve_algo==8 && ~is_dynamic)
                 flag1=1;
-                if (verbose == 1 && ~is_dynamic)
-                    disp('steady: BiCGStab');
+                if verbose == 1 && ~is_dynamic
+                    disp('steady: BiCGStab')
                 end
-                while(flag1>0)
+                while flag1>0
                     [L1, U1]=ilu(g1,ilu_setup);
                     phat = ya - U1 \ (L1 \ r);
-                    if(is_dynamic)
+                    if is_dynamic
                         y(it_,y_index_eq) = phat;
                     else
                         y(y_index_eq) = phat;
-                    end;
-                    if(is_dynamic)
+                    end
+                    if is_dynamic
                         [r, y, g1, g2, g3] = feval(fname, y, x, params, ...
                                                    steady_state, it_, 0);
                     else
                         [r, y, g1] = feval(fname, y, x, params);
-                    end;
-                    if max(abs(r)) >= options.solve_tolf
+                    end
+                    if max(abs(r))>=options.solve_tolf
                         [dx,flag1] = bicgstab(g1,-r,1e-7,Blck_size,L1,U1);
                     else
                         flag1 = 0;
                         dx = phat - ya;
-                    end;
-                    if (flag1>0 || reduced)
-                        if(flag1==1)
-                            disp(['Error in simul: No convergence inside BICGSTAB after ' num2str(iter,'%6d') ' iterations, in block' num2str(Block_Num,'%3d')]);
-                        elseif(flag1==2)
-                            disp(['Error in simul: Preconditioner is ill-conditioned, in block' num2str(Block_Num,'%3d')]);
-                        elseif(flag1==3)
-                            disp(['Error in simul: GMRES stagnated (Two consecutive iterates were the same.), in block' num2str(Block_Num,'%3d')]);
-                        end;
+                    end
+                    if flag1>0 || reduced
+                        if verbose
+                            if(flag1==1)
+                                disp(['Error in simul: No convergence inside BICGSTAB after ' num2str(iter,'%6d') ' iterations, in block' num2str(Block_Num,'%3d')])
+                            elseif(flag1==2)
+                                disp(['Error in simul: Preconditioner is ill-conditioned, in block' num2str(Block_Num,'%3d')])
+                            elseif(flag1==3)
+                                disp(['Error in simul: GMRES stagnated (Two consecutive iterates were the same.), in block' num2str(Block_Num,'%3d')])
+                            end
+                        end
                         ilu_setup.droptol = ilu_setup.droptol/10;
                         reduced = 0;
                     else
                         ya = ya + lambda*dx;
-                        if(is_dynamic)
+                        if is_dynamic
                             y(it_,y_index_eq) = ya';
                         else
                             y(y_index_eq) = ya';
-                        end;
-                    end;
-                end;
+                        end
+                    end
+                end
             else
-                disp('unknown option : ');
-                if(is_dynamic)
-                    disp(['options_.stack_solve_algo = ' num2str(stack_solve_algo) ' not implemented']);
-                else
-                    disp(['options_.solve_algo = ' num2str(options.solve_algo) ' not implemented']);
-                end;
+                if verbose
+                    disp('unknown option : ')
+                    if is_dynamic
+                        disp(['options_.stack_solve_algo = ' num2str(stack_solve_algo) ' not implemented'])
+                    else
+                        disp(['options_.solve_algo = ' num2str(options.solve_algo) ' not implemented'])
+                    end
+                end
                 info = -Block_Num*10;
-                return;
-            end;
+                return
+            end
             iter=iter+1;
             max_resa = max_res;
         end
     end
     if cvg==0
-        if(cutoff == 0)
-            fprintf('Error in simul: Convergence not achieved in block %d, at time %d, after %d iterations.\n Increase "options_.simul.maxit\".\n',Block_Num, it_,iter);
-        else
-            fprintf('Error in simul: Convergence not achieved in block %d, at time %d, after %d iterations.\n Increase "options_.simul.maxit" or set "cutoff=0" in model options.\n',Block_Num, it_,iter);
-        end;
+        if verbose
+            if cutoff == 0
+                fprintf('Error in simul: Convergence not achieved in block %d, at time %d, after %d iterations.\n Increase "options_.simul.maxit\".\n',Block_Num, it_,iter);
+            else
+                fprintf('Error in simul: Convergence not achieved in block %d, at time %d, after %d iterations.\n Increase "options_.simul.maxit" or set "cutoff=0" in model options.\n',Block_Num, it_,iter);
+            end
+        end
         if(is_dynamic)
             oo_.deterministic_simulation.status = 0;
             oo_.deterministic_simulation.error = max_res;
@@ -410,10 +389,11 @@ for it_=start:incr:finish
             oo_.deterministic_simulation.block(Block_Num).iterations = iter;
         end;
         info = -Block_Num*10;
-        return;
+        return
     end
 end
-if(is_dynamic)
+
+if is_dynamic
     info = 1;
     oo_.deterministic_simulation.status = 1;
     oo_.deterministic_simulation.error = max_res;
@@ -423,12 +403,11 @@ if(is_dynamic)
     oo_.deterministic_simulation.block(Block_Num).iterations = iter;
 else
     info = 0;
-end;
-return;
+end
 
 function [err, G]=local_fname(yl, x, params, steady_state, y, y_index_eq, fname, is_csolve)
 y(y_index_eq) = yl;
 [err, y, G] = feval(fname, y, x, params, steady_state, 0);
 if(is_csolve)
     G = full(G);
-end;
+end
\ No newline at end of file
diff --git a/matlab/solve_perfect_foresight_model.m b/matlab/solve_perfect_foresight_model.m
index 4a6464089ea78a35fa8744e8a87c3fa7272a40df..5de112ad8a6dd3d65ca8da7c93f94816aebef796 100644
--- a/matlab/solve_perfect_foresight_model.m
+++ b/matlab/solve_perfect_foresight_model.m
@@ -32,6 +32,11 @@ function [flag,endo_simul,err] = solve_perfect_foresight_model(endo_simul,exo_si
         fprintf('\n') ;
     end
 
+    if pfm.use_bytecode
+        [flag, endo_simul]=bytecode(Y, exo_simul, pfm.params);
+        return;
+    end
+
     z = Y(find(pfm.lead_lag_incidence'));
     [d1,jacobian] = model_dynamic(z,exo_simul,pfm.params,pfm.steady_state,2);
 
diff --git a/matlab/solve_two_boundaries.m b/matlab/solve_two_boundaries.m
index e8da69742d5b1de2b932f083a16224304e73d570..cf00fdacb359b74d33a02e08b0edd27249e249bf 100644
--- a/matlab/solve_two_boundaries.m
+++ b/matlab/solve_two_boundaries.m
@@ -1,4 +1,4 @@
-function [y, oo]= solve_two_boundaries(fname, y, x, params, steady_state, y_index, nze, periods, y_kmin_l, y_kmax_l, is_linear, Block_Num, y_kmin, maxit_, solve_tolf, lambda, cutoff, stack_solve_algo, M, oo)
+function [y, oo]= solve_two_boundaries(fname, y, x, params, steady_state, y_index, nze, periods, y_kmin_l, y_kmax_l, is_linear, Block_Num, y_kmin, maxit_, solve_tolf, lambda, cutoff, stack_solve_algo,options,M, oo)
 % Computes the deterministic simulation of a block of equation containing
 % both lead and lag variables using relaxation methods 
 %
@@ -46,7 +46,7 @@ function [y, oo]= solve_two_boundaries(fname, y, x, params, steady_state, y_inde
 %   none.
 %  
 
-% Copyright (C) 1996-2013 Dynare Team
+% Copyright (C) 1996-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -63,6 +63,8 @@ function [y, oo]= solve_two_boundaries(fname, y, x, params, steady_state, y_inde
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
+verbose = options.verbosity;
+
 cvg=0;
 iter=0;
 Per_u_=0;
@@ -80,91 +82,94 @@ max_resa=1e100;
 Jacobian_Size=Blck_size*(y_kmin+y_kmax_l +periods);
 g1=spalloc( Blck_size*periods, Jacobian_Size, nze*periods);
 reduced = 0;
-while ~(cvg==1 || iter>maxit_),
-    [r, y, g1, g2, g3, b]=feval(fname, y, x, params, steady_state, periods, 0, y_kmin, Blck_size);
+while ~(cvg==1 || iter>maxit_)
+    [r, y, g1, g2, g3, b]=feval(fname, y, x, params, steady_state, periods, 0, y_kmin, Blck_size,options.periods);
     preconditioner = 2;
     g1a=g1(:, y_kmin*Blck_size+1:(periods+y_kmin)*Blck_size);
     term1 = g1(:, 1:y_kmin_l*Blck_size)*reshape(y(1+y_kmin-y_kmin_l:y_kmin,y_index)',1,y_kmin_l*Blck_size)';
     term2 = g1(:, (periods+y_kmin_l)*Blck_size+1:(periods+y_kmin_l+y_kmax_l)*Blck_size)*reshape(y(periods+y_kmin+1:periods+y_kmin+y_kmax_l,y_index)',1,y_kmax_l*Blck_size)';
     b = b - term1 - term2;
     [max_res, max_indx]=max(max(abs(r')));
-    if(~isreal(r))
+    if ~isreal(r)
         max_res = (-max_res^2)^0.5;
     end;
-    %     if(~isreal(r))
-    %       max_res=(-(max(max(abs(r))))^2)^0.5;
-    %     else
-    %       max_res=max(max(abs(r)));
-    %     end;
-    if(~isreal(max_res) || isnan(max_res))
+    if ~isreal(max_res) || isnan(max_res)
         cvg = 0;
     elseif(is_linear && iter>0)
         cvg = 1;
     else
         cvg=(max_res<solve_tolf);
-    end;
-    if(~cvg)
-        if(iter>0)
-            if(~isreal(max_res) || isnan(max_res) || (max_resa<max_res && iter>1))
-                if(~isreal(max_res))
+    end
+    if ~cvg
+        if iter>0
+            if ~isreal(max_res) || isnan(max_res) || (max_resa<max_res && iter>1)
+                if verbose && ~isreal(max_res)
                     disp(['Variable ' M.endo_names(max_indx,:) ' (' int2str(max_indx) ') returns an undefined value']);
-                end;
-                if(isnan(max_res))
+                end
+                if isnan(max_res)
                     detJ=det(g1aa);
-                    if(abs(detJ)<1e-7)
+                    if abs(detJ)<1e-7
                         max_factor=max(max(abs(g1aa)));
                         ze_elem=sum(diag(g1aa)<cutoff);
-                        disp([num2str(full(ze_elem),'%d') ' elements on the Jacobian diagonal are below the cutoff (' num2str(cutoff,'%f') ')']);
-                        if(correcting_factor<max_factor)
+                        if verbose
+                            disp([num2str(full(ze_elem),'%d') ' elements on the Jacobian diagonal are below the cutoff (' num2str(cutoff,'%f') ')']);
+                        end
+                        if correcting_factor<max_factor
                             correcting_factor=correcting_factor*4;
-                            disp(['The Jacobain matrix is singular, det(Jacobian)=' num2str(detJ,'%f') '.']);
-                            disp(['    trying to correct the Jacobian matrix:']);
-                            disp(['    correcting_factor=' num2str(correcting_factor,'%f') ' max(Jacobian)=' num2str(full(max_factor),'%f')]);
+                            if verbose
+                                disp(['The Jacobain matrix is singular, det(Jacobian)=' num2str(detJ,'%f') '.']);
+                                disp(['    trying to correct the Jacobian matrix:']);
+                                disp(['    correcting_factor=' num2str(correcting_factor,'%f') ' max(Jacobian)=' num2str(full(max_factor),'%f')]);
+                            end
                             dx = (g1aa+correcting_factor*speye(periods*Blck_size))\ba- ya;
                             y(1+y_kmin:periods+y_kmin,y_index)=reshape((ya_save+lambda*dx)',length(y_index),periods)';
                             continue;
                         else
                             disp('The singularity of the jacobian matrix could not be corrected');
-                            return;
-                        end;
-                    end;
-                elseif(lambda>1e-8)
+                            return
+                        end
+                    end
+                elseif lambda>1e-8
                     lambda=lambda/2;
                     reduced = 1;
-                    disp(['reducing the path length: lambda=' num2str(lambda,'%f')]);
+                    if verbose
+                        disp(['reducing the path length: lambda=' num2str(lambda,'%f')]);
+                    end
                     y(1+y_kmin:periods+y_kmin,y_index)=reshape((ya_save+lambda*dx)',length(y_index),periods)';
-                    continue;
+                    continue
                 else
-                    if(cutoff == 0)
-                        fprintf('Error in simul: Convergence not achieved in block %d, after %d iterations.\n Increase "options_.simul.maxit".\n',Block_Num, iter);
-                    else
-                        fprintf('Error in simul: Convergence not achieved in block %d, after %d iterations.\n Increase "options_.simul.maxit" or set "cutoff=0" in model options.\n',Block_Num, iter);
-                    end;
+                    if verbose
+                        if cutoff==0
+                            fprintf('Error in simul: Convergence not achieved in block %d, after %d iterations.\n Increase "options_.simul.maxit".\n',Block_Num, iter);
+                        else
+                            fprintf('Error in simul: Convergence not achieved in block %d, after %d iterations.\n Increase "options_.simul.maxit" or set "cutoff=0" in model options.\n',Block_Num, iter);
+                        end
+                    end
                     oo.deterministic_simulation.status = 0;
                     oo.deterministic_simulation.error = max_res;
                     oo.deterministic_simulation.iterations = iter;
                     oo.deterministic_simulation.block(Block_Num).status = 0;% Convergency failed.
                     oo.deterministic_simulation.block(Block_Num).error = max_res;
                     oo.deterministic_simulation.block(Block_Num).iterations = iter;
-                    return;
-                end;
+                    return
+                end
             else
-                if(lambda<1)
+                if lambda<1
                     lambda=max(lambda*2, 1);
-                end;
-            end;
-        end;
+                end
+            end
+        end
         ya = reshape(y(y_kmin+1:y_kmin+periods,y_index)',1,periods*Blck_size)';
         ya_save=ya;
         g1aa=g1a;
         ba=b;
         max_resa=max_res;
-        if(stack_solve_algo==0),
+        if stack_solve_algo==0
             dx = g1a\b- ya;
             ya = ya + lambda*dx;
             y(1+y_kmin:periods+y_kmin,y_index)=reshape(ya',length(y_index),periods)';
-        elseif(stack_solve_algo==1),
-            for t=1:periods;
+        elseif stack_solve_algo==1
+            for t=1:periods
                 first_elem = (t-1)*Blck_size+1;
                 last_elem = t*Blck_size;
                 next_elem = (t+1)*Blck_size;
@@ -177,19 +182,19 @@ while ~(cvg==1 || iter>maxit_),
                 g1a(Elem, Elem_1) = S1;
                 b(Elem) = B1_inv * b(Elem);
                 g1a(Elem, Elem) = ones(Blck_size, Blck_size);
-                if (t < periods)
+                if t<periods
                     g1a(Elem_1, Elem_1) = g1a(Elem_1, Elem_1) - g1a(Elem_1, Elem) * S1;
                     b(Elem_1) = b(Elem_1) - g1a(Elem_1, Elem) * b(Elem);
                     g1a(Elem_1, Elem) = zeros(Blck_size, Blck_size);
-                end;
-            end;
+                end
+            end
             za = b(Elem);
             zaa = za;
             y_Elem = (periods - 1) * Blck_size + 1:(periods) * Blck_size;
             dx = ya;
             dx(y_Elem) = za - ya(y_Elem);
             ya(y_Elem) = ya(y_Elem) + lambda*dx(y_Elem);
-            for t=periods-1:-1:1;
+            for t=periods-1:-1:1
                 first_elem = (t-1)*Blck_size+1;
                 last_elem = t*Blck_size;
                 next_elem = (t+1)*Blck_size;
@@ -201,29 +206,29 @@ while ~(cvg==1 || iter>maxit_),
                 dx(y_Elem) = za - ya(y_Elem);
                 ya(y_Elem) = ya(y_Elem) + lambda*dx(y_Elem);
                 y(y_kmin + t, y_index) = ya(y_Elem);
-            end;
-        elseif(stack_solve_algo==2),
+            end
+        elseif stack_solve_algo==2
             flag1=1;
-            while(flag1>0)
-                if preconditioner == 2
+            while flag1>0
+                if preconditioner==2
                     [L1, U1]=ilu(g1a,ilu_setup);
-                elseif preconditioner == 3
+                elseif preconditioner==3
                     Size = Blck_size;
-                     gss1 =  g1a(Size + 1: 2*Size,Size + 1: 2*Size) + g1a(Size + 1: 2*Size,2*Size+1: 3*Size);
-                     [L1, U1]=lu(gss1);
-                     L(1:Size,1:Size) = L1;
-                     U(1:Size,1:Size) = U1;
-                     gss2 = g1a(Size + 1: 2*Size,1: Size) + g1a(Size + 1: 2*Size,Size+1: 2*Size) + g1a(Size + 1: 2*Size,2*Size+1: 3*Size);
-                     [L2, U2]=lu(gss2);
-                     L(Size+1:(periods-1)*Size,Size+1:(periods-1)*Size) = kron(eye(periods-2), L2);
-                     U(Size+1:(periods-1)*Size,Size+1:(periods-1)*Size) = kron(eye(periods-2), U2);
-                     gss2 = g1a(Size + 1: 2*Size,1: Size) + g1a(Size + 1: 2*Size,Size+1: 2*Size);
-                     [L3, U3]=lu(gss2);
-                     L((periods-1)*Size+1:periods*Size,(periods-1)*Size+1:periods*Size) = L3;
-                     U((periods-1)*Size+1:periods*Size,(periods-1)*Size+1:periods*Size) = U3;
-                     L1 = L;
-                     U1 = U;
-                elseif preconditioner == 4
+                    gss1 =  g1a(Size + 1: 2*Size,Size + 1: 2*Size) + g1a(Size + 1: 2*Size,2*Size+1: 3*Size);
+                    [L1, U1]=lu(gss1);
+                    L(1:Size,1:Size) = L1;
+                    U(1:Size,1:Size) = U1;
+                    gss2 = g1a(Size + 1: 2*Size,1: Size) + g1a(Size + 1: 2*Size,Size+1: 2*Size) + g1a(Size + 1: 2*Size,2*Size+1: 3*Size);
+                    [L2, U2]=lu(gss2);
+                    L(Size+1:(periods-1)*Size,Size+1:(periods-1)*Size) = kron(eye(periods-2), L2);
+                    U(Size+1:(periods-1)*Size,Size+1:(periods-1)*Size) = kron(eye(periods-2), U2);
+                    gss2 = g1a(Size + 1: 2*Size,1: Size) + g1a(Size + 1: 2*Size,Size+1: 2*Size);
+                    [L3, U3]=lu(gss2);
+                    L((periods-1)*Size+1:periods*Size,(periods-1)*Size+1:periods*Size) = L3;
+                    U((periods-1)*Size+1:periods*Size,(periods-1)*Size+1:periods*Size) = U3;
+                    L1 = L;
+                    U1 = U;
+                elseif preconditioner==4
                     Size = Blck_size;
                     gss1 =  g1a(1: 3*Size, 1: 3*Size);
                     [L, U] = lu(gss1);
@@ -231,31 +236,33 @@ while ~(cvg==1 || iter>maxit_),
                     U1 = kron(eye(ceil(periods/3)),U);
                     L1 = L1(1:periods * Size, 1:periods * Size);
                     U1 = U1(1:periods * Size, 1:periods * Size);
-                end;
+                end
                 [za,flag1] = gmres(g1a,b,Blck_size,1e-6,Blck_size*periods,L1,U1);
                 if (flag1>0 || reduced)
-                    if(flag1==1)
-                        disp(['Error in simul: No convergence inside GMRES after ' num2str(periods*10,'%6d') ' iterations, in block ' num2str(Blck_size,'%3d')]);
-                    elseif(flag1==2)
-                        disp(['Error in simul: Preconditioner is ill-conditioned, in block ' num2str(Blck_size,'%3d')]);
-                    elseif(flag1==3)
-                        disp(['Error in simul: GMRES stagnated (Two consecutive iterates were the same.), in block ' num2str(Blck_size,'%3d')]);
-                    end;
+                    if verbose
+                        if flag1==1
+                            disp(['Error in simul: No convergence inside GMRES after ' num2str(periods*10,'%6d') ' iterations, in block ' num2str(Blck_size,'%3d')]);
+                        elseif flag1==2
+                            disp(['Error in simul: Preconditioner is ill-conditioned, in block ' num2str(Blck_size,'%3d')]);
+                        elseif flag1==3
+                            disp(['Error in simul: GMRES stagnated (Two consecutive iterates were the same.), in block ' num2str(Blck_size,'%3d')]);
+                        end
+                    end
                     ilu_setup.droptol = ilu_setup.droptol/10;
                     reduced = 0;
                 else
                     dx = za - ya;
                     ya = ya + lambda*dx;
                     y(1+y_kmin:periods+y_kmin,y_index)=reshape(ya',length(y_index),periods)';
-                end;
-            end;
-        elseif(stack_solve_algo==3),
+                end
+            end
+        elseif stack_solve_algo==3
             flag1=1;
-            while(flag1>0)
-                if preconditioner == 2
+            while flag1>0
+                if preconditioner==2
                     [L1, U1]=ilu(g1a,ilu_setup);
                     [za,flag1] = bicgstab(g1a,b,1e-7,Blck_size*periods,L1,U1);
-                elseif (preconditioner == 3)
+                elseif preconditioner==3
                     Size = Blck_size;
                     gss0 = g1a(Size + 1: 2*Size,1: Size) + g1a(Size + 1: 2*Size,Size+1: 2*Size) + g1a(Size + 1: 2*Size,2*Size+1: 3*Size);
                     [L1, U1]=lu(gss0);
@@ -273,24 +280,26 @@ while ~(cvg==1 || iter>maxit_),
                     L1 = kron(eye(periods),L1);
                     U1 = kron(eye(periods),U1);
                     [za,flag1] = bicgstab(g1a,b,1e-7,Blck_size*periods,L1,U1);
-                end;
-                if (flag1>0 || reduced)
-                    if(flag1==1)
-                        disp(['Error in simul: No convergence inside BICGSTAB after ' num2str(periods*10,'%6d') ' iterations, in block ' num2str(Blck_size,'%3d')]);
-                    elseif(flag1==2)
-                        disp(['Error in simul: Preconditioner is ill-conditioned, in block ' num2str(Blck_size,'%3d')]);
-                    elseif(flag1==3)
-                        disp(['Error in simul: GMRES stagnated (Two consecutive iterates were the same.), in block ' num2str(Blck_size,'%3d')]);
-                    end;
+                end
+                if flag1>0 || reduced
+                    if verbose
+                        if flag1==1
+                            disp(['Error in simul: No convergence inside BICGSTAB after ' num2str(periods*10,'%6d') ' iterations, in block ' num2str(Blck_size,'%3d')]);
+                        elseif flag1==2
+                            disp(['Error in simul: Preconditioner is ill-conditioned, in block ' num2str(Blck_size,'%3d')]);
+                        elseif flag1==3
+                            disp(['Error in simul: GMRES stagnated (Two consecutive iterates were the same.), in block ' num2str(Blck_size,'%3d')]);
+                        end
+                    end
                     ilu_setup.droptol = ilu_setup.droptol/10;
                     reduced = 0;
                 else
                     dx = za - ya;
                     ya = ya + lambda*dx;
                     y(1+y_kmin:periods+y_kmin,y_index)=reshape(ya',length(y_index),periods)';
-                end;
-            end;
-        elseif(stack_solve_algo==4),
+                end
+            end
+        elseif stack_solve_algo==4
             ra = reshape(r(:, y_kmin+1:periods+y_kmin),periods*Blck_size, 1);
             stpmx = 100 ;
             stpmax = stpmx*max([sqrt(ya'*ya);size(y_index,2)]);
@@ -298,29 +307,34 @@ while ~(cvg==1 || iter>maxit_),
             g = (ra'*g1a)';
             f = 0.5*ra'*ra;
             p = -g1a\ra;
-            [yn,f,ra,check]=lnsrch1(ya,f,g,p,stpmax, ...
-                                    'lnsrch1_wrapper_two_boundaries',nn,nn,  fname, y, y_index, x, params, steady_state, periods, y_kmin, Blck_size);
+            [yn,f,ra,check]=lnsrch1(ya,f,g,p,stpmax,'lnsrch1_wrapper_two_boundaries',nn,nn,  fname, y, y_index,x, params, steady_state, periods, y_kmin, Blck_size,options.periods);
             dx = ya - yn;
             y(1+y_kmin:periods+y_kmin,y_index)=reshape(yn',length(y_index),periods)';
         end
     end
     iter=iter+1;
-    disp(['iteration: ' num2str(iter,'%d') ' error: ' num2str(max_res,'%e')]);
-end;
+    if verbose
+        disp(['iteration: ' num2str(iter,'%d') ' error: ' num2str(max_res,'%e')]);
+    end
+end
+
 if (iter>maxit_)
-    disp(['No convergence after ' num2str(iter,'%4d') ' iterations in Block ' num2str(Block_Num,'%d')]);
+    if verbose
+        printline(41)
+        %disp(['No convergence after ' num2str(iter,'%4d') ' iterations in Block ' num2str(Block_Num,'%d')])
+    end
     oo.deterministic_simulation.status = 0;
     oo.deterministic_simulation.error = max_res;
     oo.deterministic_simulation.iterations = iter;
     oo.deterministic_simulation.block(Block_Num).status = 0;% Convergency failed.
     oo.deterministic_simulation.block(Block_Num).error = max_res;
     oo.deterministic_simulation.block(Block_Num).iterations = iter;
-    return;
+    return
 end
+
 oo.deterministic_simulation.status = 1;
 oo.deterministic_simulation.error = max_res;
 oo.deterministic_simulation.iterations = iter;
 oo.deterministic_simulation.block(Block_Num).status = 1;% Convergency obtained.
 oo.deterministic_simulation.block(Block_Num).error = max_res;
-oo.deterministic_simulation.block(Block_Num).iterations = iter;
-return;
+oo.deterministic_simulation.block(Block_Num).iterations = iter;
\ No newline at end of file
diff --git a/matlab/stoch_simul.m b/matlab/stoch_simul.m
index 2009ca08dd886c72b7aa35de89cfed0a3da54e6f..e9a4e5e2d1a995c16aff2881a41bd75622b1c25d 100644
--- a/matlab/stoch_simul.m
+++ b/matlab/stoch_simul.m
@@ -1,6 +1,6 @@
 function info=stoch_simul(var_list)
 
-% Copyright (C) 2001-2013 Dynare Team
+% Copyright (C) 2001-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -34,8 +34,6 @@ if options_.linear
 end
 if options_.order == 1
     options_.replic = 1;
-elseif options_.order == 3
-    options_.k_order_solver = 1;
 end
 
 if isempty(options_.qz_criterium)
@@ -84,7 +82,7 @@ else
     [oo_.dr,info,M_,options_,oo_] = resol(0,M_,options_,oo_);
 end
 
-if options_.loglinear %log steady state for correct display of decision rules and simulations
+if options_.loglinear && isfield(oo_.dr,'ys') %log steady state for correct display of decision rules and simulations
     oo_.dr.ys=log(oo_.dr.ys);
     oo_.steady_state=log(oo_.steady_state);
     options_old.logged_steady_state = 1;
diff --git a/matlab/stochastic_solvers.m b/matlab/stochastic_solvers.m
index 64b9b2c810933f2239c54e60f163334703f582c9..d8374c48f33dfc5882ccb7107d4a496305bb7eda 100644
--- a/matlab/stochastic_solvers.m
+++ b/matlab/stochastic_solvers.m
@@ -1,7 +1,7 @@
 function [dr,info] = stochastic_solvers(dr,task,M_,options_,oo_)
 % function [dr,info,M_,options_,oo_] = stochastic_solvers(dr,task,M_,options_,oo_)
-% computes the reduced form solution of a rational expectation model (first or second order
-% approximation of the stochastic model around the deterministic steady state). 
+% computes the reduced form solution of a rational expectations model (first, second or third 
+% order approximation of the stochastic model around the deterministic steady state). 
 %
 % INPUTS
 %   dr         [matlab structure] Decision rules for stochastic simulations.
diff --git a/matlab/trace_plot.m b/matlab/trace_plot.m
index 71fa7e74282124b0b25a489c55f65f4ff599f3e0..bc732273762ff5445e83d62e5f52b2ecc31ee42a 100644
--- a/matlab/trace_plot.m
+++ b/matlab/trace_plot.m
@@ -1,13 +1,14 @@
 function trace_plot(options_,M_,estim_params_,type,blck,name1,name2)
-% This function build trace plot for the metropolis hastings draws.
-% 
+% This function builds trace plot for the Metropolis-Hastings draws.
 %
 % INPUTS 
 %
 %   options_        [structure]    Dynare structure.
 %   M_              [structure]    Dynare structure (related to model definition).
 %   estim_params_   [structure]    Dynare structure (related to estimation).
-%   type            [string]       'DeepParameter', 'MeasurementError' (for measurement equation error) or 'StructuralShock' (for structural shock).
+%   type            [string]       'DeepParameter', 'MeasurementError' (for measurement equation error),
+%                                  'StructuralShock' (for structural shock)
+%                                  or 'PosteriorDensity (for posterior density)'
 %   blck            [integer]      Number of the mh chain.
 %   name1           [string]       Object name.
 %   name2           [string]       Object name. 
@@ -17,7 +18,7 @@ function trace_plot(options_,M_,estim_params_,type,blck,name1,name2)
 %        
 % SPECIAL REQUIREMENTS
 
-% Copyright (C) 2003-2013 Dynare Team
+% Copyright (C) 2003-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -35,10 +36,15 @@ function trace_plot(options_,M_,estim_params_,type,blck,name1,name2)
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
 % Cet the column index:
-if nargin<7    
-    column = name2index(options_, M_, estim_params_, type, name1);
+if strcmpi(type,'PosteriorDensity')
+    column=0;
+    name1='';
 else
-    column = name2index(options_, M_, estim_params_, type, name1, name2);
+    if nargin<7    
+        column = name2index(options_, M_, estim_params_, type, name1);
+    else
+        column = name2index(options_, M_, estim_params_, type, name1, name2);
+    end
 end
 
 if isempty(column)
@@ -75,6 +81,8 @@ elseif strcmpi(type,'MeasurementError')
     else
         TYPE = 'the correlation between measurement errors ';
     end
+elseif strcmpi(type,'PosteriorDensity')
+    TYPE='the posterior density';
 end
 
 if nargin<7
@@ -111,9 +119,15 @@ legend({'MCMC draw';[num2str(N) ' period moving average']},'Location','NorthWest
 if ~exist(M_.fname, 'dir')
     mkdir('.',M_.fname);
 end
-if ~exist([M_.fname filesep 'graphs'])
+if ~exist([M_.fname filesep 'graphs'],'dir')
     mkdir(M_.fname,'graphs');
 end
-plot_name=get_the_name(column,0,M_,estim_params_,options_);
+
+%get name for plot
+if strcmpi(type,'PosteriorDensity')
+    plot_name='Posterior';
+else
+    plot_name=get_the_name(column,0,M_,estim_params_,options_);
+end
 dyn_saveas(hh,[M_.fname, filesep, 'graphs', filesep, 'TracePlot_' plot_name],options_)
 
diff --git a/matlab/reports/areParensNext.m b/matlab/utilities/general/delete_stale_file.m
similarity index 73%
rename from matlab/reports/areParensNext.m
rename to matlab/utilities/general/delete_stale_file.m
index eb485d762f8b18018829aaa883c234fd526e98bc..8ac8b799635e88eaedc4e03093a3b3201ee5dcbb 100644
--- a/matlab/reports/areParensNext.m
+++ b/matlab/utilities/general/delete_stale_file.m
@@ -1,7 +1,8 @@
-function tf = areParensNext(S)
-%function tf = areParensNext(S)
+function delete_stale_file(fname)
+% function delete_old_files(fname)
+% Checks for presence of files and deletes them if necessary
 
-% Copyright (C) 2013 Dynare Team
+% Copyright (C) 2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -18,9 +19,8 @@ function tf = areParensNext(S)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-if length(S) > 1 && strcmp(S(2).type, '()')
-    tf = true;
-else
-    tf = false;
+Files_info = dir(fname);
+if length(Files_info)>0
+    delete(fname)
 end
-end
\ No newline at end of file
+
diff --git a/matlab/utilities/general/dyn_mex.m b/matlab/utilities/general/dyn_mex.m
new file mode 100644
index 0000000000000000000000000000000000000000..fe6b0555d37ee828322ee790ea1f17c409a5bc8b
--- /dev/null
+++ b/matlab/utilities/general/dyn_mex.m
@@ -0,0 +1,110 @@
+function dyn_mex(win_compiler,basename,force)
+
+% Compile Dynare model dlls when model option use_dll is used
+% if C file is fresher than mex file 
+%
+% INPUTS
+%  o win_compiler  str  compiler used under Windows (unused under Linux or OSX): 
+%                       'msvc' (MS Visual C)
+%                        'cygwin'
+%  o basename      str  filenames base
+%  o force         bool recompile if 1 
+%  
+% OUTPUTS 
+%  none
+%
+
+    
+% Copyright (C) 2015 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+Dc = dir([basename '_dynamic.c']);
+Dmex = dir([basename '_dynamic.' mexext]);
+
+% compile only if date of C file is greater than date of mex file
+% and force is not True
+if ~isempty(Dmex)
+    if (Dmex.datenum > Dc.datenum) && ~force
+        disp('Mex files are newer than the source: not recompiled')
+        return
+    end
+end
+
+if ~exist('OCTAVE_VERSION')
+    % Some mex commands are enclosed in an eval(), because otherwise it will make Octave fail
+    if ispc
+      if msvc
+          % MATLAB/Windows + Microsoft Visual C++
+          eval(['mex -O LINKFLAGS="$LINKFLAGS /export:Dynamic" ' basename '_dynamic.c ' basename '_dynamic_mex.c'])
+          eval(['mex -O LINKFLAGS="$LINKFLAGS /export:Dynamic" ' basename '_static.c ' basename '_static_mex.c'])
+      elseif cygwin
+          % MATLAB/Windows + Cygwin g++
+          eval(['mex -O PRELINK_CMDS1="echo EXPORTS > mex.def & echo ' ...
+                'mexFunction >> mex.def & echo Dynamic >> mex.def" ' ...
+                basename '_dynamic.c ' basename '_dynamic_mex.c'])
+          eval(['mex -O PRELINK_CMDS1="echo EXPORTS > mex.def & echo ' ...
+                'mexFunction >> mex.def & echo Dynamic >> mex.def" ' ...
+                basename '_static.c ' basename '_static_mex.c'])
+      else
+        error(['When using the USE_DLL option, you must give either ' ...
+               '''cygwin'' or ''msvc'' option to the ''dynare'' command'])
+      end
+    elseif isunix
+        % MATLAB/Linux
+        if matlab_ver_less_than('8.3')
+            eval(['mex -O LDFLAGS=''-pthread -shared -Wl,--no-undefined'' ' ...
+                  basename '_dynamic.c ' basename '_dynamic_mex.c'])
+            eval(['mex -O LDFLAGS=''-pthread -shared -Wl,--no-undefined'' ' ...
+                  basename '_static.c ' basename '_static_mex.c'])
+        else
+            eval(['mex -O LINKEXPORT='''' ' basename '_dynamic.c ' basename '_dynamic_mex.c'])
+            eval(['mex -O LINKEXPORT='''' ' basename '_static.c ' basename '_static_mex.c'])
+        end
+    elseif ismac
+        % MATLAB/MacOS
+        if matlab_ver_less_than('8.3')
+            if matlab_ver_less_than('8.1')
+                eval(['mex -O LDFLAGS=''-Wl,-twolevel_namespace -undefined ' ...
+                      'error -arch $ARCHS -Wl,-syslibroot,$SDKROOT ' ...
+                      '-mmacosx-version-min=$MACOSX_DEPLOYMENT_TARGET -bundle'' ' ...
+                      basename '_dynamic.c ' basename '_dynamic_mex.c'])
+                eval(['mex -O LDFLAGS=''-Wl,-twolevel_namespace -undefined ' ...
+                      'error -arch $ARCHS -Wl,-syslibroot,$SDKROOT ' ...
+                      '-mmacosx-version-min=$MACOSX_DEPLOYMENT_TARGET -bundle'' ' ...
+                      basename '_static.c ' basename '_static_mex.c'])
+            else
+                eval(['mex -O LDFLAGS=''-Wl,-twolevel_namespace -undefined ' ...
+                      'error -arch $ARCHS -Wl,-syslibroot,$MW_SDKROOT ' ...
+                      '-mmacosx-version-min=$MACOSX_DEPLOYMENT_TARGET -bundle'' ' ...
+                      basename '_dynamic.c ' basename '_dynamic_mex.c'])
+                eval(['mex -O LDFLAGS=''-Wl,-twolevel_namespace -undefined ' ...
+                      'error -arch $ARCHS -Wl,-syslibroot,$MW_SDKROOT ' ...
+                      '-mmacosx-version-min=$MACOSX_DEPLOYMENT_TARGET -bundle'' ' ...
+                      basename '_static.c ' basename '_static_mex.c'])
+            end
+        else
+            eval(['mex -O LINKEXPORT='''' ' basename '_dynamic.c ' ...
+                  basename '_dynamic_mex.c'])
+            eval(['mex -O LINKEXPORT='''' ' basename '_static.c ' basename ...
+                  '_static_mex.c'])
+        end
+    end
+else
+    % Octave
+    eval(['mex ' basename '_dynamic.c ' basename '_dynamic_mex.c'])
+    eval(['mex ' basename '_static.c ' basename '_static_mex.c'])
+end
diff --git a/matlab/variance_decomposition_mc_analysis.m b/matlab/variance_decomposition_mc_analysis.m
index b4f3f570debe271340b1152978f78fdaa5b23e6f..798b28afee00c4f31e19b0c4e1fb21435df266a6 100644
--- a/matlab/variance_decomposition_mc_analysis.m
+++ b/matlab/variance_decomposition_mc_analysis.m
@@ -1,6 +1,28 @@
 function oo_ = variance_decomposition_mc_analysis(NumberOfSimulations,type,dname,fname,exonames,exo,vartan,var,mh_conf_sig,oo_)
+% function oo_ = variance_decomposition_mc_analysis(NumberOfSimulations,type,dname,fname,exonames,exo,vartan,var,mh_conf_sig,oo_)
 % This function analyses the (posterior or prior) distribution of the
-% endogenous variance decomposition.
+% endogenous variables' variance decomposition.
+% 
+% INPUTS
+%   NumberOfSimulations     [integer]           scalar, number of simulations.
+%   type                    [string]            'prior' or 'posterior'
+%   dname                   [string]            directory name where to save
+%   fname                   [string]            name of the mod-file
+%   exonames                [string]            (n_exo*char_length) character array with names of exogenous variables        
+%   exo                     [string]            name of current exogenous
+%                                               variable
+%   vartan                  [string]            (n_endo*char_length) character array with name
+%                                               of endogenous variables
+%   var                     [integer]         index of the current
+%                                               endogenous variable
+%   mh_conf_sig             [double]            2 by 1 vector with upper
+%                                               and lower bound of HPD intervals
+%   oo_                     [structure]         Dynare structure where the results are saved.
+%
+% OUTPUTS
+%   oo_          [structure]        Dynare structure where the results are saved.
+
+
 
 % Copyright (C) 2008-2013 Dynare Team
 %
diff --git a/matlab/ver_greater_than.m b/matlab/ver_greater_than.m
new file mode 100644
index 0000000000000000000000000000000000000000..91e26f56bdfbf5b12653de2c6d6bf49566cd3e48
--- /dev/null
+++ b/matlab/ver_greater_than.m
@@ -0,0 +1,63 @@
+function tf = ver_greater_than(ver1, ver2)
+%function tf = ver_greater_than(ver1, ver2)
+% ver1 > ver2 ? 1 : 0;
+%
+% INPUTS
+%    ver1    [string]    software version number
+%    ver2    [string]    software version number
+%
+% OUTPUTS
+%    tf      [bool]      true if ver1 > ver2
+%
+% SPECIAL REQUIREMENTS
+%    none
+
+% Copyright (C) 2015 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+tf = true;
+ver1 = strsplit(ver1, {'.', '-'});
+ver2 = strsplit(ver2, {'.', '-'});
+
+maj_ver1 = str2double(ver1{1});
+maj_ver2 = str2double(ver2{1});
+if maj_ver1 > maj_ver2
+    return;
+end
+
+min_ver1 = str2double(ver1{2});
+min_ver2 = str2double(ver2{2});
+if (maj_ver1 == maj_ver2) && (min_ver1 > min_ver2)
+    return;
+end
+
+ismaster1 = isnan(str2double(ver1{3}));
+ismaster2 = isnan(str2double(ver2{3}));
+if (maj_ver1 == maj_ver2) && (min_ver1 == min_ver2) && (ismaster1 && ~ismaster2)
+    return;
+end
+
+if ~ismaster1 && ~ismaster2
+    rev_ver1 = str2double(ver1{3});
+    rev_ver2 = str2double(ver2{3});
+    if (maj_ver1 == maj_ver2) && (min_ver1 == min_ver2) && (rev_ver1 > rev_ver2)
+        return;
+    end
+end
+
+tf = false;
+end
\ No newline at end of file
diff --git a/matlab/reports/@page/display.m b/matlab/ver_greater_than_equal.m
similarity index 65%
rename from matlab/reports/@page/display.m
rename to matlab/ver_greater_than_equal.m
index 19595ba5e30da89e430ce3e9e78357c167715250..84c54040a4ca4a946395aa2e8733bb9975dbcde4 100644
--- a/matlab/reports/@page/display.m
+++ b/matlab/ver_greater_than_equal.m
@@ -1,17 +1,18 @@
-function display(o)
-%function display(o)
-% Display a Page object
+function tf = ver_greater_than_equal(ver1, ver2)
+%function tf = ver_greater_than_equal(ver1, ver2)
+% ver1 >= ver2 ? 1 : 0;
 %
 % INPUTS
-%   o   [page] page object
+%    ver1    [string]    software version number
+%    ver2    [string]    software version number
 %
 % OUTPUTS
-%   none
+%    tf      [bool]      true if ver1 > ver2
 %
 % SPECIAL REQUIREMENTS
-%   none
+%    none
 
-% Copyright (C) 2013-2014 Dynare Team
+% Copyright (C) 2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -28,5 +29,5 @@ function display(o)
 % You should have received a copy of the GNU General Public License
 % along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
 
-display_reporting_object(o);
+tf = ver_greater_than(ver1, ver2) || strcmp(ver1, ver2);
 end
\ No newline at end of file
diff --git a/matlab/ver_less_than.m b/matlab/ver_less_than.m
new file mode 100644
index 0000000000000000000000000000000000000000..7ad2d6425de3425ee555b568d2a236d8e446912e
--- /dev/null
+++ b/matlab/ver_less_than.m
@@ -0,0 +1,63 @@
+function tf = ver_less_than(ver1, ver2)
+%function tf = ver_less_than(ver1, ver2)
+% ver1 < ver2 ? 1 : 0;
+%
+% INPUTS
+%    ver1    [string]    software version number
+%    ver2    [string]    software version number
+%
+% OUTPUTS
+%    tf      [bool]      true if ver1 < ver2
+%
+% SPECIAL REQUIREMENTS
+%    none
+
+% Copyright (C) 2015 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+tf = true;
+ver1 = strsplit(ver1, {'.', '-'});
+ver2 = strsplit(ver2, {'.', '-'});
+
+maj_ver1 = str2double(ver1{1});
+maj_ver2 = str2double(ver2{1});
+if maj_ver1 < maj_ver2
+    return;
+end
+
+min_ver1 = str2double(ver1{2});
+min_ver2 = str2double(ver2{2});
+if (maj_ver1 == maj_ver2) && (min_ver1 < min_ver2)
+    return;
+end
+
+ismaster1 = isnan(str2double(ver1{3}));
+ismaster2 = isnan(str2double(ver2{3}));
+if (maj_ver1 == maj_ver2) && (min_ver1 == min_ver2) && (~ismaster1 && ismaster2)
+    return;
+end
+
+if ~ismaster1 && ~ismaster2
+    rev_ver1 = str2double(ver1{3});
+    rev_ver2 = str2double(ver2{3});
+    if (maj_ver1 == maj_ver2) && (min_ver1 == min_ver2) && (rev_ver1 < rev_ver2)
+        return;
+    end
+end
+
+tf = false;
+end
\ No newline at end of file
diff --git a/matlab/warning_config.m b/matlab/warning_config.m
index 6b6f533063e40fa970e678ac4a430a5e63bc5d8c..3b9f45d63e5fd128b91900645881a395931426b2 100644
--- a/matlab/warning_config.m
+++ b/matlab/warning_config.m
@@ -10,7 +10,7 @@ function warning_config()
 % SPECIAL REQUIREMENTS
 %   none
 
-% Copyright (C) 2008-2013 Dynare Team
+% Copyright (C) 2008-2015 Dynare Team
 %
 % This file is part of Dynare.
 %
@@ -34,7 +34,11 @@ warning('on', 'backtrace');
 
 if isoctave
     warning('off', 'Octave:separator-insert');
-    warning('off', 'Octave:matlab-incompatible');
+    if octave_ver_less_than('4.0')
+        warning('off', 'Octave:matlab-incompatible');
+    else
+        warning('off', 'Octave:language-extension');
+    end
     warning('off', 'Octave:single-quote-string');
     warning('off', 'Octave:missing-semicolon');
     warning('off', 'Octave:empty-list-elements');
@@ -43,11 +47,7 @@ if isoctave
     warning('off', 'Octave:str-to-num');
     warning('off', 'Octave:array-as-scalar');
     warning('off', 'Octave:array-as-vector');
-    if octave_ver_less_than('3.6')
-        warning('off', 'Octave:string-concat');
-    else
-        warning('off', 'Octave:mixed-string-concat');
-    end
+    warning('off', 'Octave:mixed-string-concat');
     warning('off', 'Octave:variable-switch-label');
     warning('off', 'Octave:fortran-indexing');
 else
diff --git a/matlab/write_table_prior.m b/matlab/write_table_prior.m
new file mode 100644
index 0000000000000000000000000000000000000000..3c6c847c6a689705e440aaee2d764d6b08b39f4d
--- /dev/null
+++ b/matlab/write_table_prior.m
@@ -0,0 +1,142 @@
+function write_table_prior(lb, ub, DynareOptions, ModelInfo, BayesInfo, EstimationInfo)
+    
+% This routine builds a latex table with some descriptive statistics about the prior distribution. 
+
+% Copyright (C) 2015 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+PriorNames = { 'Beta' , 'Gamma' , 'Gaussian' , 'Inverted Gamma' , 'Uniform' , 'Inverted Gamma -- 2' };
+
+if size(ModelInfo.param_names,1)==size(ModelInfo.param_names_tex,1)% All the parameters have a TeX name.
+    fidTeX = fopen('priors_data.tex','w+');
+    fprintf(fidTeX,'%% TeX-table generated by Dynare.\n');
+    fprintf(fidTeX,'%% Prior Information\n');
+    fprintf(fidTeX,['%% ' datestr(now,0)]);
+    fprintf(fidTeX,' \n');
+    fprintf(fidTeX,' \n');
+    fprintf(fidTeX,'\\begin{center}\n');
+    fprintf(fidTeX,'\\begin{longtable}{l|cccccccc} \n');
+    fprintf(fidTeX,'\\caption{Prior information (parameters)}\\\\\n ');
+    fprintf(fidTeX,'\\label{Table:Prior}\\\\\n');
+    fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+    fprintf(fidTeX,'  & Prior distribution & Prior mean & Prior mode & Prior s.d. & Lower Bound & Upper Bound & LB Untrunc. 80\\%% HPDI & UB Untrunc. 80\\%% HPDI  \\\\ \n');
+    fprintf(fidTeX,'\\hline \\endfirsthead \n');
+    fprintf(fidTeX,'\\caption{(continued)}\\\\\n ');
+    fprintf(fidTeX,'\\hline\\hline \\\\ \n');
+    fprintf(fidTeX,'  & Prior distribution & Prior mean & Prior mode  & Prior s.d. & Lower Bound & Upper Bound & LB Untrunc.  80\\%% HPDI & UB Untrunc. 80\\%% HPDI  \\\\ \n');
+    fprintf(fidTeX,'\\hline \\endhead \n');
+    fprintf(fidTeX,'\\hline \\multicolumn{9}{r}{(Continued on next page)} \\\\ \\hline \\endfoot \n');
+    fprintf(fidTeX,'\\hline \\hline \\endlastfoot \n');
+    % Column 1: a string for the name of the prior distribution.
+    % Column 2: the prior mean.
+    % Column 3: the prior mode.
+    % Column 4: the prior standard deviation.
+    % Column 5: the lower bound of the prior density support.
+    % Column 6: the upper bound of the prior density support.
+    % Column 7: the lower bound of the interval containing 80% of the prior mass.
+    % Column 8: the upper bound of the interval containing 80% of the prior mass.
+    prior_trunc_backup = DynareOptions.prior_trunc ;
+    DynareOptions.prior_trunc = (1-DynareOptions.prior_interval)/2 ;
+    PriorIntervals = prior_bounds(BayesInfo,DynareOptions) ;
+    DynareOptions.prior_trunc = prior_trunc_backup ;
+    for i=1:size(BayesInfo.name,1)
+        [tmp,TexName] = get_the_name(i,1,ModelInfo,EstimationInfo,DynareOptions);
+        PriorShape = PriorNames{ BayesInfo.pshape(i) };
+        PriorMean = BayesInfo.p1(i);
+        PriorMode = BayesInfo.p5(i);
+        PriorStandardDeviation = BayesInfo.p2(i);
+        switch BayesInfo.pshape(i)
+          case { 1 , 5 }
+            LowerBound = BayesInfo.p3(i);
+            UpperBound = BayesInfo.p4(i);
+            if ~isinf(lb(i))
+                LowerBound=max(LowerBound,lb(i));
+            end
+            if ~isinf(ub(i))
+                UpperBound=min(UpperBound,ub(i));
+            end
+          case { 2 , 4 , 6 }
+            LowerBound = BayesInfo.p3(i);
+            if ~isinf(lb(i))
+                LowerBound=max(LowerBound,lb(i));
+            end
+            if ~isinf(ub(i))
+                UpperBound=ub(i);
+            else
+                UpperBound = '$\infty$';
+            end
+          case 3
+            if isinf(BayesInfo.p3(i)) && isinf(lb(i))
+                LowerBound = '$-\infty$';
+            else
+                LowerBound = BayesInfo.p3(i);
+                if ~isinf(lb(i))
+                    LowerBound=max(LowerBound,lb(i));
+                end
+            end
+            if isinf(BayesInfo.p4(i)) && isinf(ub(i))
+                UpperBound = '$\infty$';
+            else
+                UpperBound = BayesInfo.p4(i);
+                if ~isinf(ub(i))
+                    UpperBound=min(UpperBound,ub(i));
+                end
+            end
+          otherwise
+            error('get_prior_info:: Dynare bug!')
+        end
+        format_string = build_format_string(PriorMode, PriorStandardDeviation,LowerBound,UpperBound);
+        fprintf(fidTeX,format_string, ...
+                TexName, ...
+                PriorShape, ...
+                PriorMean, ...
+                PriorMode, ...
+                PriorStandardDeviation, ...
+                LowerBound, ...
+                UpperBound, ...
+                PriorIntervals.lb(i), ...
+                PriorIntervals.ub(i) );
+    end
+    fprintf(fidTeX,'\\end{longtable}\n ');    
+    fprintf(fidTeX,'\\end{center}\n');
+    fprintf(fidTeX,'%% End of TeX file.\n');
+    fclose(fidTeX);
+end
+
+function format_string = build_format_string(PriorMode,PriorStandardDeviation,LowerBound,UpperBound)
+format_string = ['%s & %s & %6.4f &'];
+if isnan(PriorMode)
+    format_string = [ format_string , ' %s &'];
+else
+    format_string = [ format_string , ' %6.4f &'];
+end
+if ~isnumeric(PriorStandardDeviation)
+    format_string = [ format_string , ' %s &'];
+else
+    format_string = [ format_string , ' %6.4f &'];
+end
+if ~isnumeric(LowerBound)
+    format_string = [ format_string , ' %s &'];
+else
+    format_string = [ format_string , ' %6.4f &'];
+end
+if ~isnumeric(UpperBound)
+    format_string = [ format_string , ' %s &'];
+else
+    format_string = [ format_string , ' %6.4f &'];
+end
+format_string = [ format_string , ' %6.4f & %6.4f \\\\ \n'];
\ No newline at end of file
diff --git a/mex/build/octave/Makefile.am b/mex/build/octave/Makefile.am
index 77067b24c9e72805054fc3467b289acde9861513..71d4639d6bcaa7a5a812d8261e7c3d59f2d42149 100644
--- a/mex/build/octave/Makefile.am
+++ b/mex/build/octave/Makefile.am
@@ -2,12 +2,16 @@ ACLOCAL_AMFLAGS = -I ../../../m4
 
 # libdynare++ must come before gensylv, k_order_perturbation, dynare_simul_
 if DO_SOMETHING
-SUBDIRS = mjdgges kronecker bytecode libdynare++ gensylv qzcomplex ordschur block_kalman_filter sobol local_state_space_iterations
+SUBDIRS = mjdgges kronecker bytecode libdynare++ gensylv qzcomplex block_kalman_filter sobol local_state_space_iterations
 
 if COMPILE_LINSOLVE
 SUBDIRS += linsolve
 endif
 
+if COMPILE_ORDSCHUR
+SUBDIRS += ordschur
+endif
+
 if HAVE_MATIO
 SUBDIRS += k_order_perturbation dynare_simul_
 endif
diff --git a/mex/build/octave/configure.ac b/mex/build/octave/configure.ac
index 499f5fe937bf1206b8ae89e0f57f2739de3d2c6e..fd563e61c35c2baf978940dc1a165a174cd815c2 100755
--- a/mex/build/octave/configure.ac
+++ b/mex/build/octave/configure.ac
@@ -1,6 +1,6 @@
 dnl Process this file with autoconf to produce a configure script.
 
-dnl Copyright (C) 2009-2014 Dynare Team
+dnl Copyright (C) 2009-2015 Dynare Team
 dnl
 dnl This file is part of Dynare.
 dnl
@@ -34,9 +34,11 @@ if test "x$MKOCTFILE" != "x"; then
   OCTAVE_VERSION=`$MKOCTFILE -v 2>&1 | sed 's/mkoctfile, version //'`
   AX_COMPARE_VERSION([$OCTAVE_VERSION], [lt], [3.6], [AC_MSG_ERROR([Your Octave is too old, please upgrade to version 3.6 at least.])])
   AX_COMPARE_VERSION([$OCTAVE_VERSION], [ge], [3.8], [OCTAVE38=yes])
+  AX_COMPARE_VERSION([$OCTAVE_VERSION], [ge], [4.0], [OCTAVE40=yes])
 fi
 
 AM_CONDITIONAL([COMPILE_LINSOLVE], [test "$OCTAVE38" != "yes"])
+AM_CONDITIONAL([COMPILE_ORDSCHUR], [test "$OCTAVE40" != "yes"])
 
 CFLAGS="$CFLAGS -Wall -Wno-parentheses"
 FFLAGS="$FFLAGS -Wall"
@@ -121,6 +123,12 @@ else
    BUILD_LINSOLVE_OCTAVE="no (Octave >= 3.8)"
 fi
 
+if test -n "$MKOCTFILE" -a "$OCTAVE40" != "yes"; then
+   BUILD_ORDSCHUR_OCTAVE="yes"
+else
+   BUILD_ORDSCHUR_OCTAVE="no (Octave >= 4.0)"
+fi
+
 AC_ARG_ENABLE([openmp], AS_HELP_STRING([--enable-openmp], [use OpenMP for parallelization of some MEX files]), [
   if test "x$enable_openmp" = "xyes"; then
     CPPFLAGS="$CPPFLAGS -DUSE_OMP"
@@ -139,6 +147,7 @@ Binaries (with "make"):
  Kalman Steady State MEX file for Octave:                            $BUILD_KALMAN_STEADY_STATE_OCTAVE
  Estimation, k-order and dynare_simul MEX for Octave:                $BUILD_ESTIMATION_KORDER_DYNSIMUL_MEX_OCTAVE
  Linsolve for Octave:                                                $BUILD_LINSOLVE_OCTAVE
+ Ordschur for Octave:                                                $BUILD_ORDSCHUR_OCTAVE
 
 ])
 
diff --git a/mex/sources/bytecode/ErrorHandling.hh b/mex/sources/bytecode/ErrorHandling.hh
index 6e2024a378e8cedeacfd558d3b181f0f277f50ea..946f88ab23d75556c8a92f282771852d660d8053 100644
--- a/mex/sources/bytecode/ErrorHandling.hh
+++ b/mex/sources/bytecode/ErrorHandling.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2013 Dynare Team
+ * Copyright (C) 2007-2015 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -307,15 +307,42 @@ public:
   ErrorMsg()
   {
     mxArray *M_ = mexGetVariable("global", "M_");
-    nb_endo = mxGetM(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "endo_names")));
-    endo_name_length = mxGetN(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "endo_names")));
-    P_endo_names = (char *) mxGetPr(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "endo_names")));
-    nb_exo = mxGetM(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "exo_names")));
-    exo_name_length = mxGetN(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "exo_names")));
-    P_exo_names = (char *) mxGetPr(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "exo_names")));
-    nb_param = mxGetM(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "param_names")));
-    param_name_length = mxGetN(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "param_names")));
-    P_param_names = (char *) mxGetPr(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "param_names")));
+    if (mxGetFieldNumber(M_, "endo_names") == -1)
+      {
+        nb_endo = 0;
+        endo_name_length = 0;
+        P_endo_names = NULL;
+      }
+    else
+      {
+        nb_endo = mxGetM(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "endo_names")));
+        endo_name_length = mxGetN(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "endo_names")));
+        P_endo_names = (char *) mxGetPr(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "endo_names")));
+      }
+    if (mxGetFieldNumber(M_, "exo_names") == -1)
+      {
+        nb_exo = 0;
+        exo_name_length = 0;
+        P_exo_names = NULL;
+      }
+    else
+      {
+        nb_exo = mxGetM(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "exo_names")));
+        exo_name_length = mxGetN(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "exo_names")));
+        P_exo_names = (char *) mxGetPr(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "exo_names")));
+      }
+    if (mxGetFieldNumber(M_, "param_names") == -1)
+      {
+        nb_param = 0;
+        param_name_length = 0;
+        P_param_names = NULL;
+      }
+    else
+      {
+        nb_param = mxGetM(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "param_names")));
+        param_name_length = mxGetN(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "param_names")));
+        P_param_names = (char *) mxGetPr(mxGetFieldByNumber(M_, 0, mxGetFieldNumber(M_, "param_names")));
+      }
     is_load_variable_list = false;
   }
 
diff --git a/mex/sources/bytecode/Evaluate.cc b/mex/sources/bytecode/Evaluate.cc
index 76aec3b1b650765f9e9030666e4c6ec30671aac5..60863cfef2f95a78aca4d95947419d0615f466c5 100644
--- a/mex/sources/bytecode/Evaluate.cc
+++ b/mex/sources/bytecode/Evaluate.cc
@@ -322,7 +322,10 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int
               var = ((FLDV_ *) it_code->second)->get_pos();
               lag = ((FLDV_ *) it_code->second)->get_lead_lag();
 #ifdef DEBUG
-              mexPrintf("FLDV y[var=%d, lag=%d, it_=%d], y_size=%d evaluate=%d\n", var, lag, it_, y_size, evaluate);
+              if (evaluate)
+                mexPrintf("FLDV y[var=%d, lag=%d, it_=%d], y_size=%d evaluate=%d, ya[%d]=%f\n", var, lag, it_, y_size, evaluate, (it_+lag)*y_size+var, ya[(it_+lag)*y_size+var]);
+              else
+                mexPrintf("FLDV y[var=%d, lag=%d, it_=%d], y_size=%d evaluate=%d, y[%d]=%f\n", var, lag, it_, y_size, evaluate, (it_+lag)*y_size+var, y[(it_+lag)*y_size+var]);
 #endif
               if (evaluate)
                 Stack.push(ya[(it_+lag)*y_size+var]);
@@ -336,8 +339,8 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int
               var = ((FLDV_ *) it_code->second)->get_pos();
               lag = ((FLDV_ *) it_code->second)->get_lead_lag();
 #ifdef DEBUG
-              mexPrintf("FLDV x[var=%d, lag=%d, it_=%d], nb_row_x=%d evaluate=%d\n", var, lag, it_, nb_row_x, evaluate);
-              tmp_out << " x[" << it_+lag << ", " << var << "](" << x[it_+lag+var*nb_row_x] << ")";
+              mexPrintf("FLDV x[var=%d, lag=%d, it_=%d], nb_row_x=%d evaluate=%d x[%d]=%f\n", var, lag, it_, nb_row_x, evaluate, it_+lag+var*nb_row_x, x[it_+lag+var*nb_row_x]);
+              //tmp_out << " x[" << it_+lag << ", " << var << "](" << x[it_+lag+var*nb_row_x] << ")";
 #endif
               Stack.push(x[it_+lag+var*nb_row_x]);
               break;
@@ -837,7 +840,7 @@ Evaluate::compute_block_time(const int Per_u_, const bool evaluate, /*const int
             case oLess:
               Stack.push(double (v1 < v2));
 #ifdef DEBUG
-              tmp_out << " |" << v1 << "<" << v2 << "|";
+              mexPrintf("v1=%f v2=%f v1 < v2 = %f\n",v1,v2,double(v1 < v2));
 #endif
               break;
             case oGreater:
diff --git a/mex/sources/bytecode/Interpreter.cc b/mex/sources/bytecode/Interpreter.cc
index fb47033c4cb3bed7cbc586d45d777d461bdfb9d6..4b7af71f73189a32a947deede746e7cc4520545f 100644
--- a/mex/sources/bytecode/Interpreter.cc
+++ b/mex/sources/bytecode/Interpreter.cc
@@ -582,8 +582,8 @@ Interpreter::compute_blocks(string file_name, string bin_basename, bool evaluate
 #ifdef DEBUG
                     mexPrintf("allocates jacobian_exo_block( %d, %d, mxREAL)\n", fb->get_size(), fb->get_exo_size());
 #endif
-                    jacobian_exo_block.push_back(mxCreateDoubleMatrix(fb->get_size(), fb->get_exo_size(), mxREAL));
-                    jacobian_det_exo_block.push_back(mxCreateDoubleMatrix(fb->get_size(), fb->get_det_exo_size(), mxREAL));
+                    jacobian_exo_block.push_back(mxCreateDoubleMatrix(fb->get_size(), fb->get_nb_col_exo_jacob(), mxREAL));
+                    jacobian_det_exo_block.push_back(mxCreateDoubleMatrix(fb->get_size(), fb->get_nb_col_det_exo_jacob(), mxREAL));
                     jacobian_other_endo_block.push_back(mxCreateDoubleMatrix(fb->get_size(), fb->get_nb_col_other_endo_jacob(), mxREAL));
                   }
                 if (block >= 0)
@@ -598,8 +598,8 @@ Interpreter::compute_blocks(string file_name, string bin_basename, bool evaluate
             else
               {
 #ifdef DEBUG
-                mexPrintf("endo in block=%d, type=%d, steady_state=%d, print_it=%d, Block_Count=%d, fb->get_is_linear()=%d, fb->get_endo_nbr()=%d, fb->get_Max_Lag()=%d, fb->get_Max_Lead()=%d, fb->get_u_count_int()=%d\n",
-                          fb->get_size(), fb->get_type(), steady_state, print_it, Block_Count, fb->get_is_linear(), fb->get_endo_nbr(), fb->get_Max_Lag(), fb->get_Max_Lead(), fb->get_u_count_int());
+                mexPrintf("endo in Block_Count=%d, block=%d, type=%d, steady_state=%d, print_it=%d, Block_Count=%d, fb->get_is_linear()=%d, fb->get_endo_nbr()=%d, fb->get_Max_Lag()=%d, fb->get_Max_Lead()=%d, fb->get_u_count_int()=%d\n",
+                          Block_Count, fb->get_size(), fb->get_type(), steady_state, print_it, Block_Count, fb->get_is_linear(), fb->get_endo_nbr(), fb->get_Max_Lag(), fb->get_Max_Lead(), fb->get_u_count_int());
 #endif
                 result = simulate_a_block();
                 if (result == ERROR_ON_EXIT)
diff --git a/preprocessor/CodeInterpreter.hh b/preprocessor/CodeInterpreter.hh
index d39567b83ad8bd7c09f119c46ebe1941d26d7806..b6068394ac3b90db7ea8b404a8a30e0f148f242b 100644
--- a/preprocessor/CodeInterpreter.hh
+++ b/preprocessor/CodeInterpreter.hh
@@ -20,6 +20,8 @@
 #ifndef _CODEINTERPRETER_HH
 #define _CODEINTERPRETER_HH
 //#define DEBUGL
+#include <iostream>
+
 #include <cstdlib>
 #include <cstdio>
 #include <fstream>
@@ -246,7 +248,8 @@ enum PriorDistributions
     eInvGamma1 = 4,
     eUniform = 5,
     eInvGamma2 = 6,
-    eDirichlet = 7
+    eDirichlet = 7,
+    eWeibull = 8
   };
 
 struct Block_contain_type
@@ -1413,7 +1416,7 @@ private:
   int u_count_int;
   int nb_col_jacob;
   unsigned int det_exo_size, exo_size, other_endo_size;
-  unsigned int nb_col_other_endo_jacob;
+  unsigned int nb_col_det_exo_jacob, nb_col_exo_jacob, nb_col_other_endo_jacob;
 public:
   inline
   FBEGINBLOCK_()
@@ -1425,7 +1428,7 @@ public:
   FBEGINBLOCK_(unsigned int size_arg, BlockSimulationType type_arg, int unsigned first_element, int unsigned block_size,
                const vector<int> &variable_arg, const vector<int> &equation_arg,
                bool is_linear_arg, int endo_nbr_arg, int Max_Lag_arg, int Max_Lead_arg, int &u_count_int_arg, int nb_col_jacob_arg,
-               unsigned int det_exo_size_arg, unsigned int exo_size_arg, unsigned int other_endo_size_arg, unsigned int nb_col_other_endo_jacob_arg,
+               unsigned int det_exo_size_arg, unsigned int nb_col_det_exo_jacob_arg, unsigned int exo_size_arg, unsigned int nb_col_exo_jacob_arg, unsigned int other_endo_size_arg, unsigned int nb_col_other_endo_jacob_arg,
                const vector<unsigned int> &det_exogenous_arg, const vector<unsigned int> &exogenous_arg, const vector<unsigned int> &other_endogenous_arg)
   {
     op_code = FBEGINBLOCK; size = size_arg; type = type_arg;
@@ -1435,8 +1438,10 @@ public:
     exogenous = vector<unsigned int>(exogenous_arg);
     other_endogenous = vector<unsigned int>(other_endogenous_arg);
     is_linear = is_linear_arg; endo_nbr = endo_nbr_arg; Max_Lag = Max_Lag_arg; Max_Lead = Max_Lead_arg; u_count_int = u_count_int_arg;
-    nb_col_jacob = nb_col_jacob_arg; det_exo_size = det_exo_size_arg; exo_size = exo_size_arg; other_endo_size = other_endo_size_arg;
-    nb_col_other_endo_jacob = nb_col_other_endo_jacob_arg;
+    nb_col_jacob = nb_col_jacob_arg; 
+    det_exo_size = det_exo_size_arg; nb_col_det_exo_jacob = nb_col_det_exo_jacob_arg; 
+    exo_size = exo_size_arg; nb_col_exo_jacob = nb_col_exo_jacob_arg; 
+    other_endo_size = other_endo_size_arg; nb_col_other_endo_jacob = nb_col_other_endo_jacob_arg;
   };
   inline
   FBEGINBLOCK_(unsigned int size_arg, BlockSimulationType type_arg, int unsigned first_element, int unsigned block_size,
@@ -1449,7 +1454,7 @@ public:
     is_linear = is_linear_arg; endo_nbr = endo_nbr_arg; Max_Lag = Max_Lag_arg; Max_Lead = Max_Lead_arg; u_count_int = u_count_int_arg;
     nb_col_jacob = nb_col_jacob_arg;
     det_exo_size = 0; exo_size = 0; other_endo_size = 0;
-    nb_col_other_endo_jacob = 0;
+    nb_col_det_exo_jacob = 0;nb_col_exo_jacob = 0;nb_col_other_endo_jacob = 0;
   }
   inline unsigned int
   get_size()
@@ -1502,11 +1507,21 @@ public:
     return exo_size;
   };
   inline unsigned int
+  get_nb_col_exo_jacob()
+  {
+    return nb_col_exo_jacob;
+  };
+  inline unsigned int
   get_det_exo_size()
   {
     return det_exo_size;
   };
   inline unsigned int
+  get_nb_col_det_exo_jacob()
+  {
+    return nb_col_det_exo_jacob;
+  };
+  inline unsigned int
   get_other_endo_size()
   {
     return other_endo_size;
@@ -1538,7 +1553,9 @@ public:
       }
     CompileCode.write(reinterpret_cast<char *>(&nb_col_jacob), sizeof(nb_col_jacob));
     CompileCode.write(reinterpret_cast<char *>(&det_exo_size), sizeof(det_exo_size));
+    CompileCode.write(reinterpret_cast<char *>(&nb_col_det_exo_jacob), sizeof(nb_col_det_exo_jacob));
     CompileCode.write(reinterpret_cast<char *>(&exo_size), sizeof(exo_size));
+    CompileCode.write(reinterpret_cast<char *>(&nb_col_exo_jacob), sizeof(nb_col_exo_jacob));
     CompileCode.write(reinterpret_cast<char *>(&other_endo_size), sizeof(other_endo_size));
     CompileCode.write(reinterpret_cast<char *>(&nb_col_other_endo_jacob), sizeof(nb_col_other_endo_jacob));
 
@@ -1576,7 +1593,9 @@ public:
       }
     memcpy(&nb_col_jacob, code, sizeof(nb_col_jacob)); code += sizeof(nb_col_jacob);
     memcpy(&det_exo_size, code, sizeof(det_exo_size)); code += sizeof(det_exo_size);
+    memcpy(&nb_col_det_exo_jacob, code, sizeof(nb_col_det_exo_jacob)); code += sizeof(nb_col_det_exo_jacob);
     memcpy(&exo_size, code, sizeof(exo_size)); code += sizeof(exo_size);
+    memcpy(&nb_col_exo_jacob, code, sizeof(nb_col_exo_jacob)); code += sizeof(nb_col_exo_jacob);
     memcpy(&other_endo_size, code, sizeof(other_endo_size)); code += sizeof(other_endo_size);
     memcpy(&nb_col_other_endo_jacob, code, sizeof(nb_col_other_endo_jacob)); code += sizeof(nb_col_other_endo_jacob);
 
diff --git a/preprocessor/ComputingTasks.cc b/preprocessor/ComputingTasks.cc
index e22f157725a7e3c1a93a0c9d5cca4b36e0cec1f9..76ed6faad5c648bf09314c715f7b4131f6d96829 100644
--- a/preprocessor/ComputingTasks.cc
+++ b/preprocessor/ComputingTasks.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2014 Dynare Team
+ * Copyright (C) 2003-2015 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -47,7 +47,7 @@ void
 SteadyStatement::writeOutput(ostream &output, const string &basename) const
 {
   options_list.writeOutput(output);
-  output << "steady;\n";
+  output << "steady;" << endl;
 }
 
 CheckStatement::CheckStatement(const OptionsList &options_list_arg) :
@@ -83,7 +83,7 @@ void
 ModelInfoStatement::writeOutput(ostream &output, const string &basename) const
 {
   options_list.writeOutput(output);
-  output << "model_info();\n";
+  output << "model_info();" << endl;
 }
 
 SimulStatement::SimulStatement(const OptionsList &options_list_arg) :
@@ -168,6 +168,13 @@ StochSimulStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsoli
 void
 StochSimulStatement::writeOutput(ostream &output, const string &basename) const
 {
+  // Ensure that order 3 implies k_order (#844)
+  OptionsList::num_options_t::const_iterator it = options_list.num_options.find("order");
+  OptionsList::num_options_t::const_iterator it1 = options_list.num_options.find("k_order_solver");
+  if ((it1 != options_list.num_options.end() && it1->second == "1")
+      || (it != options_list.num_options.end() && atoi(it->second.c_str()) >= 3))
+    output << "options_.k_order_solver = 1;" << endl;
+
   options_list.writeOutput(output);
   symbol_list.writeOutput("var_list_", output);
   output << "info = stoch_simul(var_list_);" << endl;
@@ -234,7 +241,14 @@ RamseyModelStatement::writeOutput(ostream &output, const string &basename) const
   // this affects the computation of the steady state that uses a special algorithm
   // It should probably rather be a M_ field, but we leave it in options_ for historical reason
 
-  output << "options_.ramsey_policy = 1;\n";
+  // Ensure that order 3 implies k_order (#844)
+  OptionsList::num_options_t::const_iterator it = options_list.num_options.find("order");
+  OptionsList::num_options_t::const_iterator it1 = options_list.num_options.find("k_order_solver");
+  if ((it1 != options_list.num_options.end() && it1->second == "1")
+      || (it != options_list.num_options.end() && atoi(it->second.c_str()) >= 3))
+    output << "options_.k_order_solver = 1;" << endl;
+
+  output << "options_.ramsey_policy = 1;" << endl;
   options_list.writeOutput(output);
 }
 
@@ -284,9 +298,16 @@ RamseyPolicyStatement::checkPass(ModFileStructure &mod_file_struct, WarningConso
 void
 RamseyPolicyStatement::writeOutput(ostream &output, const string &basename) const
 {
+  // Ensure that order 3 implies k_order (#844)
+  OptionsList::num_options_t::const_iterator it = options_list.num_options.find("order");
+  OptionsList::num_options_t::const_iterator it1 = options_list.num_options.find("k_order_solver");
+  if ((it1 != options_list.num_options.end() && it1->second == "1")
+      || (it != options_list.num_options.end() && atoi(it->second.c_str()) >= 3))
+    output << "options_.k_order_solver = 1;" << endl;
+
   options_list.writeOutput(output);
   symbol_list.writeOutput("var_list_", output);
-  output << "ramsey_policy(var_list_);\n";
+  output << "ramsey_policy(var_list_);" << endl;
 }
 
 DiscretionaryPolicyStatement::DiscretionaryPolicyStatement(const SymbolList &symbol_list_arg,
@@ -337,9 +358,16 @@ DiscretionaryPolicyStatement::checkPass(ModFileStructure &mod_file_struct, Warni
 void
 DiscretionaryPolicyStatement::writeOutput(ostream &output, const string &basename) const
 {
+  // Ensure that order 3 implies k_order (#844)
+  OptionsList::num_options_t::const_iterator it = options_list.num_options.find("order");
+  OptionsList::num_options_t::const_iterator it1 = options_list.num_options.find("k_order_solver");
+  if ((it1 != options_list.num_options.end() && it1->second == "1")
+      || (it != options_list.num_options.end() && atoi(it->second.c_str()) >= 3))
+    output << "options_.k_order_solver = 1;" << endl;
+
   options_list.writeOutput(output);
   symbol_list.writeOutput("var_list_", output);
-  output << "discretionary_policy(var_list_);\n";
+  output << "discretionary_policy(var_list_);" << endl;
 }
 
 EstimationStatement::EstimationStatement(const SymbolList &symbol_list_arg,
@@ -451,7 +479,7 @@ EstimationStatement::writeOutput(ostream &output, const string &basename) const
     output << "options_.steadystate.nocheck = 1;" << endl;
 
   symbol_list.writeOutput("var_list_", output);
-  output << "dynare_estimation(var_list_);\n";
+  output << "oo_recursive_=dynare_estimation(var_list_);" << endl;
 }
 
 DynareSensitivityStatement::DynareSensitivityStatement(const OptionsList &options_list_arg) :
@@ -490,19 +518,16 @@ DynareSensitivityStatement::writeOutput(ostream &output, const string &basename)
   output << "dynare_sensitivity(options_gsa);" << endl;
 }
 
-RplotStatement::RplotStatement(const SymbolList &symbol_list_arg,
-                               const OptionsList &options_list_arg) :
-  symbol_list(symbol_list_arg),
-  options_list(options_list_arg)
+RplotStatement::RplotStatement(const SymbolList &symbol_list_arg) :
+  symbol_list(symbol_list_arg)
 {
 }
 
 void
 RplotStatement::writeOutput(ostream &output, const string &basename) const
 {
-  options_list.writeOutput(output);
   symbol_list.writeOutput("var_list_", output);
-  output << "rplot(var_list_);\n";
+  output << "rplot(var_list_);" << endl;
 }
 
 UnitRootVarsStatement::UnitRootVarsStatement(void)
@@ -855,7 +880,7 @@ ObservationTrendsStatement::writeOutput(ostream &output, const string &basename)
       SymbolType type = symbol_table.getType(it->first);
       if (type == eEndogenous)
         {
-          output << "tmp1 = strmatch('" << it->first << "',options_.varobs,'exact');\n";
+          output << "tmp1 = strmatch('" << it->first << "',options_.varobs,'exact');" << endl;
           output << "options_.trend_coeffs{tmp1} = '";
           it->second->writeOutput(output);
           output << "';" << endl;
@@ -914,9 +939,16 @@ OsrStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation
 void
 OsrStatement::writeOutput(ostream &output, const string &basename) const
 {
+  // Ensure that order 3 implies k_order (#844)
+  OptionsList::num_options_t::const_iterator it = options_list.num_options.find("order");
+  OptionsList::num_options_t::const_iterator it1 = options_list.num_options.find("k_order_solver");
+  if ((it1 != options_list.num_options.end() && it1->second == "1")
+      || (it != options_list.num_options.end() && atoi(it->second.c_str()) >= 3))
+    output << "options_.k_order_solver = 1;" << endl;
+
   options_list.writeOutput(output);
   symbol_list.writeOutput("var_list_", output);
-  output << "oo_.osr = osr(var_list_,osr_params_,obj_var_,optim_weights_);\n";
+  output << "oo_.osr = osr(var_list_,osr_params_,obj_var_,optim_weights_);" << endl;
 }
 
 OptimWeightsStatement::OptimWeightsStatement(const var_weights_t &var_weights_arg,
@@ -952,7 +984,7 @@ OptimWeightsStatement::writeOutput(ostream &output, const string &basename) cons
       output << "optim_weights_(" << id << "," << id << ") = ";
       value->writeOutput(output);
       output << ";" << endl;
-      output << "obj_var_ = [obj_var_; " << id << "];\n";
+      output << "obj_var_ = [obj_var_; " << id << "];" << endl;
     }
 
   for (covar_weights_t::const_iterator it = covar_weights.begin();
@@ -966,7 +998,7 @@ OptimWeightsStatement::writeOutput(ostream &output, const string &basename) cons
       output << "optim_weights_(" << id1 << "," << id2 << ") = ";
       value->writeOutput(output);
       output << ";" << endl;
-      output << "obj_var_ = [obj_var_; " << id1 << "; " << id2 << "];\n";
+      output << "obj_var_ = [obj_var_; " << id1 << "; " << id2 << "];" << endl;
     }
 }
 
@@ -1396,6 +1428,17 @@ WriteLatexStaticModelStatement::writeOutput(ostream &output, const string &basen
   static_model.writeLatexFile(basename);
 }
 
+WriteLatexOriginalModelStatement::WriteLatexOriginalModelStatement(const DynamicModel &original_model_arg) :
+  original_model(original_model_arg)
+{
+}
+
+void
+WriteLatexOriginalModelStatement::writeOutput(ostream &output, const string &basename) const
+{
+  original_model.writeLatexOriginalFile(basename);
+}
+
 ShockDecompositionStatement::ShockDecompositionStatement(const SymbolList &symbol_list_arg,
                                                          const OptionsList &options_list_arg) :
   symbol_list(symbol_list_arg),
@@ -1408,7 +1451,7 @@ ShockDecompositionStatement::writeOutput(ostream &output, const string &basename
 {
   options_list.writeOutput(output);
   symbol_list.writeOutput("var_list_", output);
-  output << "oo_ = shock_decomposition(M_,oo_,options_,var_list_);\n";
+  output << "oo_ = shock_decomposition(M_,oo_,options_,var_list_);" << endl;
 }
 
 ConditionalForecastStatement::ConditionalForecastStatement(const OptionsList &options_list_arg) :
@@ -1897,8 +1940,6 @@ void
 EstimationDataStatement::writeOutput(ostream &output, const string &basename) const
 {
   options_list.writeOutput(output, "options_.dataset");
-  //if (options_list.date_options.find("first_obs") == options_list.date_options.end())
-  //  output << "options_.dataset.first_obs = options_.initial_period;" << endl;
 }
 
 SubsamplesStatement::SubsamplesStatement(const string &name1_arg,
@@ -2036,6 +2077,113 @@ SubsamplesEqualStatement::writeOutput(ostream &output, const string &basename) c
          << endl;
 }
 
+JointPriorStatement::JointPriorStatement(const vector<string> joint_parameters_arg,
+                                         const PriorDistributions &prior_shape_arg,
+                                         const OptionsList &options_list_arg) :
+  joint_parameters(joint_parameters_arg),
+  prior_shape(prior_shape_arg),
+  options_list(options_list_arg)
+{
+}
+
+void
+JointPriorStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings)
+{
+  if (joint_parameters.size() < 2)
+    {
+      cerr << "ERROR: you must pass at least two parameters to the joint prior statement" << endl;
+      exit(EXIT_FAILURE);
+    }
+
+  if (prior_shape == eNoShape)
+    {
+      cerr << "ERROR: You must pass the shape option to the prior statement." << endl;
+      exit(EXIT_FAILURE);
+    }
+
+  if (options_list.num_options.find("mean") == options_list.num_options.end() &&
+      options_list.num_options.find("mode") == options_list.num_options.end())
+    {
+      cerr << "ERROR: You must pass at least one of mean and mode to the prior statement." << endl;
+      exit(EXIT_FAILURE);
+    }
+
+  OptionsList::num_options_t::const_iterator it_num = options_list.num_options.find("domain");
+  if (it_num != options_list.num_options.end())
+    {
+      using namespace boost;
+      vector<string> tokenizedDomain;
+      split(tokenizedDomain, it_num->second, is_any_of("[ ]"), token_compress_on);
+      if (tokenizedDomain.size() != 4)
+        {
+          cerr << "ERROR: You must pass exactly two values to the domain option." << endl;
+          exit(EXIT_FAILURE);
+        }
+    }
+}
+
+void
+JointPriorStatement::writeOutput(ostream &output, const string &basename) const
+{
+  for (vector<string>::const_iterator it = joint_parameters.begin() ; it != joint_parameters.end(); it++)
+    output << "eifind = get_new_or_existing_ei_index('joint_parameter_prior_index', '"
+           << *it << "', '');" << endl
+           << "estimation_info.joint_parameter_prior_index(eifind) = {'" << *it << "'};" << endl;
+
+  output << "key = {[";
+  for (vector<string>::const_iterator it = joint_parameters.begin() ; it != joint_parameters.end(); it++)
+    output << "get_new_or_existing_ei_index('joint_parameter_prior_index', '" << *it << "', '') ..."
+           << endl << "    ";
+  output << "]};" << endl;
+
+  string lhs_field("estimation_info.joint_parameter_tmp");
+
+  writeOutputHelper(output, "domain", lhs_field);
+  writeOutputHelper(output, "interval", lhs_field);
+  writeOutputHelper(output, "mean", lhs_field);
+  writeOutputHelper(output, "median", lhs_field);
+  writeOutputHelper(output, "mode", lhs_field);
+
+  assert(prior_shape != eNoShape);
+  output << lhs_field << ".shape = " << prior_shape << ";" << endl;
+
+  writeOutputHelper(output, "shift", lhs_field);
+  writeOutputHelper(output, "stdev", lhs_field);
+  writeOutputHelper(output, "truncate", lhs_field);
+  writeOutputHelper(output, "variance", lhs_field);
+
+  output << "estimation_info.joint_parameter_tmp = [key, ..." << endl
+         << "    " << lhs_field << ".domain , ..." << endl
+         << "    " << lhs_field << ".interval , ..." << endl
+         << "    " << lhs_field << ".mean , ..." << endl
+         << "    " << lhs_field << ".median , ..." << endl
+         << "    " << lhs_field << ".mode , ..." << endl
+         << "    " << lhs_field << ".shape , ..." << endl
+         << "    " << lhs_field << ".shift , ..." << endl
+         << "    " << lhs_field << ".stdev , ..." << endl
+         << "    " << lhs_field << ".truncate , ..." << endl
+         << "    " << lhs_field << ".variance];" << endl
+         << "estimation_info.joint_parameter = [estimation_info.joint_parameter; estimation_info.joint_parameter_tmp];" << endl
+         << "estimation_info=rmfield(estimation_info, 'joint_parameter_tmp');" << endl;
+}
+
+void
+JointPriorStatement::writeOutputHelper(ostream &output, const string &field, const string &lhs_field) const
+{
+  OptionsList::num_options_t::const_iterator itn = options_list.num_options.find(field);
+  output << lhs_field << "." << field << " = {";
+  if (field=="variance")
+    output << "{";
+  if (itn != options_list.num_options.end())
+    output << itn->second;
+  else
+    output << "{}";
+  if (field=="variance")
+    output << "}";
+  output << "};" << endl;
+}
+
+
 BasicPriorStatement::~BasicPriorStatement()
 {
 }
@@ -2221,6 +2369,9 @@ BasicPriorStatement::writeCShape(ostream &output) const
     case eDirichlet:
       output  << "\"dirichlet\";" << endl;
       break;
+    case eWeibull:
+      output  << "\"weibull\";" << endl;
+      break;
     case eNoShape:
       assert(prior_shape != eNoShape);
     }
@@ -2350,27 +2501,6 @@ CorrPriorStatement::writeOutput(ostream &output, const string &basename) const
   writePriorOutput(output, lhs_field, name1);
 }
 
-PriorEqualStatement::PriorEqualStatement(const string &to_declaration_type_arg,
-                                         const string &to_name1_arg,
-                                         const string &to_name2_arg,
-                                         const string &to_subsample_name_arg,
-                                         const string &from_declaration_type_arg,
-                                         const string &from_name1_arg,
-                                         const string &from_name2_arg,
-                                         const string &from_subsample_name_arg,
-                                         const SymbolTable &symbol_table_arg) :
-  to_declaration_type(to_declaration_type_arg),
-  to_name1(to_name1_arg),
-  to_name2(to_name2_arg),
-  to_subsample_name(to_subsample_name_arg),
-  from_declaration_type(from_declaration_type_arg),
-  from_name1(from_name1_arg),
-  from_name2(from_name2_arg),
-  from_subsample_name(from_subsample_name_arg),
-  symbol_table(symbol_table_arg)
-{
-}
-
 void
 CorrPriorStatement::writeCOutput(ostream &output, const string &basename)
 {
@@ -2403,6 +2533,27 @@ CorrPriorStatement::writeCOutput(ostream &output, const string &basename)
   output << endl <<"     index, index1, shape, mean, mode, stdev, variance, domain));" << endl;
 }
 
+PriorEqualStatement::PriorEqualStatement(const string &to_declaration_type_arg,
+                                         const string &to_name1_arg,
+                                         const string &to_name2_arg,
+                                         const string &to_subsample_name_arg,
+                                         const string &from_declaration_type_arg,
+                                         const string &from_name1_arg,
+                                         const string &from_name2_arg,
+                                         const string &from_subsample_name_arg,
+                                         const SymbolTable &symbol_table_arg) :
+  to_declaration_type(to_declaration_type_arg),
+  to_name1(to_name1_arg),
+  to_name2(to_name2_arg),
+  to_subsample_name(to_subsample_name_arg),
+  from_declaration_type(from_declaration_type_arg),
+  from_name1(from_name1_arg),
+  from_name2(from_name2_arg),
+  from_subsample_name(from_subsample_name_arg),
+  symbol_table(symbol_table_arg)
+{
+}
+
 void
 PriorEqualStatement::checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings)
 {
@@ -2667,6 +2818,33 @@ CorrOptionsStatement::writeOutput(ostream &output, const string &basename) const
   writeOptionsOutput(output, lhs_field, name1);
 }
 
+void
+CorrOptionsStatement::writeCOutput(ostream &output, const string &basename)
+{
+  output << endl
+         << "index = ";
+  if (is_structural_innovation(symbol_table.getType(name)))
+    output << "exo_names";
+  else
+    output << "endo_names";
+  output << "[\""<< name << "\"];" << endl;
+
+  output << "index1 = ";
+  if (is_structural_innovation(symbol_table.getType(name1)))
+    output << "exo_names";
+  else
+    output << "endo_names";
+  output << "[\""<< name1 << "\"];" << endl;
+
+  writeCOutputHelper(output, "init");
+
+  if (is_structural_innovation(symbol_table.getType(name)))
+    output << "msdsgeinfo->addStructuralInnovationCorrOption(new ModFileStructuralInnovationCorrOption(";
+  else
+    output << "msdsgeinfo->addMeasurementErrorCorrOption(new ModFileMeasurementErrorCorrOption(";
+  output << "index, index1, init));" << endl;
+}
+
 OptionsEqualStatement::OptionsEqualStatement(const string &to_declaration_type_arg,
                                              const string &to_name1_arg,
                                              const string &to_name2_arg,
@@ -2834,33 +3012,6 @@ ModelDiagnosticsStatement::writeOutput(ostream &output, const string &basename)
   output << "model_diagnostics(M_,options_,oo_);" << endl;
 }
 
-void
-CorrOptionsStatement::writeCOutput(ostream &output, const string &basename)
-{
-  output << endl
-         << "index = ";
-  if (is_structural_innovation(symbol_table.getType(name)))
-    output << "exo_names";
-  else
-    output << "endo_names";
-  output << "[\""<< name << "\"];" << endl;
-
-  output << "index1 = ";
-  if (is_structural_innovation(symbol_table.getType(name1)))
-    output << "exo_names";
-  else
-    output << "endo_names";
-  output << "[\""<< name1 << "\"];" << endl;
-
-  writeCOutputHelper(output, "init");
-
-  if (is_structural_innovation(symbol_table.getType(name)))
-    output << "msdsgeinfo->addStructuralInnovationCorrOption(new ModFileStructuralInnovationCorrOption(";
-  else
-    output << "msdsgeinfo->addMeasurementErrorCorrOption(new ModFileMeasurementErrorCorrOption(";
-  output << "index, index1, init));" << endl;
-}
-
 Smoother2histvalStatement::Smoother2histvalStatement(const OptionsList &options_list_arg) :
   options_list(options_list_arg)
 {
diff --git a/preprocessor/ComputingTasks.hh b/preprocessor/ComputingTasks.hh
index b1a009ffac7e2ed92df869624d27a4762adadd44..037ce9b699e13b3128bcc21c7aca73988217641f 100644
--- a/preprocessor/ComputingTasks.hh
+++ b/preprocessor/ComputingTasks.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2014 Dynare Team
+ * Copyright (C) 2003-2015 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -150,10 +150,8 @@ class RplotStatement : public Statement
 {
 private:
   const SymbolList symbol_list;
-  const OptionsList options_list;
 public:
-  RplotStatement(const SymbolList &symbol_list_arg,
-                 const OptionsList &options_list_arg);
+  RplotStatement(const SymbolList &symbol_list_arg);
   virtual void writeOutput(ostream &output, const string &basename) const;
 };
 
@@ -509,6 +507,15 @@ public:
   virtual void writeOutput(ostream &output, const string &basename) const;
 };
 
+class WriteLatexOriginalModelStatement : public Statement
+{
+private:
+  const DynamicModel &original_model;
+public:
+  WriteLatexOriginalModelStatement(const DynamicModel &original_model_arg);
+  virtual void writeOutput(ostream &output, const string &basename) const;
+};
+
 class ShockDecompositionStatement : public Statement
 {
 private:
@@ -670,6 +677,22 @@ public:
   virtual void writeOutput(ostream &output, const string &basename) const;
 };
 
+class JointPriorStatement : public Statement
+{
+private:
+  const vector<string> joint_parameters;
+  const PriorDistributions prior_shape;
+  const OptionsList options_list;
+public:
+  JointPriorStatement(const vector<string> joint_parameters_arg,
+                      const PriorDistributions &prior_shape_arg,
+                      const OptionsList &options_list_arg);
+  virtual void checkPass(ModFileStructure &mod_file_struct, WarningConsolidation &warnings);
+  virtual void writeOutput(ostream &output, const string &basename) const;
+  void writeOutputHelper(ostream &output, const string &field, const string &lhs_field) const;
+};
+
+
 class BasicPriorStatement : public Statement
 {
 public:
diff --git a/preprocessor/DynamicModel.cc b/preprocessor/DynamicModel.cc
index 0043b76d77f098205ea3401e19ff810c336f7252..339cbe9765a2bfbbc032bbcc0774d59d60827cae 100644
--- a/preprocessor/DynamicModel.cc
+++ b/preprocessor/DynamicModel.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2014 Dynare Team
+ * Copyright (C) 2003-2015 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -187,6 +187,10 @@ DynamicModel::computeTemporaryTermsOrdered()
             it->second->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
           for (derivative_t::const_iterator it = derivative_other_endo[block].begin(); it != derivative_other_endo[block].end(); it++)
             it->second->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
+          for (derivative_t::const_iterator it = derivative_exo[block].begin(); it != derivative_exo[block].end(); it++)
+            it->second->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
+          for (derivative_t::const_iterator it = derivative_exo_det[block].begin(); it != derivative_exo_det[block].end(); it++)
+            it->second->collectTemporary_terms(temporary_terms, temporary_terms_in_use, block);
           v_temporary_terms_inuse[block] = temporary_terms_in_use;
         }
       computeTemporaryTermsMapping();
@@ -257,8 +261,6 @@ DynamicModel::writeModelEquationsOrdered_M(const string &dynamic_basename) const
         {
           int lag = it->first.first;
           unsigned int var = it->first.second.first;
-          //int eqr = getBlockInitialEquationID(block, eq);
-          //int varr = getBlockInitialVariableID(block, var);
           if (var != prev_var || lag != prev_lag)
             {
               prev_var = var;
@@ -276,8 +278,6 @@ DynamicModel::writeModelEquationsOrdered_M(const string &dynamic_basename) const
         {
           int lag = it->first.first;
           unsigned int var = it->first.second.first;
-          //int eqr = getBlockInitialEquationID(block, eq);
-          //int varr = getBlockInitialVariableID(block, var);
           if (var != prev_var || lag != prev_lag)
             {
               prev_var = var;
@@ -295,8 +295,6 @@ DynamicModel::writeModelEquationsOrdered_M(const string &dynamic_basename) const
         {
           int lag = it->first.first;
           unsigned int var = it->first.second.first;
-          //int eqr = getBlockInitialEquationID(block, eq);
-          //int varr = getBlockInitialVariableID(block, var);
           if (var != prev_var || lag != prev_lag)
             {
               prev_var = var;
@@ -314,8 +312,6 @@ DynamicModel::writeModelEquationsOrdered_M(const string &dynamic_basename) const
         {
           int lag = it->first.first;
           unsigned int var = it->first.second.first;
-          //int eqr = getBlockInitialEquationID(block, eq);
-          //int varr = getBlockInitialVariableID(block, var);
           if (var != prev_var || lag != prev_lag)
             {
               prev_var = var;
@@ -342,7 +338,7 @@ DynamicModel::writeModelEquationsOrdered_M(const string &dynamic_basename) const
       else if (simulation_type == SOLVE_BACKWARD_SIMPLE || simulation_type == SOLVE_FORWARD_SIMPLE)
         output << "function [residual, y, g1, g2, g3, varargout] = " << dynamic_basename << "_" << block+1 << "(y, x, params, steady_state, it_, jacobian_eval)\n";
       else
-        output << "function [residual, y, g1, g2, g3, b, varargout] = " << dynamic_basename << "_" << block+1 << "(y, x, params, steady_state, periods, jacobian_eval, y_kmin, y_size)\n";
+        output << "function [residual, y, g1, g2, g3, b, varargout] = " << dynamic_basename << "_" << block+1 << "(y, x, params, steady_state, periods, jacobian_eval, y_kmin, y_size, Periods)\n";
       BlockType block_type;
       if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE)
         block_type = SIMULTAN;
@@ -364,7 +360,6 @@ DynamicModel::writeModelEquationsOrdered_M(const string &dynamic_basename) const
              << "  % //                     Simulation type "
              << BlockSim(simulation_type) << "  //" << endl
              << "  % ////////////////////////////////////////////////////////////////////////" << endl;
-      output << "  global options_ oo_;" << endl;
       //The Temporary terms
       if (simulation_type == EVALUATE_BACKWARD || simulation_type == EVALUATE_FORWARD)
         {
@@ -385,9 +380,9 @@ DynamicModel::writeModelEquationsOrdered_M(const string &dynamic_basename) const
           output << "  else\n";
           if (simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE || simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE)
             {
-              output << "    g1 = spalloc(" << block_mfs << "*options_.periods, "
-                     << block_mfs << "*(options_.periods+" << max_leadlag_block[block].first+max_leadlag_block[block].second+1 << ")"
-                     << ", " << nze << "*options_.periods);\n";
+              output << "    g1 = spalloc(" << block_mfs << "*Periods, "
+                     << block_mfs << "*(Periods+" << max_leadlag_block[block].first+max_leadlag_block[block].second+1 << ")"
+                     << ", " << nze << "*Periods);\n";
             }
           else
             {
@@ -825,7 +820,6 @@ DynamicModel::writeModelEquationsCode(string &file_name, const string &bin_basen
   //Temporary variables declaration
   FDIMT_ fdimt(temporary_terms.size());
   fdimt.write(code_file, instruction_number);
-  int other_endo_size = 0;
 
   vector<unsigned int> exo, exo_det, other_endo;
 
@@ -868,6 +862,7 @@ DynamicModel::writeModelEquationsCode(string &file_name, const string &bin_basen
   prev_lag = -999999999;
   int prev_type = -1;
   int count_col_exo = 0;
+  int count_col_det_exo = 0;
 
   for (map<pair< pair<int, int>, pair<int, int> >, expr_t>::const_iterator it = first_derivatives_reordered_exo.begin();
        it != first_derivatives_reordered_exo.end(); it++)
@@ -880,7 +875,10 @@ DynamicModel::writeModelEquationsCode(string &file_name, const string &bin_basen
           prev_var = var;
           prev_lag = lag;
           prev_type = type;
-          count_col_exo++;
+          if (type == eExogenous)
+            count_col_exo++;
+          else if (type == eExogenousDet)
+            count_col_det_exo++;
         }
     }
   
@@ -892,13 +890,15 @@ DynamicModel::writeModelEquationsCode(string &file_name, const string &bin_basen
                            equation_reordered,
                            false,
                            symbol_table.endo_nbr(),
-                           0,
-                           0,
+                           max_endo_lag,
+                           max_endo_lead,
                            u_count_int,
                            count_col_endo,
                            symbol_table.exo_det_nbr(),
+                           count_col_det_exo,
+                           symbol_table.exo_nbr(),
                            count_col_exo,
-                           other_endo_size,
+                           0,
                            0,
                            exo_det,
                            exo,
@@ -1098,9 +1098,8 @@ DynamicModel::writeModelEquationsCode_Block(string &file_name, const string &bin
       unsigned int block_size = getBlockSize(block);
       unsigned int block_mfs = getBlockMfs(block);
       unsigned int block_recursive = block_size - block_mfs;
-      unsigned int block_exo_det_size = exo_det_block[block].size();
-      unsigned int block_other_endo_size = other_endo_block[block].size();
       int block_max_lag = max_leadlag_block[block].first;
+      int block_max_lead = max_leadlag_block[block].second;
 
       if (simulation_type == SOLVE_TWO_BOUNDARIES_SIMPLE || simulation_type == SOLVE_TWO_BOUNDARIES_COMPLETE
           || simulation_type == SOLVE_BACKWARD_COMPLETE || simulation_type == SOLVE_FORWARD_COMPLETE)
@@ -1135,19 +1134,36 @@ DynamicModel::writeModelEquationsCode_Block(string &file_name, const string &bin
               count_col_endo++;
             }
         }
+      unsigned int count_col_det_exo = 0;
       vector<unsigned int> exo_det;
       for (lag_var_t::const_iterator it = exo_det_block[block].begin(); it != exo_det_block[block].end(); it++)
-        exo_det.push_back(it->first);
+        for (var_t::const_iterator it1 = it->second.begin(); it1 != it->second.end(); it1++)
+          {
+            count_col_det_exo++;
+            if (find (exo_det.begin(), exo_det.end(), *it1) == exo_det.end())
+              exo_det.push_back(*it1);
+          }
+            
+      unsigned int count_col_exo = 0;
       vector<unsigned int> exo;
       for (lag_var_t::const_iterator it = exo_block[block].begin(); it != exo_block[block].end(); it++)
-        exo.push_back(it->first);
+        for (var_t::const_iterator it1 = it->second.begin(); it1 != it->second.end(); it1++)
+          {
+            count_col_exo++;
+            if (find (exo.begin(), exo.end(), *it1) == exo.end())
+              exo.push_back(*it1);
+          }
+          
       vector<unsigned int> other_endo;
       unsigned int count_col_other_endo = 0;
       for (lag_var_t::const_iterator it = other_endo_block[block].begin(); it != other_endo_block[block].end(); it++)
-        {
-          other_endo.push_back(it->first);
-          count_col_other_endo += it->second.size();
-        }
+        for (var_t::const_iterator it1 = it->second.begin(); it1 != it->second.end(); it1++)
+          {
+            count_col_other_endo++;
+            if (find (other_endo.begin(), other_endo.end(), *it1) == other_endo.end())
+                other_endo.push_back(*it1);
+          }
+          
       FBEGINBLOCK_ fbeginblock(block_mfs,
                                simulation_type,
                                getBlockFirstEquation(block),
@@ -1157,19 +1173,21 @@ DynamicModel::writeModelEquationsCode_Block(string &file_name, const string &bin
                                blocks_linear[block],
                                symbol_table.endo_nbr(),
                                block_max_lag,
-                               block_max_lag,
+                               block_max_lead,
                                u_count_int,
                                count_col_endo,
-                               block_exo_det_size,
+                               exo_det.size(),
+                               count_col_det_exo,
+                               exo.size(),
                                getBlockExoColSize(block),
-                               block_other_endo_size,
+                               other_endo.size(),
                                count_col_other_endo,
                                exo_det,
                                exo,
                                other_endo
                                );
       fbeginblock.write(code_file, instruction_number);
-
+      
       // The equations
       for (i = 0; i < (int) block_size; i++)
         {
@@ -1412,7 +1430,7 @@ DynamicModel::writeModelEquationsCode_Block(string &file_name, const string &bin
         }
       prev_var = -1;
       prev_lag = -999999999;
-      int count_col_exo = 0;
+      count_col_exo = 0;
       for (map<pair<int, pair<int, int> >, expr_t>::const_iterator it = tmp_exo_derivative.begin(); it != tmp_exo_derivative.end(); it++)
         {
           int lag = it->first.first;
@@ -1766,8 +1784,7 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri
   int Nb_SGE = 0;
   bool open_par = false;
 
-  mDynamicModelFile << "function [varargout] = " << dynamic_basename << "(varargin)\n";
-  mDynamicModelFile << "  global oo_ options_ M_ ;\n";
+  mDynamicModelFile << "function [varargout] = " << dynamic_basename << "(options_, M_, oo_, varargin)\n";
   mDynamicModelFile << "  g2=[];g3=[];\n";
   //Temporary variables declaration
   OK = true;
@@ -1782,7 +1799,7 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri
       (*it)->writeOutput(tmp_output, oMatlabStaticModelSparse, temporary_terms);
     }
   if (tmp_output.str().length() > 0)
-    mDynamicModelFile << "  global " << tmp_output.str() << " M_ ;\n";
+    mDynamicModelFile << "  global " << tmp_output.str() << ";\n";
 
   mDynamicModelFile << "  T_init=zeros(1,options_.periods+M_.maximum_lag+M_.maximum_lead);\n";
   tmp_output.str("");
@@ -1859,7 +1876,7 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri
           break;
         case SOLVE_TWO_BOUNDARIES_COMPLETE:
         case SOLVE_TWO_BOUNDARIES_SIMPLE:
-          mDynamicModelFile << "    [r, y, dr(" << count_call << ").g1, dr(" << count_call << ").g2, dr(" << count_call << ").g3, b, dr(" << count_call << ").g1_x, dr(" << count_call << ").g1_xd, dr(" << count_call << ").g1_o]=" << dynamic_basename << "_" <<  block + 1 << "(y, x, params, steady_state, it_-" << max_lag << ", 1, " << max_lag << ", " << block_recursive << ");\n";
+          mDynamicModelFile << "    [r, y, dr(" << count_call << ").g1, dr(" << count_call << ").g2, dr(" << count_call << ").g3, b, dr(" << count_call << ").g1_x, dr(" << count_call << ").g1_xd, dr(" << count_call << ").g1_o]=" << dynamic_basename << "_" <<  block + 1 << "(y, x, params, steady_state, it_-" << max_lag << ", 1, " << max_lag << ", " << block_recursive << "," << "options_.periods" << ");\n";
           mDynamicModelFile << "    residual(y_index_eq)=r(:,M_.maximum_lag+1);\n";
           break;
         default:
@@ -1891,9 +1908,11 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri
                     << "  else" << endl
                     << "    mthd='UNKNOWN';" << endl
                     << "  end;" << endl
-                    << "  disp (['-----------------------------------------------------']) ;" << endl
-                    << "  disp (['MODEL SIMULATION: (method=' mthd ')']) ;" << endl
-                    << "  fprintf('\\n') ;" << endl
+		    << "  if options_.verbosity" << endl 
+                    << "    printline(41)" << endl
+                    << "    disp(sprintf('MODEL SIMULATION (method=%s):',mthd))" << endl
+		    << "    skipline()" << endl
+		    << "  end" << endl
                     << "  periods=options_.periods;" << endl
                     << "  maxit_=options_.simul.maxit;" << endl
                     << "  solve_tolf=options_.solve_tolf;" << endl
@@ -1930,7 +1949,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 any(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";
@@ -2012,7 +2031,7 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri
           mDynamicModelFile << "  y = solve_one_boundary('"  << dynamic_basename << "_" <<  block + 1 << "'"
                             <<", y, x, params, steady_state, y_index, " << nze
                             <<", options_.periods, " << blocks_linear[block]
-                            <<", blck_num, y_kmin, options.simul.maxit, options_.solve_tolf, options_.slowc, " << cutoff << ", options_.stack_solve_algo, 1, 1, 0);\n";
+                            <<", blck_num, y_kmin, options_.simul.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 any(isnan(tmp) | isinf(tmp))\n";
           mDynamicModelFile << "    disp(['Inf or Nan value during the resolution of block " << block <<"']);\n";
@@ -2042,7 +2061,7 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri
                             <<", options_.periods, " << max_leadlag_block[block].first
                             <<", " << max_leadlag_block[block].second
                             <<", " << blocks_linear[block]
-                            <<", blck_num, y_kmin, options_.simul.maxit, options_.solve_tolf, options_.slowc, " << cutoff << ", options_.stack_solve_algo, M_, oo_);\n";
+                            <<", blck_num, y_kmin, options_.simul.maxit, options_.solve_tolf, options_.slowc, " << cutoff << ", options_.stack_solve_algo, options_, M_, oo_);\n";
           mDynamicModelFile << "  tmp = y(:,M_.block_structure.block(" << block + 1 << ").variable);\n";
           mDynamicModelFile << "  if any(isnan(tmp) | isinf(tmp))\n";
           mDynamicModelFile << "    disp(['Inf or Nan value during the resolution of block " << block <<"']);\n";
@@ -2054,6 +2073,7 @@ DynamicModel::writeSparseDynamicMFile(const string &dynamic_basename, const stri
     mDynamicModelFile << "  end;\n";
   open_par = false;
   mDynamicModelFile << "  oo_.endo_simul = y';\n";
+  mDynamicModelFile << "  varargout{1} = oo_;\n";
   mDynamicModelFile << "return;\n";
   mDynamicModelFile << "end" << endl;
 
@@ -2773,89 +2793,6 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de
           
           typedef pair<int, pair<int, int > > index_KF;
           vector<index_KF> v_index_KF;
-          
-          /*   DO 170, J = 1, N
-                TEMP1 = ALPHA*A( J, J )
-                DO 110, I = 1, M
-                   C( I, J ) = TEMP1*B( I, J )
-  11  110       CONTINUE
-                DO 140, K = 1, J - 1
-                   TEMP1 = ALPHA*A( K, J )
-                   DO 130, I = 1, M
-                      C( I, J ) = C( I, J ) + TEMP1*B( I, K )
-  13  130          CONTINUE
-  14  140       CONTINUE
-                DO 160, K = J + 1, N
-                   TEMP1 = ALPHA*A( J, K )
-                   DO 150, I = 1, M
-                      C( I, J ) = C( I, J ) + TEMP1*B( I, K )
-  15  150          CONTINUE
-  16  160       CONTINUE
-  17  170    CONTINUE
-          for(int j = 0; j < n; j++)
-            {
-              double temp1 = P_t_t1[j + j * n];
-              for (int i = 0; i < n; i++)
-                tmp[i + j * n] = tmp1 * T[i + j * n];
-              for (int k = 0; k < j - 1; k++)
-                {
-                  temp1 = P_t_t1[k + j * n];
-                  for (int i = 0; i < n; i++)
-                    tmp[i + j * n] += temp1 * T[i + k * n];
-                }
-              for (int k = j + 1; k < n; k++)
-                {
-                  temp1 = P_t_t1[j + k * n];
-                  for (int i = 0; i < n; i++)
-                    tmp[i + j * n] += temp1 * T[i + k * n];
-                }
-            }
-
-          for(int j = n_obs; j < n; j++)
-            {
-              int j1 = j - n_obs;
-              double temp1 = P_t_t1[j1 + j1 * n_state];
-              for (int i = 0; i < n; i++)
-                tmp[i + j1 * n] = tmp1 * T[i + j * n];
-              for (int k = n_obs; k < j - 1; k++)
-                {
-                  int k1 = k - n_obs;
-                  temp1 = P_t_t1[k1 + j1 * n_state];
-                  for (int i = 0; i < n; i++)
-                    tmp[i + j1 * n] += temp1 * T[i + k * n];
-                }
-              for (int k = max(j + 1, n_obs); k < n; k++)
-                {
-                  int k1 = k - n_obs;
-                  temp1 = P_t_t1[j1 + k1 * n_state];
-                  for (int i = 0; i < n; i++)
-                    tmp[i + j1 * n] += temp1 * T[i + k * n];
-                }
-            }
-          
-          for(int j = n_obs; j < n; j++)
-            {
-              int j1 = j - n_obs;
-              double temp1 = P_t_t1[j1 + j1 * n_state];
-              for (int i = 0; i < n; i++)
-                tmp[i + j1 * n] = tmp1 * T[i + j * n];
-              for (int k = n_obs; k < j - 1; k++)
-                {
-                  int k1 = k - n_obs;
-                  temp1 = P_t_t1[k1 + j1 * n_state];
-                  for (int i = 0; i < n; i++)
-                  if ((i < n_obs) || (i >= nb_diag + n_obs) || (j1 >= nb_diag))
-                      tmp[i + j1 * n] += temp1 * T[i + k * n];
-                }
-              for (int k = max(j + 1, n_obs); k < n; k++)
-                {
-                  int k1 = k - n_obs;
-                  temp1 = P_t_t1[j1 + k1 * n_state];
-                  for (int i = 0; i < n; i++)
-                    if ((i < n_obs) || (i >= nb_diag + n_obs) || (j1 >= nb_diag))
-                      tmp[i + j1 * n] += temp1 * T[i + k * n];
-                }
-            }*/
           for (int i = 0; i < n; i++)
             //int i = 0;
             for (int j = n_obs; j < n; j++)
@@ -2874,7 +2811,6 @@ DynamicModel::writeOutput(ostream &output, const string &basename, bool block_de
           for (vector<index_KF>::iterator it = v_index_KF.begin(); it != v_index_KF.end(); it++)
             KF_index_file.write(reinterpret_cast<char *>(&(*it)), sizeof(index_KF));
 
-          //typedef pair<pair<int, int>, pair<int, int > > index_KF_2;
           vector<index_KF> v_index_KF_2;
           int n_n_obs = n * n_obs;
           for (int i = 0; i < n; i++)
@@ -3230,12 +3166,13 @@ DynamicModel::collect_block_first_order_derivatives()
       int var = symbol_table.getTypeSpecificID(getSymbIDByDerivID(it2->first.second));
       int lag = getLagByDerivID(it2->first.second);
       int block_eq = equation_2_block[eq];
-      int block_var = variable_2_block[var];
+      int block_var=0;
       derivative_t tmp_derivative;
       lag_var_t lag_var;
       switch (getTypeByDerivID(it2->first.second))
         {
         case eEndogenous:
+          block_var = variable_2_block[var];
           if (block_eq == block_var)
             {
               if (lag < 0 && lag < -endo_max_leadlag_block[block_eq].first)
@@ -3973,6 +3910,12 @@ DynamicModel::writeLatexFile(const string &basename) const
   writeLatexModelFile(basename + "_dynamic.tex", oLatexDynamicModel);
 }
 
+void
+DynamicModel::writeLatexOriginalFile(const string &basename) const
+{
+  writeLatexModelFile(basename + "_original.tex", oLatexDynamicModel);
+}
+
 void
 DynamicModel::substituteEndoLeadGreaterThanTwo(bool deterministic_model)
 {
@@ -4278,5 +4221,117 @@ DynamicModel::dynamicOnlyEquationsNbr() const
   return eqs.size();
 }
 
+#ifndef PRIVATE_BUFFER_SIZE
+#define PRIVATE_BUFFER_SIZE 1024
+#endif
 
+bool
+DynamicModel::isChecksumMatching(const string &basename) const
+{
+  boost::crc_32_type result;
 
+  std::stringstream buffer;
+
+  // Write equation tags
+  for (size_t i = 0; i < equation_tags.size(); i++)
+    buffer << "  " << equation_tags[i].first + 1
+           << equation_tags[i].second.first
+           << equation_tags[i].second.second;
+
+  ExprNodeOutputType buffer_type = oCDynamicModel;
+
+  for (int eq = 0; eq < (int) equations.size(); eq++)
+    {
+      BinaryOpNode *eq_node = equations[eq];
+      expr_t lhs = eq_node->get_arg1();
+      expr_t rhs = eq_node->get_arg2();
+
+      // Test if the right hand side of the equation is empty.
+      double vrhs = 1.0;
+      try
+        {
+          vrhs = rhs->eval(eval_context_t());
+        }
+      catch (ExprNode::EvalException &e)
+        {
+        }
+
+      if (vrhs != 0) // The right hand side of the equation is not empty ==> residual=lhs-rhs;
+        {
+          buffer << "lhs =";
+          lhs->writeOutput(buffer, buffer_type, temporary_terms);
+          buffer << ";" << endl;
+
+          buffer << "rhs =";
+          rhs->writeOutput(buffer, buffer_type, temporary_terms);
+          buffer << ";" << endl;
+
+          buffer << "residual" << LEFT_ARRAY_SUBSCRIPT(buffer_type)
+                 << eq + ARRAY_SUBSCRIPT_OFFSET(buffer_type)
+                 << RIGHT_ARRAY_SUBSCRIPT(buffer_type)
+                 << "= lhs-rhs;" << endl;
+        }
+      else // The right hand side of the equation is empty ==> residual=lhs;
+        {
+          buffer << "residual" << LEFT_ARRAY_SUBSCRIPT(buffer_type)
+                 << eq + ARRAY_SUBSCRIPT_OFFSET(buffer_type)
+                 << RIGHT_ARRAY_SUBSCRIPT(buffer_type)
+                 << " = ";
+          lhs->writeOutput(buffer, buffer_type, temporary_terms);
+          buffer << ";" << endl;
+        }
+    }
+
+  char private_buffer[PRIVATE_BUFFER_SIZE];
+  while(buffer)
+    {
+      buffer.get(private_buffer,PRIVATE_BUFFER_SIZE);
+      result.process_bytes(private_buffer,strlen(private_buffer));
+    }
+
+  bool basename_dir_exists = false;
+#ifdef _WIN32
+  int r = mkdir(basename.c_str());
+#else
+  int r = mkdir(basename.c_str(), 0777);
+#endif
+  if (r < 0)
+    if (errno != EEXIST)
+      {
+	perror("ERROR");
+	exit(EXIT_FAILURE);
+      }
+    else
+      basename_dir_exists = true;
+
+  // check whether basename directory exist. If not, create it.
+  // If it does, read old checksum if it exist
+  fstream checksum_file;
+  string filename = basename + "/checksum";
+  unsigned int old_checksum = 0;
+  // read old checksum if it exists
+  if (basename_dir_exists)
+    {
+      checksum_file.open(filename.c_str(), ios::in | ios::binary);
+      if (checksum_file.is_open())
+	{
+	  checksum_file >> old_checksum;
+	  checksum_file.close();
+	}
+    }
+  // write new checksum file if none or different from old checksum
+  if (old_checksum != result.checksum())
+	{
+	  checksum_file.open(filename.c_str(), ios::out | ios::binary);
+	  if (!checksum_file.is_open())
+	    {
+	      cerr << "ERROR: Can't open file " << filename << endl;
+	      exit(EXIT_FAILURE);
+	    }
+	  checksum_file << result.checksum();
+	  checksum_file.close();
+	  return false;
+	}
+  
+  return true;
+}
diff --git a/preprocessor/DynamicModel.hh b/preprocessor/DynamicModel.hh
index 7f019f260fc3ffc290bdb3e4159706ba0fe4156f..d96a7d5045649069d73d46e5aecb9ffaf7f2e758 100644
--- a/preprocessor/DynamicModel.hh
+++ b/preprocessor/DynamicModel.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2014 Dynare Team
+ * Copyright (C) 2003-2015 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -24,6 +24,7 @@ using namespace std;
 #define ZERO_BAND 1e-8
 
 #include <fstream>
+#include <boost/crc.hpp>
 
 #include "StaticModel.hh"
 
@@ -252,6 +253,9 @@ public:
   //! Writes LaTeX file with the equations of the dynamic model
   void writeLatexFile(const string &basename) const;
 
+  //! Writes LaTeX file with the equations of the dynamic model (for the original model)
+  void writeLatexOriginalFile(const string &basename) const;
+
   virtual int getDerivID(int symb_id, int lag) const throw (UnknownDerivIDException);
   virtual int getDynJacobianCol(int deriv_id) const throw (UnknownDerivIDException);
   virtual void addAllParamDerivId(set<int> &deriv_id_set);
@@ -476,6 +480,8 @@ public:
   void writeSecondDerivativesC_csr(const string &basename, bool cuda) const;
   //! Writes C file containing third order derivatives of model evaluated at steady state (compressed sparse column)
   void writeThirdDerivativesC_csr(const string &basename, bool cuda) const;
+
+  bool isChecksumMatching(const string &basename) const;
 };
 
 //! Classes to re-order derivatives for various sparse storage formats 
diff --git a/preprocessor/DynareBison.yy b/preprocessor/DynareBison.yy
index a92801207b30fbe9414955f65fae44061c49096f..5893b6dc154e60e931bf91348ab233eb99a2c4c6 100644
--- a/preprocessor/DynareBison.yy
+++ b/preprocessor/DynareBison.yy
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2014 Dynare Team
+ * Copyright (C) 2003-2015 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -82,17 +82,17 @@ class ParsingDriver;
 #define yylex driver.lexer->lex
 }
 
-%token AIM_SOLVER ANALYTIC_DERIVATION AR AUTOCORR
-%token BAYESIAN_IRF BETA_PDF BLOCK USE_CALIBRATION
-%token BVAR_DENSITY BVAR_FORECAST NODECOMPOSITION
-%token BVAR_PRIOR_DECAY BVAR_PRIOR_FLAT BVAR_PRIOR_LAMBDA
+%token AIM_SOLVER ANALYTIC_DERIVATION AR AUTOCORR TARB_MODE_COMPUTE
+%token BAYESIAN_IRF BETA_PDF BLOCK USE_CALIBRATION USE_TARB TARB_NEW_BLOCK_PROBABILITY
+%token BVAR_DENSITY BVAR_FORECAST NODECOMPOSITION DR_DISPLAY_TOL HUGE_NUMBER
+%token BVAR_PRIOR_DECAY BVAR_PRIOR_FLAT BVAR_PRIOR_LAMBDA TARB_OPTIM
 %token BVAR_PRIOR_MU BVAR_PRIOR_OMEGA BVAR_PRIOR_TAU BVAR_PRIOR_TRAIN
-%token BVAR_REPLIC BYTECODE ALL_VALUES_REQUIRED
+%token BVAR_REPLIC BYTECODE ALL_VALUES_REQUIRED PROPOSAL_DISTRIBUTION
 %token CALIB_SMOOTHER CHANGE_TYPE CHECK CONDITIONAL_FORECAST CONDITIONAL_FORECAST_PATHS CONF_SIG CONSTANT CONTROLLED_VAREXO CORR COVAR CUTOFF CYCLE_REDUCTION LOGARITHMIC_REDUCTION
-%token CONSIDER_ALL_ENDOGENOUS CONSIDER_ONLY_OBSERVED
+%token CONSIDER_ALL_ENDOGENOUS CONSIDER_ONLY_OBSERVED STUDENT_DEGREES_OF_FREEDOM
 %token DATAFILE FILE SERIES DOUBLING DR_CYCLE_REDUCTION_TOL DR_LOGARITHMIC_REDUCTION_TOL DR_LOGARITHMIC_REDUCTION_MAXITER DR_ALGO DROP DSAMPLE DYNASAVE DYNATYPE CALIBRATION DIFFERENTIATE_FORWARD_VARS
 %token END ENDVAL EQUAL ESTIMATION ESTIMATED_PARAMS ESTIMATED_PARAMS_BOUNDS ESTIMATED_PARAMS_INIT EXTENDED_PATH ENDOGENOUS_PRIOR
-%token FILENAME FILTER_STEP_AHEAD FILTERED_VARS FIRST_OBS LAST_OBS SET_TIME
+%token FILENAME DIRNAME FILTER_STEP_AHEAD FILTERED_VARS FIRST_OBS LAST_OBS SET_TIME
 %token <string_val> FLOAT_NUMBER DATES
 %token DEFAULT FIXED_POINT OPT_ALGO
 %token FORECAST K_ORDER_SOLVER INSTRUMENTS SHIFT MEAN STDEV VARIANCE MODE INTERVAL SHAPE DOMAINN
@@ -101,14 +101,14 @@ class ParsingDriver;
 %token IDENTIFICATION INF_CONSTANT INITVAL INITVAL_FILE BOUNDS JSCALE INIT INFILE INVARS
 %token <string_val> INT_NUMBER
 %token INV_GAMMA_PDF INV_GAMMA1_PDF INV_GAMMA2_PDF IRF IRF_SHOCKS IRF_PLOT_THRESHOLD IRF_CALIBRATION
-%token KALMAN_ALGO KALMAN_TOL SUBSAMPLES OPTIONS TOLF
+%token KALMAN_ALGO KALMAN_TOL DIFFUSE_KALMAN_TOL SUBSAMPLES OPTIONS TOLF
 %token LAPLACE LIK_ALGO LIK_INIT LINEAR LOAD_IDENT_FILES LOAD_MH_FILE LOAD_PARAMS_AND_STEADY_STATE LOGLINEAR LOGDATA LYAPUNOV
 %token LYAPUNOV_FIXED_POINT_TOL LYAPUNOV_DOUBLING_TOL LYAPUNOV_SQUARE_ROOT_SOLVER_TOL LOG_DEFLATOR LOG_TREND_VAR LOG_GROWTH_FACTOR MARKOWITZ MARGINAL_DENSITY MAX MAXIT
 %token MFS MH_CONF_SIG MH_DROP MH_INIT_SCALE MH_JSCALE MH_MODE MH_NBLOCKS MH_REPLIC MH_RECOVER POSTERIOR_MAX_SUBSAMPLE_DRAWS MIN MINIMAL_SOLVING_PERIODS
 %token MODE_CHECK MODE_CHECK_NEIGHBOURHOOD_SIZE MODE_CHECK_SYMMETRIC_PLOTS MODE_CHECK_NUMBER_OF_POINTS MODE_COMPUTE MODE_FILE MODEL MODEL_COMPARISON MODEL_INFO MSHOCKS ABS SIGN
 %token MODEL_DIAGNOSTICS MODIFIEDHARMONICMEAN MOMENTS_VARENDO DIFFUSE_FILTER SUB_DRAWS TAPER_STEPS GEWEKE_INTERVAL MCMC_JUMPING_COVARIANCE MOMENT_CALIBRATION
 %token NUMBER_OF_PARTICLES RESAMPLING SYSTEMATIC GENERIC RESAMPLING_THRESHOLD RESAMPLING_METHOD KITAGAWA STRATIFIED SMOOTH
-%token FILTER_ALGORITHM SIS APF GF GMF CPF PROPOSAL_APPROXIMATION CUBATURE UNSCENTED MONTECARLO DISTRIBUTION_APPROXIMATION
+%token FILTER_ALGORITHM PROPOSAL_APPROXIMATION CUBATURE UNSCENTED MONTECARLO DISTRIBUTION_APPROXIMATION
 %token <string_val> NAME
 %token NAN_CONSTANT NO_STATIC NOBS NOCONSTANT NODISPLAY NOCORR NODIAGNOSTIC NOFUNCTIONS NO_HOMOTOPY
 %token NOGRAPH NOMOMENTS NOPRINT NORMAL_PDF SAVE_DRAWS
@@ -126,7 +126,7 @@ class ParsingDriver;
 %token <string_val> TEX_NAME
 %token UNIFORM_PDF UNIT_ROOT_VARS USE_DLL USEAUTOCORR GSA_SAMPLE_FILE USE_UNIVARIATE_FILTERS_IF_SINGULARITY_IS_DETECTED
 %token VALUES VAR VAREXO VAREXO_DET VAROBS PREDETERMINED_VARIABLES
-%token WRITE_LATEX_DYNAMIC_MODEL WRITE_LATEX_STATIC_MODEL
+%token WRITE_LATEX_DYNAMIC_MODEL WRITE_LATEX_STATIC_MODEL WRITE_LATEX_ORIGINAL_MODEL
 %token XLS_SHEET XLS_RANGE LONG_NAME
 %left COMMA
 %left EQUAL_EQUAL EXCLAMATION_EQUAL
@@ -148,7 +148,7 @@ class ParsingDriver;
 %token RESTRICTION RESTRICTION_FNAME CROSS_RESTRICTIONS NLAGS CONTEMP_REDUCED_FORM REAL_PSEUDO_FORECAST
 %token 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 EPS PDF FIG DR NONE PRIOR PRIOR_VARIANCE HESSIAN IDENTITY_MATRIX DIRICHLET
-%token GSIG2_LMDM Q_DIAG FLAT_PRIOR NCSK NSTD
+%token GSIG2_LMDM Q_DIAG FLAT_PRIOR NCSK NSTD WEIBULL WEIBULL_PDF
 %token INDXPARR INDXOVR INDXAP APBAND INDXIMF IMFBAND INDXFORE FOREBAND INDXGFOREHAT INDXGIMFHAT
 %token INDXESTIMA INDXGDLS EQ_MS FILTER_COVARIANCE FILTER_DECOMPOSITION
 %token EQ_CMS TLINDX TLNUMBER BANACT RESTRICTIONS
@@ -171,6 +171,7 @@ class ParsingDriver;
 %token PARAMETER_CONVERGENCE_CRITERION NUMBER_OF_LARGE_PERTURBATIONS NUMBER_OF_SMALL_PERTURBATIONS
 %token NUMBER_OF_POSTERIOR_DRAWS_AFTER_PERTURBATION MAX_NUMBER_OF_STAGES
 %token RANDOM_FUNCTION_CONVERGENCE_CRITERION RANDOM_PARAMETER_CONVERGENCE_CRITERION
+%token <vector_string_val> SYMBOL_VEC
 
 %type <node_val> expression expression_or_empty
 %type <node_val> equation hand_side
@@ -250,6 +251,7 @@ statement : parameters
           | identification
           | write_latex_dynamic_model
           | write_latex_static_model
+          | write_latex_original_model
           | shock_decomposition
           | conditional_forecast
           | conditional_forecast_paths
@@ -1092,6 +1094,7 @@ stoch_simul_primary_options : o_dr_algo
                             | o_dr_logarithmic_reduction_tol
                             | o_dr_logarithmic_reduction_maxiter
                             | o_irf_plot_threshold
+                            | o_dr_display_tol
                             ;
 
 stoch_simul_options : stoch_simul_primary_options
@@ -1330,6 +1333,8 @@ prior_distribution : BETA
                      { $$ = eInvGamma2; }
                    | DIRICHLET
                      { $$ = eDirichlet; }
+                   | WEIBULL
+                     { $$ = eWeibull; }
                    ;
 
 prior_pdf : BETA_PDF
@@ -1346,6 +1351,8 @@ prior_pdf : BETA_PDF
             { $$ = eUniform; }
           | INV_GAMMA2_PDF
             { $$ = eInvGamma2; }
+          | WEIBULL_PDF
+            { $$ = eWeibull; }
           ;
 
 date_str : DATES { $$ = $1; }
@@ -1417,6 +1424,8 @@ prior : symbol '.' PRIOR { driver.set_prior_variance(); driver.prior_shape = eNo
         { driver.set_prior($1, new string ("")); }
       | symbol '.' symbol '.' PRIOR { driver.set_prior_variance(); driver.prior_shape = eNoShape; } '(' prior_options_list ')' ';'
         { driver.set_prior($1, $3); }
+      | SYMBOL_VEC '.' PRIOR { driver.set_prior_variance(); driver.prior_shape = eNoShape; }  '(' joint_prior_options_list ')' ';'
+        { driver.set_joint_prior($1); }
       | STD '(' symbol ')' '.' PRIOR { driver.set_prior_variance(); driver.prior_shape = eNoShape; } '(' prior_options_list ')' ';'
         { driver.set_std_prior($3, new string ("")); }
       | STD '(' symbol ')' '.' symbol '.' PRIOR { driver.set_prior_variance(); driver.prior_shape = eNoShape; } '(' prior_options_list ')' ';'
@@ -1443,6 +1452,22 @@ prior_options : o_shift
               | o_domain
               ;
 
+joint_prior_options_list : joint_prior_options_list COMMA joint_prior_options
+                         | joint_prior_options
+                         ;
+
+joint_prior_options : o_shift
+                    | o_mean_vec
+                    | o_median
+                    | o_stdev
+                    | o_truncate
+                    | o_variance_mat
+                    | o_mode
+                    | o_interval
+                    | o_shape
+                    | o_domain
+                    ;
+
 prior_eq : prior_eq_opt EQUAL prior_eq_opt ';'
            {
              driver.copy_prior($1->at(0), $1->at(1), $1->at(2), $1->at(3),
@@ -1640,6 +1665,7 @@ estimation_options : o_datafile
                    | o_filtered_vars
                    | o_kalman_algo
                    | o_kalman_tol
+		   | o_diffuse_kalman_tol
                    | o_xls_sheet
                    | o_xls_range
                    | o_filter_step_ahead
@@ -1687,6 +1713,14 @@ estimation_options : o_datafile
 		   | o_filter_algorithm
 		   | o_proposal_approximation
 		   | o_distribution_approximation
+                   | o_dirname
+                   | o_huge_number
+                   | o_use_tarb
+                   | o_tarb_mode_compute
+                   | o_tarb_new_block_probability
+                   | o_tarb_optim
+                   | o_proposal_distribution
+                   | o_student_degrees_of_freedom
                    ;
 
 list_optim_option : QUOTED_STRING COMMA QUOTED_STRING
@@ -1699,6 +1733,16 @@ optim_options : list_optim_option
               | optim_options COMMA list_optim_option;
               ;
 
+list_tarb_optim_option : QUOTED_STRING COMMA QUOTED_STRING
+                         { driver.tarb_optim_options_string($1, $3); }
+                       | QUOTED_STRING COMMA signed_number
+                         { driver.tarb_optim_options_num($1, $3); }
+                       ;
+
+tarb_optim_options : list_tarb_optim_option
+                   | tarb_optim_options COMMA list_tarb_optim_option;
+                   ;
+
 varobs : VAROBS { driver.check_varobs(); } varobs_list ';';
 
 varobs_list : varobs_list symbol
@@ -1743,6 +1787,7 @@ osr_options : stoch_simul_primary_options
             | o_osr_tolf
             | o_opt_algo
             | o_optim
+            | o_huge_number
             ;
 
 osr : OSR ';'
@@ -1902,6 +1947,10 @@ write_latex_static_model : WRITE_LATEX_STATIC_MODEL ';'
                            { driver.write_latex_static_model(); }
                          ;
 
+write_latex_original_model : WRITE_LATEX_ORIGINAL_MODEL ';'
+                           { driver.write_latex_original_model(); }
+                         ;
+
 shock_decomposition : SHOCK_DECOMPOSITION ';'
                       {driver.shock_decomposition(); }
                     | SHOCK_DECOMPOSITION '(' shock_decomposition_options_list ')' ';'
@@ -2517,6 +2566,8 @@ o_qz_zero_threshold : QZ_ZERO_THRESHOLD EQUAL non_negative_number { driver.optio
 o_file : FILE EQUAL filename { driver.option_str("file", $3); };
 o_series : SERIES EQUAL symbol { driver.option_str("series", $3); };
 o_datafile : DATAFILE EQUAL filename { driver.option_str("datafile", $3); };
+o_dirname : DIRNAME EQUAL filename { driver.option_str("dirname", $3); };
+o_huge_number : HUGE_NUMBER EQUAL non_negative_number { driver.option_num("huge_number", $3); };
 o_nobs : NOBS EQUAL vec_int
          { driver.option_vec_int("nobs", $3); }
        | NOBS EQUAL vec_int_number
@@ -2535,6 +2586,7 @@ o_shift : SHIFT EQUAL signed_number { driver.option_num("shift", $3); };
 o_shape : SHAPE EQUAL prior_distribution { driver.prior_shape = $3; };
 o_mode : MODE EQUAL signed_number { driver.option_num("mode", $3); };
 o_mean : MEAN EQUAL signed_number { driver.option_num("mean", $3); };
+o_mean_vec : MEAN EQUAL vec_value { driver.option_num("mean", $3); };
 o_truncate : TRUNCATE EQUAL vec_value { driver.option_num("truncate", $3); };
 o_stdev : STDEV EQUAL non_negative_number { driver.option_num("stdev", $3); };
 o_jscale : JSCALE EQUAL non_negative_number { driver.option_num("jscale", $3); };
@@ -2543,6 +2595,7 @@ o_bounds : BOUNDS EQUAL vec_value_w_inf { driver.option_num("bounds", $3); };
 o_domain : DOMAINN EQUAL vec_value { driver.option_num("domain", $3); };
 o_interval : INTERVAL EQUAL vec_value { driver.option_num("interval", $3); };
 o_variance : VARIANCE EQUAL expression { driver.set_prior_variance($3); }
+o_variance_mat : VARIANCE EQUAL vec_of_vec_value { driver.option_num("variance",$3); }
 o_prefilter : PREFILTER EQUAL INT_NUMBER { driver.option_num("prefilter", $3); };
 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); };
@@ -2581,6 +2634,9 @@ o_posterior_max_subsample_draws : POSTERIOR_MAX_SUBSAMPLE_DRAWS EQUAL INT_NUMBER
 o_mh_drop : MH_DROP EQUAL non_negative_number { driver.option_num("mh_drop", $3); };
 o_mh_jscale : MH_JSCALE EQUAL non_negative_number { driver.option_num("mh_jscale", $3); };
 o_optim : OPTIM  EQUAL '(' optim_options ')';
+o_tarb_optim : TARB_OPTIM  EQUAL '(' tarb_optim_options ')';
+o_proposal_distribution : PROPOSAL_DISTRIBUTION EQUAL symbol { driver.option_str("proposal_distribution", $3); };
+o_student_degrees_of_freedom : STUDENT_DEGREES_OF_FREEDOM EQUAL INT_NUMBER { driver.option_num("student_degrees_of_freedom", $3); };
 o_mh_init_scale : MH_INIT_SCALE EQUAL non_negative_number { driver.option_num("mh_init_scale", $3); };
 o_mode_file : MODE_FILE EQUAL filename { driver.option_str("mode_file", $3); };
 o_mode_compute : MODE_COMPUTE EQUAL INT_NUMBER { driver.option_num("mode_compute", $3); };
@@ -2613,6 +2669,7 @@ o_filtered_vars : FILTERED_VARS { driver.option_num("filtered_vars", "1"); };
 o_relative_irf : RELATIVE_IRF { driver.option_num("relative_irf", "1"); };
 o_kalman_algo : KALMAN_ALGO EQUAL INT_NUMBER { driver.option_num("kalman_algo", $3); };
 o_kalman_tol : KALMAN_TOL EQUAL non_negative_number { driver.option_num("kalman_tol", $3); };
+o_diffuse_kalman_tol : DIFFUSE_KALMAN_TOL EQUAL non_negative_number { driver.option_num("diffuse_kalman_tol", $3); };
 o_marginal_density : MARGINAL_DENSITY EQUAL LAPLACE
                      { driver.option_str("mc_marginal_density", "laplace"); }
                    | MARGINAL_DENSITY EQUAL MODIFIEDHARMONICMEAN
@@ -2667,11 +2724,7 @@ o_resampling_threshold : RESAMPLING_THRESHOLD EQUAL non_negative_number { driver
 o_resampling_method : RESAMPLING_METHOD EQUAL KITAGAWA {driver.option_num("particle.resampling.method.kitagawa", "1"); driver.option_num("particle.resampling.method.smooth", "0"); driver.option_num("particle.resampling.smethod.stratified", "0"); }
               | RESAMPLING_METHOD EQUAL SMOOTH {driver.option_num("particle.resampling.method.kitagawa", "0"); driver.option_num("particle.resampling.method.smooth", "1"); driver.option_num("particle.resampling.smethod.stratified", "0"); }
               | RESAMPLING_METHOD EQUAL STRATIFIED {driver.option_num("particle.resampling.method.kitagawa", "0"); driver.option_num("particle.resampling.method.smooth", "0"); driver.option_num("particle.resampling.method.stratified", "1"); };
-o_filter_algorithm : FILTER_ALGORITHM EQUAL SIS {driver.option_num("particle.filter_algorithm.sis", "1"); driver.option_num("particle.filter_algorithm.apf", "0"); driver.option_num("particle.filter_algorithm.gf", "0"); driver.option_num("particle.filter_algorithm.gmf", "0");driver.option_num("particle.filter_algorithm.cpf", "0");}
-		   | FILTER_ALGORITHM EQUAL APF {driver.option_num("particle.filter_algorithm.sis", "0"); driver.option_num("particle.filter_algorithm.apf", "1"); driver.option_num("particle.filter_algorithm.gf", "0"); driver.option_num("particle.filter_algorithm.gmf", "0"); driver.option_num("particle.filter_algorithm.cpf", "0");}
-		   | FILTER_ALGORITHM EQUAL GF {driver.option_num("particle.filter_algorithm.sis", "0"); driver.option_num("particle.filter_algorithm.apf", "0"); driver.option_num("particle.filter_algorithm.gf", "1");  driver.option_num("particle.filter_algorithm.gmf", "0"); driver.option_num("particle.filter_algorithm.cpf", "0");}
-		   | FILTER_ALGORITHM EQUAL GMF {driver.option_num("particle.filter_algorithm.sis", "0"); driver.option_num("particle.filter_algorithm.apf", "0"); driver.option_num("particle.filter_algorithm.gf", "0"); driver.option_num("particle.filter_algorithm.gmf", "1"); driver.option_num("particle.filter_algorithm.cpf", "0");}
-		   | FILTER_ALGORITHM EQUAL CPF {driver.option_num("particle.filter_algorithm.sis", "0"); driver.option_num("particle.filter_algorithm.apf", "0"); driver.option_num("particle.filter_algorithm.gf", "0"); driver.option_num("particle.filter_algorithm.gmf", "0"); driver.option_num("particle.filter_algorithm.cpf", "1");} ;
+o_filter_algorithm : FILTER_ALGORITHM EQUAL symbol { driver.option_str("particle.filter_algorithm", $3); };
 o_proposal_approximation : PROPOSAL_APPROXIMATION EQUAL CUBATURE {driver.option_num("particle.proposal_approximation.cubature", "1"); driver.option_num("particle.proposal_approximation.unscented", "0"); driver.option_num("particle.proposal_approximation.montecarlo", "0");}
 		| PROPOSAL_APPROXIMATION EQUAL UNSCENTED {driver.option_num("particle.proposal_approximation.cubature", "0"); driver.option_num("particle.proposal_approximation.unscented", "1"); driver.option_num("particle.proposal_approximation.montecarlo", "0");}
 		| PROPOSAL_APPROXIMATION EQUAL MONTECARLO {driver.option_num("particle.proposal_approximation.cubature", "0"); driver.option_num("particle.proposal_approximation.unscented", "0"); driver.option_num("particle.proposal_approximation.montecarlo", "1");} ;
@@ -2838,7 +2891,9 @@ o_equations : EQUATIONS EQUAL vec_int
             | EQUATIONS EQUAL vec_int_number
               { driver.option_vec_int("ms.equations",$3); }
             ;
-
+o_use_tarb : USE_TARB { driver.option_num("TaRB.use_TaRB", "1"); };
+o_tarb_mode_compute : TARB_MODE_COMPUTE EQUAL INT_NUMBER { driver.option_num("TaRB.mode_compute", $3); };
+o_tarb_new_block_probability : TARB_NEW_BLOCK_PROBABILITY EQUAL non_negative_number {driver.option_num("TaRB.new_block_probability",$3); };
 o_instruments : INSTRUMENTS EQUAL '(' symbol_list ')' {driver.option_symbol_list("instruments"); };
 
 o_ext_func_name : EXT_FUNC_NAME EQUAL filename { driver.external_function_option("name", $3); };
@@ -2936,6 +2991,7 @@ o_mcmc_jumping_covariance : MCMC_JUMPING_COVARIANCE EQUAL HESSIAN
                             { driver.option_str("MCMC_jumping_covariance", $3); }
                           ;
 o_irf_plot_threshold : IRF_PLOT_THRESHOLD EQUAL non_negative_number { driver.option_num("impulse_responses.plot_threshold", $3); };
+o_dr_display_tol : DR_DISPLAY_TOL EQUAL non_negative_number { driver.option_num("dr_display_tol", $3); };
 o_consider_all_endogenous : CONSIDER_ALL_ENDOGENOUS { driver.option_str("endo_vars_for_moment_computations_in_estimation", "all_endogenous_variables"); };
 o_consider_only_observed : CONSIDER_ONLY_OBSERVED { driver.option_str("endo_vars_for_moment_computations_in_estimation", "only_observed_variables"); };
 o_no_homotopy : NO_HOMOTOPY { driver.option_num("no_homotopy", "1"); };
diff --git a/preprocessor/DynareFlex.ll b/preprocessor/DynareFlex.ll
index 9052a1027dad845da6378e740c5e5bdd292fc486..92d52ecfe64c42049c56eae44838b17a8e250d03 100644
--- a/preprocessor/DynareFlex.ll
+++ b/preprocessor/DynareFlex.ll
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2014 Dynare Team
+ * Copyright (C) 2003-2015 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -129,6 +129,7 @@ DATE -?[0-9]+([YyAa]|[Mm]([1-9]|1[0-2])|[Qq][1-4]|[Ww]([1-9]{1}|[1-4][0-9]|5[0-2
 <INITIAL>save_params_and_steady_state  {BEGIN DYNARE_STATEMENT; return token::SAVE_PARAMS_AND_STEADY_STATE;}
 <INITIAL>write_latex_dynamic_model  {BEGIN DYNARE_STATEMENT; return token::WRITE_LATEX_DYNAMIC_MODEL;}
 <INITIAL>write_latex_static_model  {BEGIN DYNARE_STATEMENT; return token::WRITE_LATEX_STATIC_MODEL;}
+<INITIAL>write_latex_original_model  {BEGIN DYNARE_STATEMENT; return token::WRITE_LATEX_ORIGINAL_MODEL;}
 
 <INITIAL>steady {BEGIN DYNARE_STATEMENT; return token::STEADY;}
 <INITIAL>check {BEGIN DYNARE_STATEMENT; return token::CHECK;}
@@ -235,6 +236,7 @@ DATE -?[0-9]+([YyAa]|[Mm]([1-9]|1[0-2])|[Qq][1-4]|[Ww]([1-9]{1}|[1-4][0-9]|5[0-2
 <DYNARE_STATEMENT>dates  {dates_parens_nb=0; BEGIN DATES_STATEMENT; yylval->string_val = new string("dates");}
 <DYNARE_STATEMENT>file                  {return token::FILE;}
 <DYNARE_STATEMENT>datafile 		{return token::DATAFILE;}
+<DYNARE_STATEMENT>dirname       {return token::DIRNAME;}
 <DYNARE_STATEMENT>nobs 			{return token::NOBS;}
 <DYNARE_STATEMENT>last_obs 		{return token::LAST_OBS;}
 <DYNARE_STATEMENT>first_obs 		{return token::FIRST_OBS;}
@@ -287,6 +289,7 @@ DATE -?[0-9]+([YyAa]|[Mm]([1-9]|1[0-2])|[Qq][1-4]|[Ww]([1-9]{1}|[1-4][0-9]|5[0-2
 <DYNARE_STATEMENT>nodiagnostic 	{return token::NODIAGNOSTIC;}
 <DYNARE_STATEMENT>kalman_algo 	{return token::KALMAN_ALGO;}
 <DYNARE_STATEMENT>kalman_tol 	{return token::KALMAN_TOL;}
+<DYNARE_STATEMENT>diffuse_kalman_tol 	{return token::DIFFUSE_KALMAN_TOL;}
 <DYNARE_STATEMENT>forecast 	{return token::FORECAST;}
 <DYNARE_STATEMENT>smoother 	{return token::SMOOTHER;}
 <DYNARE_STATEMENT>bayesian_irf 	{return token::BAYESIAN_IRF;}
@@ -363,16 +366,13 @@ DATE -?[0-9]+([YyAa]|[Mm]([1-9]|1[0-2])|[Qq][1-4]|[Ww]([1-9]{1}|[1-4][0-9]|5[0-2
 <DYNARE_STATEMENT>smooth {return token::SMOOTH;}
 <DYNARE_STATEMENT>stratified {return token::STRATIFIED;}
 <DYNARE_STATEMENT>filter_algorithm {return token::FILTER_ALGORITHM;}
-<DYNARE_STATEMENT>sis {return token::SIS;}
-<DYNARE_STATEMENT>apf {return token::APF;}
-<DYNARE_STATEMENT>gf {return token::GF;}
-<DYNARE_STATEMENT>gmf {return token::GMF;}
-<DYNARE_STATEMENT>cpf {return token::CPF;}
 <DYNARE_STATEMENT>proposal_approximation {return token::PROPOSAL_APPROXIMATION;}
 <DYNARE_STATEMENT>cubature {return token::CUBATURE;}
 <DYNARE_STATEMENT>unscented {return token::UNSCENTED;}
 <DYNARE_STATEMENT>montecarlo {return token::MONTECARLO;}
 <DYNARE_STATEMENT>distribution_approximation {return token::DISTRIBUTION_APPROXIMATION;}
+<DYNARE_STATEMENT>proposal_distribution {return token::PROPOSAL_DISTRIBUTION;}
+<DYNARE_STATEMENT>student_degrees_of_freedom {return token::STUDENT_DEGREES_OF_FREEDOM;}
 
 <DYNARE_STATEMENT>alpha {
   yylval->string_val = new string(yytext);
@@ -402,6 +402,10 @@ DATE -?[0-9]+([YyAa]|[Mm]([1-9]|1[0-2])|[Qq][1-4]|[Ww]([1-9]{1}|[1-4][0-9]|5[0-2
   yylval->string_val = new string(yytext);
   return token::DIRICHLET;
 }
+<DYNARE_STATEMENT>weibull {
+  yylval->string_val = new string(yytext);
+  return token::WEIBULL;
+}
 <DYNARE_STATEMENT>normal {
   yylval->string_val = new string(yytext);
   return token::NORMAL;
@@ -565,6 +569,12 @@ DATE -?[0-9]+([YyAa]|[Mm]([1-9]|1[0-2])|[Qq][1-4]|[Ww]([1-9]{1}|[1-4][0-9]|5[0-2
 <DYNARE_STATEMENT>period {return token::PERIOD;}
 <DYNARE_STATEMENT>outfile {return token::OUTFILE;}
 <DYNARE_STATEMENT>outvars {return token::OUTVARS;}
+<DYNARE_STATEMENT>huge_number {return token::HUGE_NUMBER;}
+<DYNARE_STATEMENT>dr_display_tol {return token::DR_DISPLAY_TOL;}
+<DYNARE_STATEMENT>use_tarb {return token::USE_TARB;}
+<DYNARE_STATEMENT>tarb_mode_compute {return token::TARB_MODE_COMPUTE;}
+<DYNARE_STATEMENT>tarb_new_block_probability {return token::TARB_NEW_BLOCK_PROBABILITY;}
+<DYNARE_STATEMENT>tarb_optim {return token::TARB_OPTIM;}
 
 <DYNARE_STATEMENT>[\$][^$]*[\$] {
   strtok(yytext+1, "$");
@@ -587,6 +597,7 @@ DATE -?[0-9]+([YyAa]|[Mm]([1-9]|1[0-2])|[Qq][1-4]|[Ww]([1-9]{1}|[1-4][0-9]|5[0-2
 <DYNARE_BLOCK>inv_gamma1_pdf {return token::INV_GAMMA1_PDF;}
 <DYNARE_BLOCK>inv_gamma2_pdf {return token::INV_GAMMA2_PDF;}
 <DYNARE_BLOCK>uniform_pdf {return token::UNIFORM_PDF;}
+<DYNARE_BLOCK>weibull_pdf {return token::WEIBULL_PDF;}
 <DYNARE_BLOCK>dsge_prior_weight {return token::DSGE_PRIOR_WEIGHT;}
 
 <DYNARE_BLOCK>; {return Dynare::parser::token_type (yytext[0]);}
@@ -838,6 +849,41 @@ DATE -?[0-9]+([YyAa]|[Mm]([1-9]|1[0-2])|[Qq][1-4]|[Ww]([1-9]{1}|[1-4][0-9]|5[0-2
     }
 }
 
+ /* For joint prior statement, match [symbol, symbol, ...]
+   If no match, begin native and push everything back on stack
+ */
+<INITIAL>\[([[:space:]]*[A-Za-z_][A-Za-z0-9_]*[[:space:]]*,{1}[[:space:]]*)*([[:space:]]*[A-Za-z_][A-Za-z0-9_]*[[:space:]]*){1}\] {
+  string yytextcpy = string(yytext);
+  yytextcpy.erase(remove(yytextcpy.begin(), yytextcpy.end(), '['), yytextcpy.end());
+  yytextcpy.erase(remove(yytextcpy.begin(), yytextcpy.end(), ']'), yytextcpy.end());
+  yytextcpy.erase(remove(yytextcpy.begin(), yytextcpy.end(), ' '), yytextcpy.end());
+  istringstream ss(yytextcpy);
+  string token;
+  yylval->vector_string_val = new vector<string *>;
+
+  bool dynare_statement = true;
+
+  while(getline(ss, token, ','))
+    if (driver.symbol_exists_and_is_not_modfile_local_or_external_function(token.c_str()))
+      yylval->vector_string_val->push_back(new string(token));
+    else
+      {
+        for (vector<string *>::iterator it=yylval->vector_string_val->begin();
+            it != yylval->vector_string_val->end(); it++)
+          delete *it;
+        delete yylval->vector_string_val;
+        BEGIN NATIVE;
+        yyless(0);
+        dynare_statement = false;
+        break;
+      }
+  if (dynare_statement)
+    {
+      BEGIN DYNARE_STATEMENT;
+      return token::SYMBOL_VEC;
+    }
+}
+
  /* Enter a native block */
 <INITIAL>. { BEGIN NATIVE; yyless(0); }
 
diff --git a/preprocessor/DynareMain.cc b/preprocessor/DynareMain.cc
index 7fed1e7858964a73f3421dc7d5664b2fa1288f6b..9320a4afd83e7d78286c88899264d5c9371b63f3 100644
--- a/preprocessor/DynareMain.cc
+++ b/preprocessor/DynareMain.cc
@@ -35,9 +35,10 @@
    Splitting main() in two parts was necessary because ParsingDriver.h and MacroDriver.h can't be
    included simultaneously (because of Bison limitations).
 */
-void main2(stringstream &in, string &basename, bool debug, bool clear_all, bool no_tmp_terms, bool no_log, bool no_warn, bool warn_uninit, bool console, bool nograph, bool nointeractive, 
+void main2(stringstream &in, string &basename, bool debug, bool clear_all, bool clear_global, bool no_tmp_terms, bool no_log, bool no_warn,
+           bool warn_uninit, bool console, bool nograph, bool nointeractive,
            bool parallel, const string &parallel_config_file, const string &cluster_name, bool parallel_slave_open_mode,
-           bool parallel_test, bool nostrict, FileOutputType output_mode, LanguageOutputType lang
+           bool parallel_test, bool nostrict, bool check_model_changes, FileOutputType output_mode, LanguageOutputType lang
 #if defined(_WIN32) || defined(__CYGWIN32__)
            , bool cygwin, bool msvc
 #endif
@@ -46,9 +47,9 @@ void main2(stringstream &in, string &basename, bool debug, bool clear_all, bool
 void
 usage()
 {
-  cerr << "Dynare usage: dynare mod_file [debug] [noclearall] [savemacro[=macro_file]] [onlymacro] [nolinemacro] [notmpterms] [nolog] [warn_uninit]"
+  cerr << "Dynare usage: dynare mod_file [debug] [noclearall] [onlyclearglobals] [savemacro[=macro_file]] [onlymacro] [nolinemacro] [notmpterms] [nolog] [warn_uninit]"
        << " [console] [nograph] [nointeractive] [parallel[=cluster_name]] [conffile=parallel_config_path_and_filename] [parallel_slave_open_mode] [parallel_test] "
-       << " [-D<variable>[=<value>]] [nostrict] [output=dynamic|first|second|third] [language=C|C++]"
+       << " [-D<variable>[=<value>]] [nostrict] [fast] [output=dynamic|first|second|third] [language=C|C++]"
 #if defined(_WIN32) || defined(__CYGWIN32__)
        << " [cygwin] [msvc]"
 #endif
@@ -73,6 +74,7 @@ main(int argc, char **argv)
     }
 
   bool clear_all = true;
+  bool clear_global = false;
   bool save_macro = false;
   string save_macro_file;
   bool debug = false;
@@ -95,6 +97,7 @@ main(int argc, char **argv)
   bool parallel_slave_open_mode = false;
   bool parallel_test = false;
   bool nostrict = false;
+  bool check_model_changes = false;
   map<string, string> defines;
   FileOutputType output_mode = none;
   LanguageOutputType language = matlab;
@@ -106,6 +109,11 @@ main(int argc, char **argv)
         debug = true;
       else if (!strcmp(argv[arg], "noclearall"))
         clear_all = false;
+      else if (!strcmp(argv[arg], "onlyclearglobals"))
+        {
+          clear_all = false;
+          clear_global = true;
+        }
       else if (!strcmp(argv[arg], "onlymacro"))
         only_macro = true;
       else if (strlen(argv[arg]) >= 9 && !strncmp(argv[arg], "savemacro", 9))
@@ -158,6 +166,8 @@ main(int argc, char **argv)
         parallel_test = true;
       else if (!strcmp(argv[arg], "nostrict"))
         nostrict = true;
+      else if (!strcmp(argv[arg], "fast"))
+        check_model_changes = true;
       else if (strlen(argv[arg]) >= 8 && !strncmp(argv[arg], "parallel", 8))
         {
           parallel = true;
@@ -277,8 +287,8 @@ main(int argc, char **argv)
     return EXIT_SUCCESS;
 
   // Do the rest
-  main2(macro_output, basename, debug, clear_all, no_tmp_terms, no_log, no_warn, warn_uninit, console, nograph, nointeractive, 
-        parallel, parallel_config_file, cluster_name, parallel_slave_open_mode, parallel_test, nostrict, output_mode, language
+  main2(macro_output, basename, debug, clear_all, clear_global, no_tmp_terms, no_log, no_warn, warn_uninit, console, nograph, nointeractive,
+        parallel, parallel_config_file, cluster_name, parallel_slave_open_mode, parallel_test, nostrict, check_model_changes, output_mode, language
 #if defined(_WIN32) || defined(__CYGWIN32__)
         , cygwin, msvc
 #endif
diff --git a/preprocessor/DynareMain2.cc b/preprocessor/DynareMain2.cc
index 8f82a059f81940be169ac5bc731312dc0f6f6590..fe1c6942723ccf4dd450beaa90e25c6930fbc04e 100644
--- a/preprocessor/DynareMain2.cc
+++ b/preprocessor/DynareMain2.cc
@@ -25,9 +25,9 @@
 #include "ExtendedPreprocessorTypes.hh"
 
 void
-main2(stringstream &in, string &basename, bool debug, bool clear_all, bool no_tmp_terms, bool no_log, bool no_warn, bool warn_uninit, bool console, bool nograph, bool nointeractive,
+main2(stringstream &in, string &basename, bool debug, bool clear_all, bool clear_global, bool no_tmp_terms, bool no_log, bool no_warn, bool warn_uninit, bool console, bool nograph, bool nointeractive,
       bool parallel, const string &parallel_config_file, const string &cluster_name, bool parallel_slave_open_mode,
-      bool parallel_test, bool nostrict, FileOutputType output_mode, LanguageOutputType language
+      bool parallel_test, bool nostrict, bool check_model_changes, FileOutputType output_mode, LanguageOutputType language
 #if defined(_WIN32) || defined(__CYGWIN32__)
       , bool cygwin, bool msvc
 #endif
@@ -60,11 +60,12 @@ main2(stringstream &in, string &basename, bool debug, bool clear_all, bool no_tm
   if (output_mode != none)
     mod_file->writeExternalFiles(basename, output_mode, language);
   else
-    mod_file->writeOutputFiles(basename, clear_all, no_log, no_warn, console, nograph, nointeractive, config_file
+    mod_file->writeOutputFiles(basename, clear_all, clear_global, no_log, no_warn, console, nograph,
+			       nointeractive, config_file, check_model_changes
 #if defined(_WIN32) || defined(__CYGWIN32__)
-                             , cygwin, msvc
+			       , cygwin, msvc
 #endif
-                             );
+			       );
 
   delete mod_file;
 
diff --git a/preprocessor/ExprNode.cc b/preprocessor/ExprNode.cc
index d4121b72924600e3e2663709300afab1edd0f2b0..b9c4405528ed4f596f0f159f00d71199d57e251e 100644
--- a/preprocessor/ExprNode.cc
+++ b/preprocessor/ExprNode.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2014 Dynare Team
+ * Copyright (C) 2007-2015 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -308,6 +308,12 @@ NumConstNode::writeOutput(ostream &output, ExprNodeOutputType output_type,
     output << datatree.num_constants.get(id);
 }
 
+bool
+NumConstNode::containsExternalFunction() const
+{
+  return false;
+}
+
 double
 NumConstNode::eval(const eval_context_t &eval_context) const throw (EvalException, EvalExternalFunctionException)
 {
@@ -571,6 +577,12 @@ VariableNode::collectTemporary_terms(const temporary_terms_t &temporary_terms, t
     datatree.local_variables_table[symb_id]->collectTemporary_terms(temporary_terms, temporary_terms_inuse, Curr_Block);
 }
 
+bool
+VariableNode::containsExternalFunction() const
+{
+  return false;
+}
+
 void
 VariableNode::writeOutput(ostream &output, ExprNodeOutputType output_type,
                           const temporary_terms_t &temporary_terms,
@@ -1714,6 +1726,12 @@ UnaryOpNode::collectTemporary_terms(const temporary_terms_t &temporary_terms, te
     arg->collectTemporary_terms(temporary_terms, temporary_terms_inuse, Curr_Block);
 }
 
+bool
+UnaryOpNode::containsExternalFunction() const
+{
+  return arg->containsExternalFunction();
+}
+
 void
 UnaryOpNode::writeOutput(ostream &output, ExprNodeOutputType output_type,
                          const temporary_terms_t &temporary_terms,
@@ -1851,8 +1869,20 @@ UnaryOpNode::writeOutput(ostream &output, ExprNodeOutputType output_type,
       }
       return;
     case oExpectation:
-      cerr << "UnaryOpNode::writeOutput: not implemented on oExpectation" << endl;
-      exit(EXIT_FAILURE);
+      if (!IS_LATEX(output_type))
+        {
+          cerr << "UnaryOpNode::writeOutput: not implemented on oExpectation" << endl;
+          exit(EXIT_FAILURE);
+        }
+      output << "\\mathbb{E}_{t";
+      if (expectation_information_set != 0)
+        {
+          if (expectation_information_set > 0)
+            output << "+";
+          output << expectation_information_set;
+        }
+      output << "}";
+      break;
     case oErf:
       output << "erf";
       break;
@@ -2326,7 +2356,7 @@ UnaryOpNode::substituteExpectation(subst_table_t &subst_table, vector<BinaryOpNo
       //Arriving here, we need to create an auxiliary variable for this Expectation Operator:
       //AUX_EXPECT_(LEAD/LAG)_(period)_(arg.idx) OR
       //AUX_EXPECT_(info_set_name)_(arg.idx)
-      int symb_id = datatree.symbol_table.addExpectationAuxiliaryVar(expectation_information_set, arg->idx);
+      int symb_id = datatree.symbol_table.addExpectationAuxiliaryVar(expectation_information_set, arg->idx, arg);
       expr_t newAuxE = datatree.AddVariable(symb_id, 0);
 
       if (partial_information_model && expectation_information_set == 0)
@@ -2873,6 +2903,13 @@ BinaryOpNode::collectTemporary_terms(const temporary_terms_t &temporary_terms, t
     }
 }
 
+bool
+BinaryOpNode::containsExternalFunction() const
+{
+  return arg1->containsExternalFunction()
+    || arg2->containsExternalFunction();
+}
+
 void
 BinaryOpNode::writeOutput(ostream &output, ExprNodeOutputType output_type,
                           const temporary_terms_t &temporary_terms,
@@ -3951,6 +3988,14 @@ TrinaryOpNode::collectTemporary_terms(const temporary_terms_t &temporary_terms,
     }
 }
 
+bool
+TrinaryOpNode::containsExternalFunction() const
+{
+  return arg1->containsExternalFunction()
+    || arg2->containsExternalFunction()
+    || arg3->containsExternalFunction();
+}
+
 void
 TrinaryOpNode::writeOutput(ostream &output, ExprNodeOutputType output_type,
                            const temporary_terms_t &temporary_terms,
@@ -4285,15 +4330,6 @@ AbstractExternalFunctionNode::AbstractExternalFunctionNode(DataTree &datatree_ar
 {
 }
 
-ExternalFunctionNode::ExternalFunctionNode(DataTree &datatree_arg,
-                                           int symb_id_arg,
-                                           const vector<expr_t> &arguments_arg) :
-  AbstractExternalFunctionNode(datatree_arg, symb_id_arg, arguments_arg)
-{
-  // Add myself to the external function map
-  datatree.external_function_node_map[make_pair(arguments, symb_id)] = this;
-}
-
 void
 AbstractExternalFunctionNode::prepareForDerivation()
 {
@@ -4324,20 +4360,6 @@ AbstractExternalFunctionNode::computeDerivative(int deriv_id)
   return composeDerivatives(dargs);
 }
 
-expr_t
-ExternalFunctionNode::composeDerivatives(const vector<expr_t> &dargs)
-{
-  vector<expr_t> dNodes;
-  for (int i = 0; i < (int) dargs.size(); i++)
-    dNodes.push_back(datatree.AddTimes(dargs.at(i),
-                                       datatree.AddFirstDerivExternalFunction(symb_id, arguments, i+1)));
-
-  expr_t theDeriv = datatree.Zero;
-  for (vector<expr_t>::const_iterator it = dNodes.begin(); it != dNodes.end(); it++)
-    theDeriv = datatree.AddPlus(theDeriv, *it);
-  return theDeriv;
-}
-
 expr_t
 AbstractExternalFunctionNode::getChainRuleDerivative(int deriv_id, const map<int, expr_t> &recursive_variables)
 {
@@ -4349,401 +4371,114 @@ AbstractExternalFunctionNode::getChainRuleDerivative(int deriv_id, const map<int
   return composeDerivatives(dargs);
 }
 
-void
-ExternalFunctionNode::computeTemporaryTerms(map<expr_t, int> &reference_count,
-                                            temporary_terms_t &temporary_terms,
-                                            bool is_matlab) const
-{
-  temporary_terms.insert(const_cast<ExternalFunctionNode *>(this));
-}
-
-void
-AbstractExternalFunctionNode::writeExternalFunctionArguments(ostream &output, ExprNodeOutputType output_type,
-                                                             const temporary_terms_t &temporary_terms,
-                                                             deriv_node_temp_terms_t &tef_terms) const
+unsigned int
+AbstractExternalFunctionNode::compileExternalFunctionArguments(ostream &CompileCode, unsigned int &instruction_number,
+                                                               bool lhs_rhs, const temporary_terms_t &temporary_terms,
+                                                               const map_idx_t &map_idx, bool dynamic, bool steady_dynamic,
+                                                               deriv_node_temp_terms_t &tef_terms) const
 {
   for (vector<expr_t>::const_iterator it = arguments.begin();
        it != arguments.end(); it++)
-    {
-      if (it != arguments.begin())
-        output << ",";
-
-      (*it)->writeOutput(output, output_type, temporary_terms, tef_terms);
-    }
+    (*it)->compile(CompileCode, instruction_number, lhs_rhs, temporary_terms, map_idx,
+                   dynamic, steady_dynamic, tef_terms);
+  return (arguments.size());
 }
 
 void
-AbstractExternalFunctionNode::writePrhs(ostream &output, ExprNodeOutputType output_type,
-                                        const temporary_terms_t &temporary_terms,
-                                        deriv_node_temp_terms_t &tef_terms, const string &ending) const
+AbstractExternalFunctionNode::collectDynamicVariables(SymbolType type_arg, set<pair<int, int> > &result) const
 {
-  output << "mxArray *prhs"<< ending << "[nrhs"<< ending << "];" << endl;
-  int i = 0;
   for (vector<expr_t>::const_iterator it = arguments.begin();
        it != arguments.end(); it++)
-    {
-      output << "prhs" << ending << "[" << i++ << "] = mxCreateDoubleScalar("; // All external_function arguments are scalars
-      (*it)->writeOutput(output, output_type, temporary_terms, tef_terms);
-      output << ");" << endl;
-    }
+    (*it)->collectDynamicVariables(type_arg, result);
 }
 
 void
-ExternalFunctionNode::writeOutput(ostream &output, ExprNodeOutputType output_type,
-                                  const temporary_terms_t &temporary_terms,
-                                  deriv_node_temp_terms_t &tef_terms) const
+AbstractExternalFunctionNode::collectTemporary_terms(const temporary_terms_t &temporary_terms, temporary_terms_inuse_t &temporary_terms_inuse, int Curr_Block) const
 {
-  if (output_type == oMatlabOutsideModel || output_type == oSteadyStateFile
-      || output_type == oCSteadyStateFile || IS_LATEX(output_type))
-    {
-      string name = IS_LATEX(output_type) ? datatree.symbol_table.getTeXName(symb_id)
-        : datatree.symbol_table.getName(symb_id);
-      output << name << "(";
-      writeExternalFunctionArguments(output, output_type, temporary_terms, tef_terms);
-      output << ")";
-      return;
-    }
-
-  temporary_terms_t::const_iterator it = temporary_terms.find(const_cast<ExternalFunctionNode *>(this));
+  temporary_terms_t::const_iterator it = temporary_terms.find(const_cast<AbstractExternalFunctionNode *>(this));
   if (it != temporary_terms.end())
+    temporary_terms_inuse.insert(idx);
+  else
     {
-      if (output_type == oMatlabDynamicModelSparse)
-        output << "T" << idx << "(it_)";
-      else
-        output << "T" << idx;
-      return;
+      for (vector<expr_t>::const_iterator it = arguments.begin();
+           it != arguments.end(); it++)
+        (*it)->collectTemporary_terms(temporary_terms, temporary_terms_inuse, Curr_Block);
     }
+}
 
-  if (IS_C(output_type))
-    output << "*";
-  output << "TEF_" << getIndxInTefTerms(symb_id, tef_terms);
+double
+AbstractExternalFunctionNode::eval(const eval_context_t &eval_context) const throw (EvalException, EvalExternalFunctionException)
+{
+  throw EvalExternalFunctionException();
 }
 
-unsigned int
-AbstractExternalFunctionNode::compileExternalFunctionArguments(ostream &CompileCode, unsigned int &instruction_number,
-                                                               bool lhs_rhs, const temporary_terms_t &temporary_terms,
-                                                               const map_idx_t &map_idx, bool dynamic, bool steady_dynamic,
-                                                               deriv_node_temp_terms_t &tef_terms) const
+int
+AbstractExternalFunctionNode::maxEndoLead() const
 {
+  int val = 0;
   for (vector<expr_t>::const_iterator it = arguments.begin();
        it != arguments.end(); it++)
-    (*it)->compile(CompileCode, instruction_number, lhs_rhs, temporary_terms, map_idx,
-                   dynamic, steady_dynamic, tef_terms);
-  return (arguments.size());
+    val = max(val, (*it)->maxEndoLead());
+  return val;
 }
 
-void
-ExternalFunctionNode::compile(ostream &CompileCode, unsigned int &instruction_number,
-                              bool lhs_rhs, const temporary_terms_t &temporary_terms,
-                              const map_idx_t &map_idx, bool dynamic, bool steady_dynamic,
-                              deriv_node_temp_terms_t &tef_terms) const
+int
+AbstractExternalFunctionNode::maxExoLead() const
 {
-  temporary_terms_t::const_iterator it = temporary_terms.find(const_cast<ExternalFunctionNode *>(this));
-  if (it != temporary_terms.end())
-    {
-      if (dynamic)
-        {
-          map_idx_t::const_iterator ii = map_idx.find(idx);
-          FLDT_ fldt(ii->second);
-          fldt.write(CompileCode, instruction_number);
-        }
-      else
-        {
-          map_idx_t::const_iterator ii = map_idx.find(idx);
-          FLDST_ fldst(ii->second);
-          fldst.write(CompileCode, instruction_number);
-        }
-      return;
-    }
-
-  if (!lhs_rhs)
-    {
-      FLDTEF_ fldtef(getIndxInTefTerms(symb_id, tef_terms));
-      fldtef.write(CompileCode, instruction_number);
-    }
-  else
-    {
-      FSTPTEF_ fstptef(getIndxInTefTerms(symb_id, tef_terms));
-      fstptef.write(CompileCode, instruction_number);
-    }
+  int val = 0;
+  for (vector<expr_t>::const_iterator it = arguments.begin();
+       it != arguments.end(); it++)
+    val = max(val, (*it)->maxExoLead());
+  return val;
 }
 
-void
-ExternalFunctionNode::writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type,
-                                                  const temporary_terms_t &temporary_terms,
-                                                  deriv_node_temp_terms_t &tef_terms) const
+int
+AbstractExternalFunctionNode::maxEndoLag() const
 {
-  int first_deriv_symb_id = datatree.external_functions_table.getFirstDerivSymbID(symb_id);
-  assert(first_deriv_symb_id != eExtFunSetButNoNameProvided);
+  int val = 0;
+  for (vector<expr_t>::const_iterator it = arguments.begin();
+       it != arguments.end(); it++)
+    val = max(val, (*it)->maxEndoLag());
+  return val;
+}
 
+int
+AbstractExternalFunctionNode::maxExoLag() const
+{
+  int val = 0;
   for (vector<expr_t>::const_iterator it = arguments.begin();
        it != arguments.end(); it++)
-    (*it)->writeExternalFunctionOutput(output, output_type, temporary_terms, tef_terms);
+    val = max(val, (*it)->maxExoLag());
+  return val;
+}
 
-  if (!alreadyWrittenAsTefTerm(symb_id, tef_terms))
-    {
-      tef_terms[make_pair(symb_id, arguments)] = (int) tef_terms.size();
-      int indx = getIndxInTefTerms(symb_id, tef_terms);
-      int second_deriv_symb_id = datatree.external_functions_table.getSecondDerivSymbID(symb_id);
-      assert(second_deriv_symb_id != eExtFunSetButNoNameProvided);
+int
+AbstractExternalFunctionNode::maxLead() const
+{
+  int val = 0;
+  for (vector<expr_t>::const_iterator it = arguments.begin();
+       it != arguments.end(); it++)
+    val = max(val, (*it)->maxLead());
+  return val;
+}
 
-      if (IS_C(output_type))
-        {
-          stringstream ending;
-          ending << "_tef_" << getIndxInTefTerms(symb_id, tef_terms);
-          if (symb_id == first_deriv_symb_id
-              && symb_id == second_deriv_symb_id)
-            output << "int nlhs" << ending.str() << " = 3;" << endl
-                   << "double *TEF_" << indx << ", "
-                   << "*TEFD_" << indx << ", "
-                   << "*TEFDD_" << indx << ";" << endl;
-          else if (symb_id == first_deriv_symb_id)
-            output << "int nlhs" << ending.str() << " = 2;" << endl
-                   << "double *TEF_" << indx << ", "
-                   << "*TEFD_" << indx << "; " << endl;
-          else
-            output << "int nlhs" << ending.str() << " = 1;" << endl
-                   << "double *TEF_" << indx << ";" << endl;
+expr_t
+AbstractExternalFunctionNode::decreaseLeadsLags(int n) const
+{
+  vector<expr_t> arguments_subst;
+  for (vector<expr_t>::const_iterator it = arguments.begin(); it != arguments.end(); it++)
+    arguments_subst.push_back((*it)->decreaseLeadsLags(n));
+  return buildSimilarExternalFunctionNode(arguments_subst, datatree);
+}
 
-          output << "mxArray *plhs" << ending.str()<< "[nlhs"<< ending.str() << "];" << endl;
-          output << "int nrhs" << ending.str()<< " = " << arguments.size() << ";" << endl;
-          writePrhs(output, output_type, temporary_terms, tef_terms, ending.str());
-
-          output << "mexCallMATLAB("
-                 << "nlhs" << ending.str() << ", "
-                 << "plhs" << ending.str() << ", "
-                 << "nrhs" << ending.str() << ", "
-                 << "prhs" << ending.str() << ", \""
-                 << datatree.symbol_table.getName(symb_id) << "\");" << endl;
-
-          if (symb_id == first_deriv_symb_id
-              && symb_id == second_deriv_symb_id)
-            output << "TEF_" << indx << " = mxGetPr(plhs" << ending.str() << "[0]);" << endl
-                   << "TEFD_" << indx << " = mxGetPr(plhs" << ending.str() << "[1]);" << endl
-                   << "TEFDD_" << indx << " = mxGetPr(plhs" << ending.str() << "[2]);" << endl
-                   << "int TEFDD_" << indx << "_nrows = (int)mxGetM(plhs" << ending.str()<< "[2]);" << endl;
-          else if (symb_id == first_deriv_symb_id)
-            output << "TEF_" << indx << " = mxGetPr(plhs" << ending.str() << "[0]);" << endl
-                   << "TEFD_" << indx << " = mxGetPr(plhs" << ending.str() << "[1]);" << endl;
-          else
-            output << "TEF_" << indx << " = mxGetPr(plhs" << ending.str() << "[0]);" << endl;
-        }
-      else
-        {
-          if (symb_id == first_deriv_symb_id
-              && symb_id == second_deriv_symb_id)
-            output << "[TEF_" << indx << " TEFD_"<< indx << " TEFDD_"<< indx << "] = ";
-          else if (symb_id == first_deriv_symb_id)
-            output << "[TEF_" << indx << " TEFD_"<< indx << "] = ";
-          else
-            output << "TEF_" << indx << " = ";
-
-          output << datatree.symbol_table.getName(symb_id) << "(";
-          writeExternalFunctionArguments(output, output_type, temporary_terms, tef_terms);
-          output << ");" << endl;
-        }
-    }
-}
-
-void
-ExternalFunctionNode::compileExternalFunctionOutput(ostream &CompileCode, unsigned int &instruction_number,
-                                                    bool lhs_rhs, const temporary_terms_t &temporary_terms,
-                                                    const map_idx_t &map_idx, bool dynamic, bool steady_dynamic,
-                                                    deriv_node_temp_terms_t &tef_terms) const
-{
-  int first_deriv_symb_id = datatree.external_functions_table.getFirstDerivSymbID(symb_id);
-  assert(first_deriv_symb_id != eExtFunSetButNoNameProvided);
-
-  for (vector<expr_t>::const_iterator it = arguments.begin();
-       it != arguments.end(); it++)
-    (*it)->compileExternalFunctionOutput(CompileCode, instruction_number, lhs_rhs, temporary_terms,
-                                         map_idx, dynamic, steady_dynamic, tef_terms);
-
-  if (!alreadyWrittenAsTefTerm(symb_id, tef_terms))
-    {
-      tef_terms[make_pair(symb_id, arguments)] = (int) tef_terms.size();
-      int indx = getIndxInTefTerms(symb_id, tef_terms);
-      int second_deriv_symb_id = datatree.external_functions_table.getSecondDerivSymbID(symb_id);
-      assert(second_deriv_symb_id != eExtFunSetButNoNameProvided);
-
-      unsigned int nb_output_arguments = 0;
-      if (symb_id == first_deriv_symb_id
-          && symb_id == second_deriv_symb_id)
-        nb_output_arguments = 3;
-      else if (symb_id == first_deriv_symb_id)
-        nb_output_arguments = 2;
-      else
-        nb_output_arguments = 1;
-      unsigned int nb_input_arguments = compileExternalFunctionArguments(CompileCode, instruction_number, lhs_rhs, temporary_terms,
-                                                                         map_idx, dynamic, steady_dynamic, tef_terms);
-
-      FCALL_ fcall(nb_output_arguments, nb_input_arguments, datatree.symbol_table.getName(symb_id), indx);
-      switch (nb_output_arguments)
-        {
-        case 1:
-          fcall.set_function_type(ExternalFunctionWithoutDerivative);
-          break;
-        case 2:
-          fcall.set_function_type(ExternalFunctionWithFirstDerivative);
-          break;
-        case 3:
-          fcall.set_function_type(ExternalFunctionWithFirstandSecondDerivative);
-          break;
-        }
-      fcall.write(CompileCode, instruction_number);
-      FSTPTEF_ fstptef(indx);
-      fstptef.write(CompileCode, instruction_number);
-    }
-}
-
-void
-ExternalFunctionNode::computeTemporaryTerms(map<expr_t, int> &reference_count,
-                                            temporary_terms_t &temporary_terms,
-                                            map<expr_t, pair<int, int> > &first_occurence,
-                                            int Curr_block,
-                                            vector< vector<temporary_terms_t> > &v_temporary_terms,
-                                            int equation) const
-{
-  expr_t this2 = const_cast<ExternalFunctionNode *>(this);
-  temporary_terms.insert(this2);
-  first_occurence[this2] = make_pair(Curr_block, equation);
-  v_temporary_terms[Curr_block][equation].insert(this2);
-}
-
-void
-AbstractExternalFunctionNode::collectDynamicVariables(SymbolType type_arg, set<pair<int, int> > &result) const
-{
-  for (vector<expr_t>::const_iterator it = arguments.begin();
-       it != arguments.end(); it++)
-    (*it)->collectDynamicVariables(type_arg, result);
-}
-
-void
-AbstractExternalFunctionNode::collectTemporary_terms(const temporary_terms_t &temporary_terms, temporary_terms_inuse_t &temporary_terms_inuse, int Curr_Block) const
-{
-  temporary_terms_t::const_iterator it = temporary_terms.find(const_cast<AbstractExternalFunctionNode *>(this));
-  if (it != temporary_terms.end())
-    temporary_terms_inuse.insert(idx);
-  else
-    {
-      for (vector<expr_t>::const_iterator it = arguments.begin();
-           it != arguments.end(); it++)
-        (*it)->collectTemporary_terms(temporary_terms, temporary_terms_inuse, Curr_Block);
-    }
-}
-
-double
-AbstractExternalFunctionNode::eval(const eval_context_t &eval_context) const throw (EvalException, EvalExternalFunctionException)
-{
-  throw EvalExternalFunctionException();
-}
-
-pair<int, expr_t>
-AbstractExternalFunctionNode::normalizeEquation(int var_endo, vector<pair<int, pair<expr_t, expr_t> > >  &List_of_Op_RHS) const
-{
-  vector<pair<bool, expr_t> > V_arguments;
-  vector<expr_t> V_expr_t;
-  bool present = false;
-  for (vector<expr_t>::const_iterator it = arguments.begin();
-       it != arguments.end(); it++)
-    {
-      V_arguments.push_back((*it)->normalizeEquation(var_endo, List_of_Op_RHS));
-      present = present || V_arguments[V_arguments.size()-1].first;
-      V_expr_t.push_back(V_arguments[V_arguments.size()-1].second);
-    }
-  if (!present)
-    return (make_pair(0, datatree.AddExternalFunction(symb_id, V_expr_t)));
-  else
-    return (make_pair(1, (expr_t) NULL));
-}
-
-expr_t
-ExternalFunctionNode::toStatic(DataTree &static_datatree) const
-{
-  vector<expr_t> static_arguments;
-  for (vector<expr_t>::const_iterator it = arguments.begin();
-       it != arguments.end(); it++)
-    static_arguments.push_back((*it)->toStatic(static_datatree));
-  return static_datatree.AddExternalFunction(symb_id, static_arguments);
-}
-
-expr_t
-ExternalFunctionNode::cloneDynamic(DataTree &dynamic_datatree) const
-{
-  vector<expr_t> dynamic_arguments;
-  for (vector<expr_t>::const_iterator it = arguments.begin();
-       it != arguments.end(); it++)
-    dynamic_arguments.push_back((*it)->cloneDynamic(dynamic_datatree));
-  return dynamic_datatree.AddExternalFunction(symb_id, dynamic_arguments);
-}
-
-int
-AbstractExternalFunctionNode::maxEndoLead() const
-{
-  int val = 0;
-  for (vector<expr_t>::const_iterator it = arguments.begin();
-       it != arguments.end(); it++)
-    val = max(val, (*it)->maxEndoLead());
-  return val;
-}
-
-int
-AbstractExternalFunctionNode::maxExoLead() const
-{
-  int val = 0;
-  for (vector<expr_t>::const_iterator it = arguments.begin();
-       it != arguments.end(); it++)
-    val = max(val, (*it)->maxExoLead());
-  return val;
-}
-
-int
-AbstractExternalFunctionNode::maxEndoLag() const
-{
-  int val = 0;
-  for (vector<expr_t>::const_iterator it = arguments.begin();
-       it != arguments.end(); it++)
-    val = max(val, (*it)->maxEndoLag());
-  return val;
-}
-
-int
-AbstractExternalFunctionNode::maxExoLag() const
-{
-  int val = 0;
-  for (vector<expr_t>::const_iterator it = arguments.begin();
-       it != arguments.end(); it++)
-    val = max(val, (*it)->maxExoLag());
-  return val;
-}
-
-int
-AbstractExternalFunctionNode::maxLead() const
-{
-  int val = 0;
-  for (vector<expr_t>::const_iterator it = arguments.begin();
-       it != arguments.end(); it++)
-    val = max(val, (*it)->maxLead());
-  return val;
-}
-
-expr_t
-AbstractExternalFunctionNode::decreaseLeadsLags(int n) const
-{
-  vector<expr_t> arguments_subst;
-  for (vector<expr_t>::const_iterator it = arguments.begin(); it != arguments.end(); it++)
-    arguments_subst.push_back((*it)->decreaseLeadsLags(n));
-  return buildSimilarExternalFunctionNode(arguments_subst, datatree);
-}
-
-expr_t
-AbstractExternalFunctionNode::decreaseLeadsLagsPredeterminedVariables() const
-{
-  vector<expr_t> arguments_subst;
-  for (vector<expr_t>::const_iterator it = arguments.begin(); it != arguments.end(); it++)
-    arguments_subst.push_back((*it)->decreaseLeadsLagsPredeterminedVariables());
-  return buildSimilarExternalFunctionNode(arguments_subst, datatree);
-}
+expr_t
+AbstractExternalFunctionNode::decreaseLeadsLagsPredeterminedVariables() const
+{
+  vector<expr_t> arguments_subst;
+  for (vector<expr_t>::const_iterator it = arguments.begin(); it != arguments.end(); it++)
+    arguments_subst.push_back((*it)->decreaseLeadsLagsPredeterminedVariables());
+  return buildSimilarExternalFunctionNode(arguments_subst, datatree);
+}
 
 expr_t
 AbstractExternalFunctionNode::substituteEndoLeadGreaterThanTwo(subst_table_t &subst_table, vector<BinaryOpNode *> &neweqs, bool deterministic_model) const
@@ -4799,12 +4534,6 @@ AbstractExternalFunctionNode::differentiateForwardVars(const vector<string> &sub
   return buildSimilarExternalFunctionNode(arguments_subst, datatree);
 }
 
-expr_t
-ExternalFunctionNode::buildSimilarExternalFunctionNode(vector<expr_t> &alt_args, DataTree &alt_datatree) const
-{
-  return alt_datatree.AddExternalFunction(symb_id, alt_args);
-}
-
 bool
 AbstractExternalFunctionNode::alreadyWrittenAsTefTerm(int the_symb_id, deriv_node_temp_terms_t &tef_terms) const
 {
@@ -4877,10 +4606,331 @@ AbstractExternalFunctionNode::isInStaticForm() const
   for (vector<expr_t>::const_iterator it = arguments.begin(); it != arguments.end(); ++it)
     if (!(*it)->isInStaticForm())
       return false;
-  
   return true;
 }
 
+pair<int, expr_t>
+AbstractExternalFunctionNode::normalizeEquation(int var_endo, vector<pair<int, pair<expr_t, expr_t> > >  &List_of_Op_RHS) const
+{
+  vector<pair<bool, expr_t> > V_arguments;
+  vector<expr_t> V_expr_t;
+  bool present = false;
+  for (vector<expr_t>::const_iterator it = arguments.begin();
+       it != arguments.end(); it++)
+    {
+      V_arguments.push_back((*it)->normalizeEquation(var_endo, List_of_Op_RHS));
+      present = present || V_arguments[V_arguments.size()-1].first;
+      V_expr_t.push_back(V_arguments[V_arguments.size()-1].second);
+    }
+  if (!present)
+    return (make_pair(0, datatree.AddExternalFunction(symb_id, V_expr_t)));
+  else
+    return (make_pair(1, (expr_t) NULL));
+}
+
+void
+AbstractExternalFunctionNode::writeExternalFunctionArguments(ostream &output, ExprNodeOutputType output_type,
+                                                             const temporary_terms_t &temporary_terms,
+                                                             deriv_node_temp_terms_t &tef_terms) const
+{
+  for (vector<expr_t>::const_iterator it = arguments.begin();
+       it != arguments.end(); it++)
+    {
+      if (it != arguments.begin())
+        output << ",";
+
+      (*it)->writeOutput(output, output_type, temporary_terms, tef_terms);
+    }
+}
+
+void
+AbstractExternalFunctionNode::writePrhs(ostream &output, ExprNodeOutputType output_type,
+                                        const temporary_terms_t &temporary_terms,
+                                        deriv_node_temp_terms_t &tef_terms, const string &ending) const
+{
+  output << "mxArray *prhs"<< ending << "[nrhs"<< ending << "];" << endl;
+  int i = 0;
+  for (vector<expr_t>::const_iterator it = arguments.begin();
+       it != arguments.end(); it++)
+    {
+      output << "prhs" << ending << "[" << i++ << "] = mxCreateDoubleScalar("; // All external_function arguments are scalars
+      (*it)->writeOutput(output, output_type, temporary_terms, tef_terms);
+      output << ");" << endl;
+    }
+}
+
+bool
+AbstractExternalFunctionNode::containsExternalFunction() const
+{
+  return true;
+}
+
+ExternalFunctionNode::ExternalFunctionNode(DataTree &datatree_arg,
+                                           int symb_id_arg,
+                                           const vector<expr_t> &arguments_arg) :
+  AbstractExternalFunctionNode(datatree_arg, symb_id_arg, arguments_arg)
+{
+  // Add myself to the external function map
+  datatree.external_function_node_map[make_pair(arguments, symb_id)] = this;
+}
+
+expr_t
+ExternalFunctionNode::composeDerivatives(const vector<expr_t> &dargs)
+{
+  vector<expr_t> dNodes;
+  for (int i = 0; i < (int) dargs.size(); i++)
+    dNodes.push_back(datatree.AddTimes(dargs.at(i),
+                                       datatree.AddFirstDerivExternalFunction(symb_id, arguments, i+1)));
+
+  expr_t theDeriv = datatree.Zero;
+  for (vector<expr_t>::const_iterator it = dNodes.begin(); it != dNodes.end(); it++)
+    theDeriv = datatree.AddPlus(theDeriv, *it);
+  return theDeriv;
+}
+
+void
+ExternalFunctionNode::computeTemporaryTerms(map<expr_t, int> &reference_count,
+                                            temporary_terms_t &temporary_terms,
+                                            bool is_matlab) const
+{
+  temporary_terms.insert(const_cast<ExternalFunctionNode *>(this));
+}
+
+void
+ExternalFunctionNode::computeTemporaryTerms(map<expr_t, int> &reference_count,
+                                            temporary_terms_t &temporary_terms,
+                                            map<expr_t, pair<int, int> > &first_occurence,
+                                            int Curr_block,
+                                            vector< vector<temporary_terms_t> > &v_temporary_terms,
+                                            int equation) const
+{
+  expr_t this2 = const_cast<ExternalFunctionNode *>(this);
+  temporary_terms.insert(this2);
+  first_occurence[this2] = make_pair(Curr_block, equation);
+  v_temporary_terms[Curr_block][equation].insert(this2);
+}
+
+void
+ExternalFunctionNode::compile(ostream &CompileCode, unsigned int &instruction_number,
+                              bool lhs_rhs, const temporary_terms_t &temporary_terms,
+                              const map_idx_t &map_idx, bool dynamic, bool steady_dynamic,
+                              deriv_node_temp_terms_t &tef_terms) const
+{
+  temporary_terms_t::const_iterator it = temporary_terms.find(const_cast<ExternalFunctionNode *>(this));
+  if (it != temporary_terms.end())
+    {
+      if (dynamic)
+        {
+          map_idx_t::const_iterator ii = map_idx.find(idx);
+          FLDT_ fldt(ii->second);
+          fldt.write(CompileCode, instruction_number);
+        }
+      else
+        {
+          map_idx_t::const_iterator ii = map_idx.find(idx);
+          FLDST_ fldst(ii->second);
+          fldst.write(CompileCode, instruction_number);
+        }
+      return;
+    }
+
+  if (!lhs_rhs)
+    {
+      FLDTEF_ fldtef(getIndxInTefTerms(symb_id, tef_terms));
+      fldtef.write(CompileCode, instruction_number);
+    }
+  else
+    {
+      FSTPTEF_ fstptef(getIndxInTefTerms(symb_id, tef_terms));
+      fstptef.write(CompileCode, instruction_number);
+    }
+}
+
+void
+ExternalFunctionNode::compileExternalFunctionOutput(ostream &CompileCode, unsigned int &instruction_number,
+                                                    bool lhs_rhs, const temporary_terms_t &temporary_terms,
+                                                    const map_idx_t &map_idx, bool dynamic, bool steady_dynamic,
+                                                    deriv_node_temp_terms_t &tef_terms) const
+{
+  int first_deriv_symb_id = datatree.external_functions_table.getFirstDerivSymbID(symb_id);
+  assert(first_deriv_symb_id != eExtFunSetButNoNameProvided);
+
+  for (vector<expr_t>::const_iterator it = arguments.begin();
+       it != arguments.end(); it++)
+    (*it)->compileExternalFunctionOutput(CompileCode, instruction_number, lhs_rhs, temporary_terms,
+                                         map_idx, dynamic, steady_dynamic, tef_terms);
+
+  if (!alreadyWrittenAsTefTerm(symb_id, tef_terms))
+    {
+      tef_terms[make_pair(symb_id, arguments)] = (int) tef_terms.size();
+      int indx = getIndxInTefTerms(symb_id, tef_terms);
+      int second_deriv_symb_id = datatree.external_functions_table.getSecondDerivSymbID(symb_id);
+      assert(second_deriv_symb_id != eExtFunSetButNoNameProvided);
+
+      unsigned int nb_output_arguments = 0;
+      if (symb_id == first_deriv_symb_id
+          && symb_id == second_deriv_symb_id)
+        nb_output_arguments = 3;
+      else if (symb_id == first_deriv_symb_id)
+        nb_output_arguments = 2;
+      else
+        nb_output_arguments = 1;
+      unsigned int nb_input_arguments = compileExternalFunctionArguments(CompileCode, instruction_number, lhs_rhs, temporary_terms,
+                                                                         map_idx, dynamic, steady_dynamic, tef_terms);
+
+      FCALL_ fcall(nb_output_arguments, nb_input_arguments, datatree.symbol_table.getName(symb_id), indx);
+      switch (nb_output_arguments)
+        {
+        case 1:
+          fcall.set_function_type(ExternalFunctionWithoutDerivative);
+          break;
+        case 2:
+          fcall.set_function_type(ExternalFunctionWithFirstDerivative);
+          break;
+        case 3:
+          fcall.set_function_type(ExternalFunctionWithFirstandSecondDerivative);
+          break;
+        }
+      fcall.write(CompileCode, instruction_number);
+      FSTPTEF_ fstptef(indx);
+      fstptef.write(CompileCode, instruction_number);
+    }
+}
+
+void
+ExternalFunctionNode::writeOutput(ostream &output, ExprNodeOutputType output_type,
+                                  const temporary_terms_t &temporary_terms,
+                                  deriv_node_temp_terms_t &tef_terms) const
+{
+  if (output_type == oMatlabOutsideModel || output_type == oSteadyStateFile
+      || output_type == oCSteadyStateFile || IS_LATEX(output_type))
+    {
+      string name = IS_LATEX(output_type) ? datatree.symbol_table.getTeXName(symb_id)
+        : datatree.symbol_table.getName(symb_id);
+      output << name << "(";
+      writeExternalFunctionArguments(output, output_type, temporary_terms, tef_terms);
+      output << ")";
+      return;
+    }
+
+  temporary_terms_t::const_iterator it = temporary_terms.find(const_cast<ExternalFunctionNode *>(this));
+  if (it != temporary_terms.end())
+    {
+      if (output_type == oMatlabDynamicModelSparse)
+        output << "T" << idx << "(it_)";
+      else
+        output << "T" << idx;
+      return;
+    }
+
+  if (IS_C(output_type))
+    output << "*";
+  output << "TEF_" << getIndxInTefTerms(symb_id, tef_terms);
+}
+
+void
+ExternalFunctionNode::writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type,
+                                                  const temporary_terms_t &temporary_terms,
+                                                  deriv_node_temp_terms_t &tef_terms) const
+{
+  int first_deriv_symb_id = datatree.external_functions_table.getFirstDerivSymbID(symb_id);
+  assert(first_deriv_symb_id != eExtFunSetButNoNameProvided);
+
+  for (vector<expr_t>::const_iterator it = arguments.begin();
+       it != arguments.end(); it++)
+    (*it)->writeExternalFunctionOutput(output, output_type, temporary_terms, tef_terms);
+
+  if (!alreadyWrittenAsTefTerm(symb_id, tef_terms))
+    {
+      tef_terms[make_pair(symb_id, arguments)] = (int) tef_terms.size();
+      int indx = getIndxInTefTerms(symb_id, tef_terms);
+      int second_deriv_symb_id = datatree.external_functions_table.getSecondDerivSymbID(symb_id);
+      assert(second_deriv_symb_id != eExtFunSetButNoNameProvided);
+
+      if (IS_C(output_type))
+        {
+          stringstream ending;
+          ending << "_tef_" << getIndxInTefTerms(symb_id, tef_terms);
+          if (symb_id == first_deriv_symb_id
+              && symb_id == second_deriv_symb_id)
+            output << "int nlhs" << ending.str() << " = 3;" << endl
+                   << "double *TEF_" << indx << ", "
+                   << "*TEFD_" << indx << ", "
+                   << "*TEFDD_" << indx << ";" << endl;
+          else if (symb_id == first_deriv_symb_id)
+            output << "int nlhs" << ending.str() << " = 2;" << endl
+                   << "double *TEF_" << indx << ", "
+                   << "*TEFD_" << indx << "; " << endl;
+          else
+            output << "int nlhs" << ending.str() << " = 1;" << endl
+                   << "double *TEF_" << indx << ";" << endl;
+
+          output << "mxArray *plhs" << ending.str()<< "[nlhs"<< ending.str() << "];" << endl;
+          output << "int nrhs" << ending.str()<< " = " << arguments.size() << ";" << endl;
+          writePrhs(output, output_type, temporary_terms, tef_terms, ending.str());
+
+          output << "mexCallMATLAB("
+                 << "nlhs" << ending.str() << ", "
+                 << "plhs" << ending.str() << ", "
+                 << "nrhs" << ending.str() << ", "
+                 << "prhs" << ending.str() << ", \""
+                 << datatree.symbol_table.getName(symb_id) << "\");" << endl;
+
+          if (symb_id == first_deriv_symb_id
+              && symb_id == second_deriv_symb_id)
+            output << "TEF_" << indx << " = mxGetPr(plhs" << ending.str() << "[0]);" << endl
+                   << "TEFD_" << indx << " = mxGetPr(plhs" << ending.str() << "[1]);" << endl
+                   << "TEFDD_" << indx << " = mxGetPr(plhs" << ending.str() << "[2]);" << endl
+                   << "int TEFDD_" << indx << "_nrows = (int)mxGetM(plhs" << ending.str()<< "[2]);" << endl;
+          else if (symb_id == first_deriv_symb_id)
+            output << "TEF_" << indx << " = mxGetPr(plhs" << ending.str() << "[0]);" << endl
+                   << "TEFD_" << indx << " = mxGetPr(plhs" << ending.str() << "[1]);" << endl;
+          else
+            output << "TEF_" << indx << " = mxGetPr(plhs" << ending.str() << "[0]);" << endl;
+        }
+      else
+        {
+          if (symb_id == first_deriv_symb_id
+              && symb_id == second_deriv_symb_id)
+            output << "[TEF_" << indx << " TEFD_"<< indx << " TEFDD_"<< indx << "] = ";
+          else if (symb_id == first_deriv_symb_id)
+            output << "[TEF_" << indx << " TEFD_"<< indx << "] = ";
+          else
+            output << "TEF_" << indx << " = ";
+
+          output << datatree.symbol_table.getName(symb_id) << "(";
+          writeExternalFunctionArguments(output, output_type, temporary_terms, tef_terms);
+          output << ");" << endl;
+        }
+    }
+}
+
+expr_t
+ExternalFunctionNode::toStatic(DataTree &static_datatree) const
+{
+  vector<expr_t> static_arguments;
+  for (vector<expr_t>::const_iterator it = arguments.begin();
+       it != arguments.end(); it++)
+    static_arguments.push_back((*it)->toStatic(static_datatree));
+  return static_datatree.AddExternalFunction(symb_id, static_arguments);
+}
+
+expr_t
+ExternalFunctionNode::cloneDynamic(DataTree &dynamic_datatree) const
+{
+  vector<expr_t> dynamic_arguments;
+  for (vector<expr_t>::const_iterator it = arguments.begin();
+       it != arguments.end(); it++)
+    dynamic_arguments.push_back((*it)->cloneDynamic(dynamic_datatree));
+  return dynamic_datatree.AddExternalFunction(symb_id, dynamic_arguments);
+}
+
+expr_t
+ExternalFunctionNode::buildSimilarExternalFunctionNode(vector<expr_t> &alt_args, DataTree &alt_datatree) const
+{
+  return alt_datatree.AddExternalFunction(symb_id, alt_args);
+}
+
 FirstDerivExternalFunctionNode::FirstDerivExternalFunctionNode(DataTree &datatree_arg,
                                                                int top_level_symb_id_arg,
                                                                const vector<expr_t> &arguments_arg,
diff --git a/preprocessor/ExprNode.hh b/preprocessor/ExprNode.hh
index b008333cdfa186e0858971a6daf59e24518593c6..0500ff6d501edf45b2bf713884520c38fffc8f6d 100644
--- a/preprocessor/ExprNode.hh
+++ b/preprocessor/ExprNode.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2014 Dynare Team
+ * Copyright (C) 2007-2015 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -187,6 +187,9 @@ public:
   */
   virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const = 0;
 
+  //! returns true if the expr node contains an external function
+  virtual bool containsExternalFunction() const = 0;
+
   //! Writes output of node (with no temporary terms and with "outside model" output type)
   void writeOutput(ostream &output) const;
 
@@ -441,6 +444,7 @@ public:
   };
   virtual void prepareForDerivation();
   virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const;
+  virtual bool containsExternalFunction() const;
   virtual void collectDynamicVariables(SymbolType type_arg, set<pair<int, int> > &result) const;
   virtual void collectTemporary_terms(const temporary_terms_t &temporary_terms, temporary_terms_inuse_t &temporary_terms_inuse, int Curr_Block) const;
   virtual double eval(const eval_context_t &eval_context) const throw (EvalException, EvalExternalFunctionException);
@@ -486,6 +490,7 @@ public:
   VariableNode(DataTree &datatree_arg, int symb_id_arg, int lag_arg);
   virtual void prepareForDerivation();
   virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const;
+  virtual bool containsExternalFunction() const;
   virtual void collectDynamicVariables(SymbolType type_arg, set<pair<int, int> > &result) const;
   virtual void computeTemporaryTerms(map<expr_t, int> &reference_count,
                                      temporary_terms_t &temporary_terms,
@@ -552,6 +557,7 @@ public:
   virtual void prepareForDerivation();
   virtual void computeTemporaryTerms(map<expr_t, int> &reference_count, temporary_terms_t &temporary_terms, bool is_matlab) const;
   virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const;
+  virtual bool containsExternalFunction() const;
   virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type,
                                            const temporary_terms_t &temporary_terms,
                                            deriv_node_temp_terms_t &tef_terms) const;
@@ -630,6 +636,7 @@ public:
   virtual int precedence(ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms) const;
   virtual void computeTemporaryTerms(map<expr_t, int> &reference_count, temporary_terms_t &temporary_terms, bool is_matlab) const;
   virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const;
+  virtual bool containsExternalFunction() const;
   virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type,
                                            const temporary_terms_t &temporary_terms,
                                            deriv_node_temp_terms_t &tef_terms) const;
@@ -724,6 +731,7 @@ public:
   virtual int precedence(ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms) const;
   virtual void computeTemporaryTerms(map<expr_t, int> &reference_count, temporary_terms_t &temporary_terms, bool is_matlab) const;
   virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const;
+  virtual bool containsExternalFunction() const;
   virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type,
                                            const temporary_terms_t &temporary_terms,
                                            deriv_node_temp_terms_t &tef_terms) const;
@@ -795,6 +803,7 @@ public:
   virtual void prepareForDerivation();
   virtual void computeTemporaryTerms(map<expr_t, int> &reference_count, temporary_terms_t &temporary_terms, bool is_matlab) const = 0;
   virtual void writeOutput(ostream &output, ExprNodeOutputType output_type, const temporary_terms_t &temporary_terms, deriv_node_temp_terms_t &tef_terms) const = 0;
+  virtual bool containsExternalFunction() const;
   virtual void writeExternalFunctionOutput(ostream &output, ExprNodeOutputType output_type,
                                            const temporary_terms_t &temporary_terms,
                                            deriv_node_temp_terms_t &tef_terms) const = 0;
diff --git a/preprocessor/Makefile.am b/preprocessor/Makefile.am
index aea2e45a7f1c3f346eea7fd98e7d4a76c306747a..4ea6bf6f0fb06a4f964502fc7fc7a5bd6631f103 100644
--- a/preprocessor/Makefile.am
+++ b/preprocessor/Makefile.am
@@ -68,8 +68,14 @@ DynareFlex.cc FlexLexer.h: DynareFlex.ll
 DynareBison.cc DynareBison.hh location.hh stack.hh position.hh: DynareBison.yy
 	$(YACC) -o DynareBison.cc DynareBison.yy
 
-all-local:
-	cd ../matlab && $(LN_S) -f $(abs_srcdir)/$(PROGRAMS) $(PROGRAMS)
+all-local: $(PROGRAMS)
+	if [ -z "`file $(PROGRAMS) | grep x86.64`" ]; then \
+	  ARCH="32"; \
+	else \
+	  ARCH="64"; \
+	fi; \
+	mkdir -p ../matlab/preprocessor$$ARCH ; \
+	cd ../matlab/preprocessor$$ARCH && $(LN_S) -f $(abs_srcdir)/$(PROGRAMS) $(PROGRAMS)
 
 if HAVE_DOXYGEN
 html-local:
@@ -77,7 +83,7 @@ html-local:
 endif
 
 clean-local:
-	cd ../matlab && rm -f $(PROGRAMS)
+	rm -rf ../matlab/preprocessor*
 	rm -rf doc/html/
 
 EXTRA_DIST = $(BUILT_SOURCES) Doxyfile
diff --git a/preprocessor/ModFile.cc b/preprocessor/ModFile.cc
index 554901776c5937822b7ace9f134407bcafa8bcbf..0a7860c4d61b8870a33238c7c262cc366015fbb6 100644
--- a/preprocessor/ModFile.cc
+++ b/preprocessor/ModFile.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006-2014 Dynare Team
+ * Copyright (C) 2006-2015 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -32,6 +32,7 @@
 
 ModFile::ModFile(WarningConsolidation &warnings_arg)
   : expressions_tree(symbol_table, num_constants, external_functions_table),
+    original_model(symbol_table, num_constants, external_functions_table),
     dynamic_model(symbol_table, num_constants, external_functions_table),
     trend_dynamic_model(symbol_table, num_constants, external_functions_table),
     ramsey_FOC_equations_dynamic_model(symbol_table, num_constants, external_functions_table),
@@ -289,7 +290,7 @@ ModFile::checkPass()
 
   // Check if some exogenous is not used in the model block
   set<int> unusedExo = dynamic_model.findUnusedExogenous();
-  if (unusedExo.size() > 1)
+  if (unusedExo.size() > 0)
     {
       warnings << "WARNING: some exogenous (";
       for (set<int>::const_iterator it = unusedExo.begin();
@@ -306,6 +307,9 @@ ModFile::checkPass()
 void
 ModFile::transformPass(bool nostrict)
 {
+  // Save the original model (must be done before any model transformations by preprocessor)
+  dynamic_model.cloneDynamic(original_model);
+
   if (nostrict)
     {
       set<int> unusedEndogs = dynamic_model.findUnusedEndogenous();
@@ -465,55 +469,55 @@ ModFile::computingPass(bool no_tmp_terms, FileOutputType output)
       // Compute static model and its derivatives
       dynamic_model.toStatic(static_model);
       if (!no_static)
-        {
-          if (mod_file_struct.stoch_simul_present
-              || mod_file_struct.estimation_present || mod_file_struct.osr_present
-              || mod_file_struct.ramsey_model_present || mod_file_struct.identification_present
-              || mod_file_struct.calib_smoother_present)
-            static_model.set_cutoff_to_zero();
-
-          const bool static_hessian = mod_file_struct.identification_present
-            || mod_file_struct.estimation_analytic_derivation;
-          const bool paramsDerivatives = mod_file_struct.identification_present
-            || mod_file_struct.estimation_analytic_derivation;
-          static_model.computingPass(global_eval_context, no_tmp_terms, static_hessian,
-                                     false, paramsDerivatives, block, byte_code);
-        }
+	{
+	  if (mod_file_struct.stoch_simul_present
+	      || mod_file_struct.estimation_present || mod_file_struct.osr_present
+	      || mod_file_struct.ramsey_model_present || mod_file_struct.identification_present
+	      || mod_file_struct.calib_smoother_present)
+	    static_model.set_cutoff_to_zero();
+
+	  const bool static_hessian = mod_file_struct.identification_present
+	    || mod_file_struct.estimation_analytic_derivation;
+	  const bool paramsDerivatives = mod_file_struct.identification_present
+	    || mod_file_struct.estimation_analytic_derivation;
+	  static_model.computingPass(global_eval_context, no_tmp_terms, static_hessian,
+				     false, paramsDerivatives, block, byte_code);
+	}
       // Set things to compute for dynamic model
       if (mod_file_struct.perfect_foresight_solver_present || mod_file_struct.check_present
-          || mod_file_struct.stoch_simul_present
-          || mod_file_struct.estimation_present || mod_file_struct.osr_present
-          || mod_file_struct.ramsey_model_present || mod_file_struct.identification_present
-          || mod_file_struct.calib_smoother_present)
-        {
-          if (mod_file_struct.perfect_foresight_solver_present)
-            dynamic_model.computingPass(true, false, false, false, global_eval_context, no_tmp_terms, block, use_dll, byte_code);
-          else
-            {
-              if (mod_file_struct.stoch_simul_present
-                  || mod_file_struct.estimation_present || mod_file_struct.osr_present
-                  || mod_file_struct.ramsey_model_present || mod_file_struct.identification_present
-                  || mod_file_struct.calib_smoother_present)
-                dynamic_model.set_cutoff_to_zero();
-              if (mod_file_struct.order_option < 1 || mod_file_struct.order_option > 3)
-                {
-                  cerr << "ERROR: Incorrect order option..." << endl;
-                  exit(EXIT_FAILURE);
-                }
-              bool hessian = mod_file_struct.order_option >= 2 
-		|| mod_file_struct.identification_present 
-		|| mod_file_struct.estimation_analytic_derivation
-		|| output == second 
-		|| output == third;
-              bool thirdDerivatives = mod_file_struct.order_option == 3 
-		|| mod_file_struct.estimation_analytic_derivation
-		|| output == third;
-              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);
-            }
-        }
-      else // No computing task requested, compute derivatives up to 2nd order by default
-        dynamic_model.computingPass(true, true, false, false, global_eval_context, no_tmp_terms, block, use_dll, byte_code);
+	  || mod_file_struct.stoch_simul_present
+	  || mod_file_struct.estimation_present || mod_file_struct.osr_present
+	  || mod_file_struct.ramsey_model_present || mod_file_struct.identification_present
+	  || mod_file_struct.calib_smoother_present)
+	{
+	  if (mod_file_struct.perfect_foresight_solver_present)
+	    dynamic_model.computingPass(true, false, false, false, global_eval_context, no_tmp_terms, block, use_dll, byte_code);
+	      else
+		{
+		  if (mod_file_struct.stoch_simul_present
+		      || mod_file_struct.estimation_present || mod_file_struct.osr_present
+		      || mod_file_struct.ramsey_model_present || mod_file_struct.identification_present
+		      || mod_file_struct.calib_smoother_present)
+		    dynamic_model.set_cutoff_to_zero();
+		  if (mod_file_struct.order_option < 1 || mod_file_struct.order_option > 3)
+		    {
+		      cerr << "ERROR: Incorrect order option..." << endl;
+		      exit(EXIT_FAILURE);
+		    }
+		  bool hessian = mod_file_struct.order_option >= 2 
+		    || mod_file_struct.identification_present 
+		    || mod_file_struct.estimation_analytic_derivation
+		    || output == second 
+		    || output == third;
+		  bool thirdDerivatives = mod_file_struct.order_option == 3 
+		    || mod_file_struct.estimation_analytic_derivation
+		    || output == third;
+		  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);
+		}
+	    }
+	  else // No computing task requested, compute derivatives up to 2nd order by default
+	    dynamic_model.computingPass(true, true, false, false, global_eval_context, no_tmp_terms, block, use_dll, byte_code);
     }
 
   for (vector<Statement *>::iterator it = statements.begin();
@@ -522,7 +526,8 @@ ModFile::computingPass(bool no_tmp_terms, FileOutputType output)
 }
 
 void
-ModFile::writeOutputFiles(const string &basename, bool clear_all, bool no_log, bool no_warn, bool console, bool nograph, bool nointeractive, const ConfigFile &config_file
+ModFile::writeOutputFiles(const string &basename, bool clear_all, bool clear_global, bool no_log, bool no_warn, bool console, bool nograph,
+			  bool nointeractive, const ConfigFile &config_file, bool check_model_changes
 #if defined(_WIN32) || defined(__CYGWIN32__)
                           , bool cygwin, bool msvc
 #endif
@@ -559,6 +564,8 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool no_log, b
 
   if (clear_all)
     mOutputFile << "clear all" << endl;
+  else if (clear_global)
+    mOutputFile << "clear M_ options_ oo_ estim_params_ bayestopt_ dataset_;" << endl;
 
   mOutputFile << "tic;" << endl
 	      << "% Save empty dates and dseries objects in memory." << endl
@@ -568,6 +575,9 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool no_log, b
               << "global M_ oo_ options_ ys0_ ex0_ estimation_info" << endl
               << "options_ = [];" << endl
               << "M_.fname = '" << basename << "';" << endl
+              << "M_.dynare_version = '" << PACKAGE_VERSION << "';" << endl
+              << "oo_.dynare_version = '" << PACKAGE_VERSION << "';" << endl
+              << "options_.dynare_version = '" << PACKAGE_VERSION << "';" << endl
               << "%" << endl
               << "% Some global variables initialization" << endl
               << "%" << endl;
@@ -586,7 +596,7 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool no_log, b
   if (nointeractive)
     mOutputFile << "options_.nointeractive = 1;" << endl;
     
-  cout << "Processing outputs ...";
+  cout << "Processing outputs ..." << endl;
 
   symbol_table.writeOutput(mOutputFile);
 
@@ -640,18 +650,25 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool no_log, b
                 << "  error('DYNARE: Can''t find bytecode DLL. Please compile it or remove the ''bytecode'' option.')" << endl
                 << "end" << endl;
 
-  // Erase possible remnants of previous runs
-  unlink((basename + "_dynamic.m").c_str());
-  unlink((basename + "_dynamic.cod").c_str());
-  unlink((basename + "_dynamic.bin").c_str());
-
-  unlink((basename + "_static.m").c_str());
-  unlink((basename + "_static.cod").c_str());
-  unlink((basename + "_static.bin").c_str());
+  bool hasModelChanged = !dynamic_model.isChecksumMatching(basename);
+  if (!check_model_changes)
+    hasModelChanged = true;
+  
+  if (hasModelChanged)
+    {
+      // Erase possible remnants of previous runs
+      unlink((basename + "_dynamic.m").c_str());
+      unlink((basename + "_dynamic.cod").c_str());
+      unlink((basename + "_dynamic.bin").c_str());
 
-  unlink((basename + "_steadystate2.m").c_str());
-  unlink((basename + "_set_auxiliary_variables.m").c_str());
+      unlink((basename + "_static.m").c_str());
+      unlink((basename + "_static.cod").c_str());
+      unlink((basename + "_static.bin").c_str());
 
+      unlink((basename + "_steadystate2.m").c_str());
+      unlink((basename + "_set_auxiliary_variables.m").c_str());
+    }
+  
   if (!use_dll)
     {
       mOutputFile << "erase_compiled_function('" + basename + "_static');" << endl;
@@ -686,55 +703,22 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool no_log, b
 #endif
 
   // Compile the dynamic MEX file for use_dll option
+  // When check_model_changes is true, don't force compile if MEX is fresher than source
   if (use_dll)
     {
-      mOutputFile << "if ~exist('OCTAVE_VERSION')" << endl;
-      // Some mex commands are enclosed in an eval(), because otherwise it will make Octave fail
 #if defined(_WIN32) || defined(__CYGWIN32__)
       if (msvc)
         // MATLAB/Windows + Microsoft Visual C++
-        mOutputFile << "    eval('mex -O LINKFLAGS=\"$LINKFLAGS /export:Dynamic\" " << basename << "_dynamic.c " << basename << "_dynamic_mex.c')" << endl
-                    << "    eval('mex -O LINKFLAGS=\"$LINKFLAGS /export:Static\" " << basename << "_static.c "<< basename << "_static_mex.c')" << endl;
+	mOutputFile << "dyn_mex('msvc', '" << basename << "', " << !check_model_changes << ")" <<  endl;
       else if (cygwin)
         // MATLAB/Windows + Cygwin g++
-        mOutputFile << "    eval('mex -O PRELINK_CMDS1=\"echo EXPORTS > mex.def & echo mexFunction >> mex.def & echo Dynamic >> mex.def\" " << basename << "_dynamic.c " << basename << "_dynamic_mex.c')" << endl
-                    << "    eval('mex -O PRELINK_CMDS1=\"echo EXPORTS > mex.def & echo mexFunction >> mex.def & echo Static >> mex.def\" " << basename << "_static.c "<< basename << "_static_mex.c')" << endl;
+	mOutputFile << "dyn_mex('cygwin', '" << basename << "', " << !check_model_changes << ")" << endl;
       else
         mOutputFile << "    error('When using the USE_DLL option, you must give either ''cygwin'' or ''msvc'' option to the ''dynare'' command')" << endl;
 #else
-# ifdef __linux__
-      // MATLAB/Linux
-      mOutputFile << "    if matlab_ver_less_than('8.3')" << endl
-                  << "        eval('mex -O LDFLAGS=''-pthread -shared -Wl,--no-undefined'' " << basename << "_dynamic.c " << basename << "_dynamic_mex.c')" << endl
-                  << "        eval('mex -O LDFLAGS=''-pthread -shared -Wl,--no-undefined'' " << basename << "_static.c "<< basename << "_static_mex.c')" << endl
-                  << "    else" << endl
-                  << "        eval('mex -O LINKEXPORT='''' " << basename << "_dynamic.c " << basename << "_dynamic_mex.c')" << endl
-                  << "        eval('mex -O LINKEXPORT='''' " << basename << "_static.c "<< basename << "_static_mex.c')" << endl
-                  << "    end" << endl;
-# else // MacOS
-      // MATLAB/MacOS
-      mOutputFile << "    if matlab_ver_less_than('8.3')" << endl
-                  << "        if matlab_ver_less_than('8.1')" << endl
-                  << "            eval('mex -O LDFLAGS=''-Wl,-twolevel_namespace -undefined error -arch \\$ARCHS -Wl,-syslibroot,\\$SDKROOT -mmacosx-version-min=\\$MACOSX_DEPLOYMENT_TARGET -bundle'' "
-                  << basename << "_dynamic.c " << basename << "_dynamic_mex.c')" << endl
-                  << "            eval('mex -O LDFLAGS=''-Wl,-twolevel_namespace -undefined error -arch \\$ARCHS -Wl,-syslibroot,\\$SDKROOT -mmacosx-version-min=\\$MACOSX_DEPLOYMENT_TARGET -bundle'' "
-                  << basename << "_static.c " << basename << "_static_mex.c')" << endl
-                  << "        else" << endl
-                  << "            eval('mex -O LDFLAGS=''-Wl,-twolevel_namespace -undefined error -arch \\$ARCHS -Wl,-syslibroot,\\$MW_SDKROOT -mmacosx-version-min=\\$MACOSX_DEPLOYMENT_TARGET -bundle'' "
-                  << basename << "_dynamic.c " << basename << "_dynamic_mex.c')" << endl
-                  << "            eval('mex -O LDFLAGS=''-Wl,-twolevel_namespace -undefined error -arch \\$ARCHS -Wl,-syslibroot,\\$MW_SDKROOT -mmacosx-version-min=\\$MACOSX_DEPLOYMENT_TARGET -bundle'' "
-                  << basename << "_static.c " << basename << "_static_mex.c')" << endl
-                  << "        end" << endl
-                  << "    else" << endl
-                  << "        eval('mex -O LINKEXPORT='''' " << basename << "_dynamic.c " << basename << "_dynamic_mex.c')" << endl
-                  << "        eval('mex -O LINKEXPORT='''' " << basename << "_static.c "<< basename << "_static_mex.c')" << endl
-                  << "    end" << endl;
-# endif
+      // other configurations
+      mOutputFile << "dyn_mex('', '" << basename << "', " << !check_model_changes << ")" << endl;
 #endif
-      mOutputFile << "else" << endl // Octave
-                  << "    mex " << basename << "_dynamic.c " << basename << "_dynamic_mex.c" << endl
-                  << "    mex " << basename << "_static.c " << basename << "_static_mex.c" << endl
-                  << "end" << endl;
     }
 
   // Add path for block option with M-files
@@ -790,7 +774,9 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool no_log, b
               << "if exist('dataset_', 'var') == 1" << endl
               << "  save('" << basename << "_results.mat', 'dataset_', '-append');" << endl << "end" << endl
               << "if exist('estimation_info', 'var') == 1" << endl
-              << "  save('" << basename << "_results.mat', 'estimation_info', '-append');" << endl << "end" << endl;
+              << "  save('" << basename << "_results.mat', 'estimation_info', '-append');" << endl << "end" << endl
+              << "if exist('oo_recursive_', 'var') == 1" << endl
+              << "  save('" << basename << "_results.mat', 'oo_recursive_', '-append');" << endl << "end" << endl;
 
   config_file.writeEndParallel(mOutputFile);
 
@@ -813,22 +799,24 @@ ModFile::writeOutputFiles(const string &basename, bool clear_all, bool no_log, b
 
   mOutputFile.close();
 
-  // Create static and dynamic files
-  if (dynamic_model.equation_number() > 0)
+  if (hasModelChanged)
     {
-      if (!no_static)
-        {
-          static_model.writeStaticFile(basename, block, byte_code, use_dll);
-          static_model.writeParamsDerivativesFile(basename);
-        }
+      // Create static and dynamic files
+      if (dynamic_model.equation_number() > 0)
+	{
+	  if (!no_static)
+	    {
+	      static_model.writeStaticFile(basename, block, byte_code, use_dll);
+	      static_model.writeParamsDerivativesFile(basename);
+	    }
 
-      dynamic_model.writeDynamicFile(basename, block, byte_code, use_dll, mod_file_struct.order_option);
-      dynamic_model.writeParamsDerivativesFile(basename);
-    }
-
-  // Create steady state file
-  steady_state_model.writeSteadyStateFile(basename, mod_file_struct.ramsey_model_present);
+	  dynamic_model.writeDynamicFile(basename, block, byte_code, use_dll, mod_file_struct.order_option);
+	  dynamic_model.writeParamsDerivativesFile(basename);
+	}
 
+      // Create steady state file
+      steady_state_model.writeSteadyStateFile(basename, mod_file_struct.ramsey_model_present);
+    }
+  
   cout << "done" << endl;
 }
-
diff --git a/preprocessor/ModFile.hh b/preprocessor/ModFile.hh
index d8b042a73ed55c6749140b7ec603b9e407decec8..bf36366856d5c7645f8c226912a9122afde6d729 100644
--- a/preprocessor/ModFile.hh
+++ b/preprocessor/ModFile.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006-2014 Dynare Team
+ * Copyright (C) 2006-2015 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -24,6 +24,8 @@ using namespace std;
 
 #include <ostream>
 #include <ctime>
+#include <iostream>
+#include <sstream>
 
 #include "SymbolTable.hh"
 #include "NumericalConstants.hh"
@@ -37,6 +39,11 @@ using namespace std;
 #include "WarningConsolidation.hh"
 #include "ExtendedPreprocessorTypes.hh"
 
+// for checksum computation
+#ifndef PRIVATE_BUFFER_SIZE
+#define PRIVATE_BUFFER_SIZE 1024
+#endif
+
 //! The abstract representation of a "mod" file
 class ModFile
 {
@@ -51,6 +58,8 @@ public:
   NumericalConstants num_constants;
   //! Expressions outside model block
   DataTree expressions_tree;
+  //! Original model, as declared in the "model" block, that won't be modified by the preprocessor
+  DynamicModel original_model;
   //! Dynamic model, as declared in the "model" block
   DynamicModel dynamic_model;
   //! A copy of Dynamic model, for testing trends declared by user
@@ -136,7 +145,8 @@ public:
     \param cygwin Should the MEX command of use_dll be adapted for Cygwin?
     \param msvc Should the MEX command of use_dll be adapted for MSVC?
   */
-  void writeOutputFiles(const string &basename, bool clear_all, bool no_log, bool no_warn, bool console, bool nograph, bool nointeractive, const ConfigFile &config_file
+  void writeOutputFiles(const string &basename, bool clear_all, bool clear_global, bool no_log, bool no_warn,
+			bool console, bool nograph, bool nointeractive, const ConfigFile &config_file, bool check_model_changes
 #if defined(_WIN32) || defined(__CYGWIN32__)
                         , bool cygwin, bool msvc
 #endif
@@ -151,6 +161,8 @@ public:
   //! Writes Cpp output files only => No further Matlab processing
   void writeCCOutputFiles(const string &basename) const;
   void writeModelCC(const string &basename) const;
+
+  void computeChecksum();
 };
 
 #endif // ! MOD_FILE_HH
diff --git a/preprocessor/ModelTree.cc b/preprocessor/ModelTree.cc
index 7bdd78aed948bb82c7030dbd85c9fc4eea340d77..688d4f292d888d43c533a40456f871dc2f976cc4 100644
--- a/preprocessor/ModelTree.cc
+++ b/preprocessor/ModelTree.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2014 Dynare Team
+ * Copyright (C) 2003-2015 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -1352,6 +1352,7 @@ ModelTree::writeLatexModelFile(const string &filename, ExprNodeOutputType output
   output << "\\documentclass[10pt,a4paper]{article}" << endl
          << "\\usepackage[landscape]{geometry}" << endl
          << "\\usepackage{fullpage}" << endl
+         << "\\usepackage{amsfonts}" << endl
          << "\\usepackage{breqn}" << endl
          << "\\begin{document}" << endl
          << "\\footnotesize" << endl;
diff --git a/preprocessor/ParsingDriver.cc b/preprocessor/ParsingDriver.cc
index c7f6b2574e07da1a109a9a2da8d79f753f66f2ad..ba541ec818e250c5f2acef060062be0457151306 100644
--- a/preprocessor/ParsingDriver.cc
+++ b/preprocessor/ParsingDriver.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2014 Dynare Team
+ * Copyright (C) 2003-2015 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -1186,8 +1186,7 @@ ParsingDriver::add_in_symbol_list(string *tmp_var)
 void
 ParsingDriver::rplot()
 {
-  mod_file->addStatement(new RplotStatement(symbol_list, options_list));
-  options_list.clear();
+  mod_file->addStatement(new RplotStatement(symbol_list));
   symbol_list.clear();
 }
 
@@ -1410,6 +1409,26 @@ ParsingDriver::set_prior(string *name, string *subsample_name)
   delete subsample_name;
 }
 
+void
+ParsingDriver::set_joint_prior(vector<string *>*symbol_vec)
+{
+  for (vector<string *>::const_iterator it=symbol_vec->begin(); it != symbol_vec->end(); it++)
+    add_joint_parameter(*it);
+  mod_file->addStatement(new JointPriorStatement(joint_parameters, prior_shape, options_list));
+  joint_parameters.clear();
+  options_list.clear();
+  prior_shape = eNoShape;
+  delete symbol_vec;
+}
+
+void
+ParsingDriver::add_joint_parameter(string *name)
+{
+  check_symbol_is_parameter(name);
+  joint_parameters.push_back(*name);
+  delete name;
+}
+
 void
 ParsingDriver::set_prior_variance(expr_t variance)
 {
@@ -1611,6 +1630,34 @@ ParsingDriver::optim_options_num(string *name, string *value)
   delete value;
 }
 
+void
+ParsingDriver::tarb_optim_options_helper(const string &name)
+{
+  if (options_list.string_options.find("TaRB.optim_opt") == options_list.string_options.end())
+    options_list.string_options["TaRB.optim_opt"] = "";
+  else
+    options_list.string_options["TaRB.optim_opt"] += ",";
+  options_list.string_options["TaRB.optim_opt"] += "''" + name + "'',";
+}
+
+void
+ParsingDriver::tarb_optim_options_string(string *name, string *value)
+{
+  tarb_optim_options_helper(*name);
+  options_list.string_options["TaRB.optim_opt"] += "''" + *value + "''";
+  delete name;
+  delete value;
+}
+
+void
+ParsingDriver::tarb_optim_options_num(string *name, string *value)
+{
+  tarb_optim_options_helper(*name);
+  options_list.string_options["TaRB.optim_opt"] += *value;
+  delete name;
+  delete value;
+}
+
 void
 ParsingDriver::check_varobs()
 {
@@ -1820,6 +1867,12 @@ ParsingDriver::write_latex_static_model()
   mod_file->addStatement(new WriteLatexStaticModelStatement(mod_file->static_model));
 }
 
+void
+ParsingDriver::write_latex_original_model()
+{
+  mod_file->addStatement(new WriteLatexOriginalModelStatement(mod_file->original_model));
+}
+
 void
 ParsingDriver::bvar_density(string *maxnlags)
 {
diff --git a/preprocessor/ParsingDriver.hh b/preprocessor/ParsingDriver.hh
index a747e896cadb97b75ee5a985265c461d6f6bb826..dd93276c08e2b9f96b6cf861ca2299fd9563cae3 100644
--- a/preprocessor/ParsingDriver.hh
+++ b/preprocessor/ParsingDriver.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2014 Dynare Team
+ * Copyright (C) 2003-2015 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -98,6 +98,7 @@ private:
 
   //! Creates option "optim_opt" in OptionsList if it doesn't exist, else add a comma, and adds the option name
   void optim_options_helper(const string &name);
+  void tarb_optim_options_helper(const string &name);
 
   //! Stores temporary symbol table
   SymbolList symbol_list;
@@ -186,6 +187,8 @@ private:
 
   //! Temporary storage for argument list of external function
   stack<vector<expr_t> >  stack_external_function_args;
+  //! Temporary storage for parameters in joint prior statement
+  vector<string> joint_parameters;
   //! Temporary storage for the symb_id associated with the "name" symbol of the current external_function statement
   int current_external_function_id;
   //! Temporary storage for option list provided to external_function()
@@ -411,6 +414,10 @@ public:
   void estimation_data();
   //! Sets the prior for a parameter
   void set_prior(string *arg1, string *arg2);
+  //! Sets the joint prior for a set of parameters
+  void set_joint_prior(vector<string *>*symbol_vec);
+  //! Adds a parameters to the list of joint parameters
+  void add_joint_parameter(string *name);
   //! Adds the variance option to its temporary holding place
   void set_prior_variance(expr_t variance=NULL);
   //! Copies the prior from_name to_name
@@ -437,6 +444,10 @@ public:
   void optim_options_string(string *name, string *value);
   //! Adds an optimization option (numeric value)
   void optim_options_num(string *name, string *value);
+  //! Adds a TaRB optimization option (string value)
+  void tarb_optim_options_string(string *name, string *value);
+  //! Adds a TaRB optimization option (numeric value)
+  void tarb_optim_options_num(string *name, string *value);
   //! Check that no observed variable has yet be defined
   void check_varobs();
   //! Add a new observed variable
@@ -503,6 +514,8 @@ public:
   void write_latex_dynamic_model();
   //! Adds a write_latex_static_model statement
   void write_latex_static_model();
+  //! Adds a write_latex_original_model statement
+  void write_latex_original_model();
   //! BVAR marginal density
   void bvar_density(string *maxnlags);
   //! BVAR forecast
diff --git a/preprocessor/StaticModel.cc b/preprocessor/StaticModel.cc
index 09fb9261b06593004b1fc7244c6e5b20ab09014d..045e63364b368a644dadfcb5868e576f3bf337c0 100644
--- a/preprocessor/StaticModel.cc
+++ b/preprocessor/StaticModel.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2014 Dynare Team
+ * Copyright (C) 2003-2015 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -1927,9 +1927,16 @@ void StaticModel::writeAuxVarRecursiveDefinitions(const string &basename) const
          << "%           from model file (.mod)" << endl
          << endl;
 
+  deriv_node_temp_terms_t tef_terms;
+  temporary_terms_t temporary_terms;
+  for (int i = 0; i < (int) aux_equations.size(); i++)
+    if (dynamic_cast<ExprNode *>(aux_equations[i])->containsExternalFunction())
+      dynamic_cast<ExprNode *>(aux_equations[i])->writeExternalFunctionOutput(output, oMatlabStaticModel,
+                                                                              temporary_terms, tef_terms);
+
   for (int i = 0; i < (int) aux_equations.size(); i++)
     {
-      dynamic_cast<ExprNode *>(aux_equations[i])->writeOutput(output, oMatlabStaticModel);
+      dynamic_cast<ExprNode *>(aux_equations[i])->writeOutput(output, oMatlabStaticModel, temporary_terms, tef_terms);
       output << ";" << endl;
     }
 }
diff --git a/preprocessor/SymbolTable.cc b/preprocessor/SymbolTable.cc
index 9d43b79114881831a6a2496d412ca89e5539d2d3..2c1a699c593433fb06dd58e6cb1245d328e363c9 100644
--- a/preprocessor/SymbolTable.cc
+++ b/preprocessor/SymbolTable.cc
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2014 Dynare Team
+ * Copyright (C) 2003-2015 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -25,12 +25,15 @@
 #include "SymbolTable.hh"
 
 AuxVarInfo::AuxVarInfo(int symb_id_arg, aux_var_t type_arg, int orig_symb_id_arg, int orig_lead_lag_arg,
-                       int equation_number_for_multiplier_arg) :
+                       int equation_number_for_multiplier_arg, int information_set_arg,
+                       expr_t expectation_expr_node_arg) :
   symb_id(symb_id_arg),
   type(type_arg),
   orig_symb_id(orig_symb_id_arg),
   orig_lead_lag(orig_lead_lag_arg),
-  equation_number_for_multiplier(equation_number_for_multiplier_arg)
+  equation_number_for_multiplier(equation_number_for_multiplier_arg),
+  information_set(information_set_arg),
+  expectation_expr_node(expectation_expr_node_arg)
 {
 }
 
@@ -243,7 +246,6 @@ SymbolTable::writeOutput(ostream &output) const throw (NotYetFrozenException)
           {
           case avEndoLead:
           case avExoLead:
-          case avExpectation:
             break;
           case avEndoLag:
           case avExoLag:
@@ -256,6 +258,13 @@ SymbolTable::writeOutput(ostream &output) const throw (NotYetFrozenException)
           case avDiffForward:
             output << "M_.aux_vars(" << i+1 << ").orig_index = " << getTypeSpecificID(aux_vars[i].get_orig_symb_id())+1 << ";" << endl;
             break;
+          case avExpectation:
+            output << "M_.aux_vars(" << i+1 << ").orig_expr = '\\mathbb{E}_{t"
+                   << (aux_vars[i].get_information_set() < 0 ? "" : "+")
+                   << aux_vars[i].get_information_set() << "}(";
+            aux_vars[i].get_expectation_expr_node()->writeOutput(output, oLatexDynamicModel);
+            output << ")';" << endl;
+            break;
           }
       }
 
@@ -468,7 +477,7 @@ SymbolTable::addLeadAuxiliaryVarInternal(bool endo, int index) throw (FrozenExce
       exit(EXIT_FAILURE);
     }
 
-  aux_vars.push_back(AuxVarInfo(symb_id, (endo ? avEndoLead : avExoLead), 0, 0, 0));
+  aux_vars.push_back(AuxVarInfo(symb_id, (endo ? avEndoLead : avExoLead), 0, 0, 0, 0, NULL));
 
   return symb_id;
 }
@@ -494,7 +503,7 @@ SymbolTable::addLagAuxiliaryVarInternal(bool endo, int orig_symb_id, int orig_le
       exit(EXIT_FAILURE);
     }
 
-  aux_vars.push_back(AuxVarInfo(symb_id, (endo ? avEndoLag : avExoLag), orig_symb_id, orig_lead_lag, 0));
+  aux_vars.push_back(AuxVarInfo(symb_id, (endo ? avEndoLag : avExoLag), orig_symb_id, orig_lead_lag, 0, 0, NULL));
 
   return symb_id;
 }
@@ -524,7 +533,7 @@ SymbolTable::addExoLagAuxiliaryVar(int orig_symb_id, int orig_lead_lag) throw (F
 }
 
 int
-SymbolTable::addExpectationAuxiliaryVar(int information_set, int index) throw (FrozenException)
+SymbolTable::addExpectationAuxiliaryVar(int information_set, int index, expr_t exp_arg) throw (FrozenException)
 {
   ostringstream varname;
   int symb_id;
@@ -542,7 +551,7 @@ SymbolTable::addExpectationAuxiliaryVar(int information_set, int index) throw (F
       exit(EXIT_FAILURE);
     }
 
-  aux_vars.push_back(AuxVarInfo(symb_id, avExpectation, 0, 0, 0));
+  aux_vars.push_back(AuxVarInfo(symb_id, avExpectation, 0, 0, 0, information_set, exp_arg));
 
   return symb_id;
 }
@@ -564,7 +573,7 @@ SymbolTable::addMultiplierAuxiliaryVar(int index) throw (FrozenException)
       exit(EXIT_FAILURE);
     }
 
-  aux_vars.push_back(AuxVarInfo(symb_id, avMultiplier, 0, 0, index));
+  aux_vars.push_back(AuxVarInfo(symb_id, avMultiplier, 0, 0, index, 0, NULL));
   return symb_id;
 }
 
@@ -585,7 +594,7 @@ SymbolTable::addDiffForwardAuxiliaryVar(int orig_symb_id) throw (FrozenException
       exit(EXIT_FAILURE);
     }
 
-  aux_vars.push_back(AuxVarInfo(symb_id, avDiffForward, orig_symb_id, 0, 0));
+  aux_vars.push_back(AuxVarInfo(symb_id, avDiffForward, orig_symb_id, 0, 0, 0, NULL));
   return symb_id;
 }
 
diff --git a/preprocessor/SymbolTable.hh b/preprocessor/SymbolTable.hh
index 3e4c47e126940efb470002e6a81b597ba22330f8..4be960a1c87bb6265a977ee2af25b0ff166801a3 100644
--- a/preprocessor/SymbolTable.hh
+++ b/preprocessor/SymbolTable.hh
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2003-2014 Dynare Team
+ * Copyright (C) 2003-2015 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -29,6 +29,9 @@ using namespace std;
 #include <ostream>
 
 #include "CodeInterpreter.hh"
+#include "ExprNode.hh"
+
+typedef class ExprNode *expr_t;
 
 //! Types of auxiliary variables
 enum aux_var_t
@@ -51,13 +54,17 @@ private:
   int orig_symb_id; //!< Symbol ID of the endo of the original model represented by this aux var. Only used for avEndoLag and avExoLag.
   int orig_lead_lag; //!< Lead/lag of the endo of the original model represented by this aux var. Only used for avEndoLag and avExoLag.
   int equation_number_for_multiplier; //!< Stores the original constraint equation number associated with this aux var. Only used for avMultiplier.
+  int information_set; //! Argument of expectation operator. Only used for avExpectation.
+  expr_t expectation_expr_node; //! Argument of expectation operator. Only used for avExpectation.
 public:
-  AuxVarInfo(int symb_id_arg, aux_var_t type_arg, int orig_symb_id, int orig_lead_lag, int equation_number_for_multiplier_arg);
+  AuxVarInfo(int symb_id_arg, aux_var_t type_arg, int orig_symb_id, int orig_lead_lag, int equation_number_for_multiplier_arg, int information_set_arg, expr_t expectation_expr_node_arg);
   int get_symb_id() const { return symb_id; };
   aux_var_t get_type() const { return type; };
   int get_orig_symb_id() const { return orig_symb_id; };
   int get_orig_lead_lag() const { return orig_lead_lag; };
   int get_equation_number_for_multiplier() const { return equation_number_for_multiplier; };
+  int get_information_set() const { return information_set; };
+  expr_t get_expectation_expr_node() const { return expectation_expr_node; } ;
 };
 
 //! Stores the symbol table
@@ -216,7 +223,7 @@ public:
     \param[in] index Used to construct the variable name
     \return the symbol ID of the new symbol
   */
-  int addExpectationAuxiliaryVar(int information_set, int index) throw (FrozenException);
+  int addExpectationAuxiliaryVar(int information_set, int index, expr_t arg) throw (FrozenException);
   //! Adds an auxiliary variable for the multiplier for the FOCs of the Ramsey Problem
   /*!
     \param[in] index Used to construct the variable name
diff --git a/preprocessor/macro/MacroFlex.ll b/preprocessor/macro/MacroFlex.ll
index 05a60329c71d35dfa8c62794da03fa5cfad0a7e6..0b5ff7a21e5f96c386401b85389ae3519c7f8951 100644
--- a/preprocessor/macro/MacroFlex.ll
+++ b/preprocessor/macro/MacroFlex.ll
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008-2013 Dynare Team
+ * Copyright (C) 2008-2015 Dynare Team
  *
  * This file is part of Dynare.
  *
@@ -84,6 +84,32 @@ CONT \\\\
                               BEGIN(INITIAL);
                             }
 
+<INITIAL>^{SPC}*@#{SPC}*include{SPC}+[^\"\r\n]*{SPC}*{EOL} {
+                              yylloc->lines(1);
+                              yylloc->step();
+
+                              // Get variable name
+                              string modvarname = string(yytext);
+                              int dblq_idx1 = modvarname.find("include");
+                              modvarname.erase(0, dblq_idx1 + 7);
+                              modvarname.erase(0, modvarname.find_first_not_of(" \t"));
+                              size_t p = modvarname.find_last_not_of(" \t\n\r");
+                              if (string::npos != p)
+                                modvarname.erase(p+1);
+
+                              string *filename = NULL;
+                              try
+                              {
+                                filename = new string(driver.get_variable(modvarname)->toString());
+                              }
+                              catch(MacroDriver::UnknownVariable(&e))
+                              {
+                                driver.error(*yylloc, "Unknown variable: " + modvarname);
+                              }
+                              create_include_context(filename, yylloc, driver);
+                              BEGIN(INITIAL);
+                            }
+
 <INITIAL>^{SPC}*@#          { yylloc->step(); BEGIN(STMT); }
 <INITIAL>@\{                { yylloc->step(); BEGIN(EXPR); }
 
@@ -190,7 +216,7 @@ CONT \\\\
                               yylloc->step();
                             }
 <FOR_BODY>.                 { for_body_tmp.append(yytext); yylloc->step(); }
-<FOR_BODY><<EOF>>           { driver.error(for_stmt_loc_tmp, "@#for loop not matched by an @#endfor (unexpected end of file)"); }
+<FOR_BODY><<EOF>>           { driver.error(for_stmt_loc_tmp, "@#for loop not matched by an @#endfor or file does not end with a new line (unexpected end of file)"); }
 <FOR_BODY>^{SPC}*@#{SPC}*endfor{SPC}*(\/\/.*)?{EOL} {
                               yylloc->lines(1);
                               yylloc->step();
@@ -227,7 +253,7 @@ CONT \\\\
                               yylloc->step();
                             }
 <THEN_BODY>.                { then_body_tmp.append(yytext); yylloc->step(); }
-<THEN_BODY><<EOF>>          { driver.error(if_stmt_loc_tmp, "@#if/@#ifdef/@#ifndef 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 or file does not end with a new line (unexpected end of file)"); }
 <THEN_BODY>^{SPC}*@#{SPC}*else{SPC}*(\/\/.*)?{EOL} {
                               yylloc->lines(1);
                               yylloc->step();
@@ -269,7 +295,7 @@ CONT \\\\
                               yylloc->step();
                             }
 <ELSE_BODY>.                { else_body_tmp.append(yytext); yylloc->step(); }
-<ELSE_BODY><<EOF>>          { driver.error(if_stmt_loc_tmp, "@#if/@#ifdef/@#ifndef 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 or file does not end with a new line (unexpected end of file)"); }
 
 <ELSE_BODY>^{SPC}*@#{SPC}*endif{SPC}*(\/\/.*)?{EOL} {
                               yylloc->lines(1);
diff --git a/tests/Makefile.am b/tests/Makefile.am
index b133708533968acc5b62c914a8fb57adb70cac27..c45755cd88bfac986ff727ae0cbcced739164fc8 100644
--- a/tests/Makefile.am
+++ b/tests/Makefile.am
@@ -6,7 +6,10 @@ MODFILES = \
 	estimation/fs2000_MCMC_jumping_covariance.mod \
 	estimation/fs2000_initialize_from_calib.mod	\
 	estimation/fs2000_calibrated_covariance.mod \
+	estimation/MH_recover/fs2000_recover.mod \
+	estimation/t_proposal/fs2000_student.mod \
 	gsa/ls2003.mod \
+	gsa/ls2003a.mod \
 	ramst.mod \
 	ramst_a.mod \
 	ramst_static_tag.mod \
@@ -21,7 +24,13 @@ MODFILES = \
 	optimal_policy/osr_example.mod \
 	optimal_policy/osr_example_objective_correctness.mod \
 	optimal_policy/osr_example_obj_corr_non_stat_vars.mod \
-	optimal_policy/ramsey.mod \
+	optimal_policy/OSR/osr_obj_corr_algo_1.mod \
+	optimal_policy/OSR/osr_obj_corr_algo_3.mod \
+	optimal_policy/OSR/osr_obj_corr_algo_4.mod \
+	optimal_policy/OSR/osr_obj_corr_algo_7.mod \
+	optimal_policy/OSR/osr_obj_corr_algo_8.mod \
+	optimal_policy/OSR/osr_obj_corr_algo_9.mod \
+	optimal_policy/ramsey_.mod \
 	optimal_policy/nk_ramsey.mod \
 	optimal_policy/nk_ramsey_model.mod \
 	optimal_policy/nk_ramsey_det.mod \
@@ -33,7 +42,7 @@ MODFILES = \
 	optimal_policy/Ramsey/ramsey_ex_initval_AR2.mod \
 	optimal_policy/Ramsey/ramsey_ex_aux.mod \
 	discretionary_policy/dennis_1.mod \
-	ramst_initval_file.mod \
+	initval_file/ramst_initval_file.mod \
 	ramst_normcdf_and_friends.mod \
 	ramst_vec.mod \
 	example1_varexo_det.mod \
@@ -79,18 +88,15 @@ MODFILES = \
 	arima/mod2b.mod \
 	arima/mod2c.mod \
 	data/mod1a.mod \
+	analytic_derivatives/fs2000_analytic_derivation.mod \
 	fs2000/fs2000.mod \
 	fs2000/fs2000a.mod \
 	fs2000/fs2000c.mod \
-	fs2000/fs2000d.mod \
-	fs2000/fs2000e.mod \
-	fs2000/fs2000_cmaes.mod \
 	fs2000/fs2000_calib.mod \
 	fs2000/fs2000_calib_dseries.mod \
 	fs2000/fs2000_analytic_derivation.mod \
 	fs2000/fs2000_missing_data.mod \
 	fs2000/fs2000_sd.mod \
-	fs2000/fs2000_mode_compute_8.mod \
 	fs2000/fs2000_dseries_a.mod \
 	fs2000/fs2000_dseries_b.mod \
 	homotopy/homotopy1_test.mod \
@@ -129,6 +135,7 @@ MODFILES = \
 	conditional_forecasts/fs2000_est.mod \
 	recursive/ls2003.mod \
 	recursive/ls2003_bayesian.mod \
+	recursive/ls2003_bayesian_xls.mod \
 	ms-sbvar/test_exclusions.mod \
 	ms-sbvar/test_exclusions_nc.mod \
 	ms-sbvar/test_lower_cholesky.mod \
@@ -154,6 +161,7 @@ MODFILES = \
 	kalman_filter_smoother/fs2000_1.mod \
 	kalman_filter_smoother/fs2000_2.mod \
 	kalman_filter_smoother/fs2000a.mod \
+	kalman_filter_smoother/fs2000_smoother_only.mod \
 	kalman_filter_smoother/check_variable_dimensions/fs2000.mod \
 	kalman_filter_smoother/check_variable_dimensions/fs2000_ML.mod \
 	second_order/burnside_1.mod \
@@ -172,6 +180,10 @@ MODFILES = \
 	deterministic_simulations/rbc_det5.mod \
 	deterministic_simulations/rbc_det6.mod \
 	deterministic_simulations/homotopy.mod \
+	deterministic_simulations/rbc_det_exo_lag_2a.mod \
+	deterministic_simulations/rbc_det_exo_lag_2b.mod \
+	deterministic_simulations/rbc_det_exo_lag_2c.mod \
+	deterministic_simulations/sim_several_leads_lags.mod \
 	walsh.mod \
 	measurement_errors/fs2000_corr_me_ml_mcmc/fs2000_corr_ME.mod \
 	trend_var/fs2000_nonstationary.mod \
@@ -194,12 +206,29 @@ MODFILES = \
 	smoother2histval/fs2000_simul.mod \
 	smoother2histval/fs2000_smooth.mod \
 	smoother2histval/fs2000_smooth_stoch_simul.mod \
+	optimizers/fs2000_2.mod \
+	optimizers/fs2000_3.mod \
+	optimizers/fs2000_4.mod \
+	optimizers/fs2000_4_with_optim.mod \
+	optimizers/fs2000_5.mod \
+	optimizers/fs2000_6.mod \
+	optimizers/fs2000_7.mod \
+	optimizers/fs2000_8.mod \
+	optimizers/fs2000_8_with_optim.mod \
+	optimizers/fs2000_9.mod \
+	optimizers/fs2000_10.mod \
+	optimizers/fs2000_101.mod \
+	optimizers/fs2000_102.mod \
+	optimizers/fs2000_w.mod \
+	differentiate_forward_vars/RBC_differentiate_forward.mod \
 	reporting/example1.mod
 
 XFAIL_MODFILES = ramst_xfail.mod \
 	estim_param_in_shock_value.mod \
 	optimal_policy/Ramsey/ramsey_ex_wrong_ss_file.mod
 
+MFILES = initval_file/ramst_initval_file_data.m
+
 # Dependencies
 example1_use_dll.m.trs: example1.m.trs
 example1_use_dll.o.trs: example1.o.trs
@@ -269,6 +298,16 @@ dsge-var/dsgevar_forward_estimated_lambda.o.trs: dsge-var/simul_hybrid.o.trs
 smoother2histval/fs2000_simul.m.trs: smoother2histval/fs2000_smooth.m.trs
 smoother2histval/fs2000_simul.o.trs: smoother2histval/fs2000_smooth.o.trs
 
+deterministic_simulations/rbc_det_exo_lag_2b.m.trs: deterministic_simulations/rbc_det_exo_lag_2a.m.trs
+deterministic_simulations/rbc_det_exo_lag_2c.m.trs: deterministic_simulations/rbc_det_exo_lag_2a.m.trs
+deterministic_simulations/rbc_det_exo_lag_2b.o.trs: deterministic_simulations/rbc_det_exo_lag_2a.o.trs
+deterministic_simulations/rbc_det_exo_lag_2c.o.trs: deterministic_simulations/rbc_det_exo_lag_2a.o.trs
+
+initval_file/ramst_initval_file.m.trs: initval_file/ramst_initval_file_data.m.tls
+initval_file/ramst_initval_file.o.trs: initval_file/ramst_initval_file_data.o.tls
+
+
+
 # Matlab TRS Files
 M_TRS_FILES = $(patsubst %.mod, %.m.trs, $(MODFILES))
 M_TRS_FILES += run_block_byte_tests_matlab.m.trs run_reporting_test_matlab.m.trs run_all_unitary_tests.m.trs
@@ -279,12 +318,21 @@ O_TRS_FILES = $(patsubst %.mod, %.o.trs, $(MODFILES))
 O_TRS_FILES += run_block_byte_tests_octave.o.trs run_reporting_test_octave.o.trs run_all_unitary_tests.o.trs
 O_XFAIL_TRS_FILES = $(patsubst %.mod, %.o.trs, $(XFAIL_MODFILES))
 
+# Matlab TLS Files
+M_TLS_FILES = $(patsubst %.m, %.m.tls, $(MFILES))
+
+# Octave TLS Files
+O_TLS_FILES = $(patsubst %.m, %.o.tls, $(MFILES))
+
+
+
 EXTRA_DIST = \
 	read_trs_files.sh \
 	run_test_matlab.m \
 	run_test_octave.m \
 	$(MODFILES) \
 	$(XFAIL_MODFILES) \
+	$(MFILES) \
 	run_block_byte_tests_matlab.m \
 	run_block_byte_tests_octave.m \
 	run_reporting_test_matlab.m \
@@ -305,8 +353,7 @@ EXTRA_DIST = \
 	fs2000_ssfile_aux.m \
 	printMakeCheckMatlabErrMsg.m \
 	printMakeCheckOctaveErrMsg.m \
-	ramst_initval_file_data.m \
-	test.m \
+	fataltest.m \
 	AIM/data_ca1.m \
 	AIM/fs2000_b1L1L_AIM_steadystate.m \
 	AIM/fs2000_b1L1L_steadystate.m \
@@ -319,6 +366,7 @@ EXTRA_DIST = \
 	expectations/expectation_ss_old_steadystate.m \
 	steady_state/walsh1_old_ss_steadystate.m \
 	data/test.xls \
+	analytic_derivatives/fsdat_simul.m \
 	fs2000/fs2000a_steadystate.m \
 	fs2000/fsdat_simul.m \
 	k_order_perturbation/run_fs2000kplusplus.m \
@@ -362,7 +410,9 @@ EXTRA_DIST = \
 	loglinear/results_exp.mat \
 	smoother2histval/fsdat_simul.m \
 	optimal_policy/Ramsey/find_c.m \
-	optimal_policy/Ramsey/oo_ramsey_policy_initval.mat 
+	optimal_policy/Ramsey/oo_ramsey_policy_initval.mat \
+	optimizers/optimizer_function_wrapper.m \
+	optimizers/fs2000.common.inc
 
 TARGETS =
 
@@ -387,25 +437,63 @@ check-octave: $(O_XFAIL_TRS_FILES) $(O_TRS_FILES)
 	@echo 'Octave Tests Done'
 
 %.m.trs %.m.log: %.mod
-	DYNARE_VERSION="$(PACKAGE_VERSION)" TOP_TEST_DIR="$(PWD)" FILESTEM="$*" \
-		$(MATLAB)/bin/matlab -nosplash -nodisplay -logfile $*.m.log -r run_test_matlab
+	@echo "`tput bold``tput setaf 8`MATLAB: $(PWD)/$*... `tput sgr0`"
+	@DYNARE_VERSION="$(PACKAGE_VERSION)" TOP_TEST_DIR="$(PWD)" FILESTEM="$*" \
+	$(MATLAB)/bin/matlab -nosplash -nodisplay -r run_test_matlab > $*.m.log  2> /dev/null
+	@if grep -q ":test-result: PASS" $*.m.trs; then \
+	echo "`tput bold``tput setaf 2`MATLAB: $(PWD)/$* PASSED!`tput sgr0`" ; \
+	else \
+	echo "`tput bold``tput setaf 1`MATLAB: $(PWD)/$* FAILED!`tput sgr0`" ; \
+	fi
+
+%.m.drs %.m.log: %.m.trs
+	@cat $*.m.log
 
 %.m.trs %.m.log : %.m
-	DYNARE_VERSION="$(PACKAGE_VERSION)" TOP_TEST_DIR="$(PWD)" \
-		$(MATLAB)/bin/matlab -nosplash -nodisplay -logfile $*.m.log -r $*
+	@echo "`tput bold``tput setaf 8`MATLAB: $(PWD)/$*... `tput sgr0`"
+	@DYNARE_VERSION="$(PACKAGE_VERSION)" TOP_TEST_DIR="$(PWD)" \
+		$(MATLAB)/bin/matlab -nosplash -nodisplay -r $* > $*.m.log 2> /dev/null 
+	@echo "`tput bold``tput setaf 8`MATLAB: $(PWD)/$* Done!`tput sgr0`"
 
 %.o.trs %.o.log: %.mod
-	DYNARE_VERSION="$(PACKAGE_VERSION)" TOP_TEST_DIR="$(PWD)" FILESTEM="$*" \
+	@echo "`tput bold``tput setaf 8`OCTAVE: $(PWD)/$*... `tput sgr0`"
+	@DYNARE_VERSION="$(PACKAGE_VERSION)" TOP_TEST_DIR="$(PWD)" FILESTEM="$*" \
 		$(OCTAVE) --no-init-file --silent --no-history run_test_octave.m > $*.o.log 2>&1
+	@if grep -q ":test-result: PASS" $*.o.trs; then \
+	echo "`tput bold``tput setaf 2`OCTAVE: $(PWD)/$* PASSED!`tput sgr0`" ; \
+	else \
+	echo "`tput bold``tput setaf 1`OCTAVE: $(PWD)/$* FAILED!`tput sgr0`" ; \
+	fi
+
+%.o.drs %.o.log: %.mod %.o.trs
+	@cat $*.o.log
 
 %.o.trs %.o.log : %.m
-	DYNARE_VERSION="$(PACKAGE_VERSION)" TOP_TEST_DIR="$(PWD)" \
+	@echo "`tput bold``tput setaf 8`OCTAVE: $(PWD)/$*... `tput sgr0`"
+	@DYNARE_VERSION="$(PACKAGE_VERSION)" TOP_TEST_DIR="$(PWD)" \
 		$(OCTAVE) --no-init-file --silent --no-history $< > $*.o.log 2>&1
+	@echo "`tput bold``tput setaf 8`OCTAVE: $(PWD)/$* Done!`tput sgr0`"
+
+%.m.tls : %.m
+	@echo "`tput bold``tput setaf 8`MATLAB: $(PWD)/$*... `tput sgr0`"
+	@TOP_TEST_DIR="$(PWD)" FILESTEM="$*" \
+		$(MATLAB)/bin/matlab -nosplash -nodisplay -r run_m_script 2> /dev/null
+	@touch $*.m.tls
+	@echo "`tput bold`MATLAB`tput setaf 8`: $(PWD)/$* Done!`tput sgr0`"
+
+%.o.tls : %.m
+	@echo "`tput bold``tput setaf 8`OCTAVE: $(PWD)/$*... `tput sgr0`"
+	@TOP_TEST_DIR="$(PWD)"  FILESTEM="$*" \
+		$(OCTAVE) --no-init-file --silent --no-history run_o_script.m 2>&1
+	@touch $*.o.tls
+	@echo "`tput bold``tput setaf 8`OCTAVE: $(PWD)/$* Done!`tput sgr0`"
 
 clean-local:
 	rm -f $(M_TRS_FILES) \
+		$(M_TLS_FILES) \
 		$(M_XFAIL_TRS_FILES) \
 		$(O_TRS_FILES) \
+		$(O_TLS_FILES) \
 		$(O_XFAIL_TRS_FILES) \
 		$(patsubst %.trs, %.log, $(M_TRS_FILES)) \
 		$(patsubst %.trs, %.log, $(M_XFAIL_TRS_FILES)) \
@@ -472,3 +560,5 @@ clean-local:
 		ms-sbvar/tmv_rr_tr
 
 	rm -f estimation/test_matrix.mat
+
+	rm -f initval_file/ramst_initval_file_data_col_vec_mat.mat initval_file/ramst_initval_file_data_row_vec_mat.mat initval_file/ramst_initval_file_excel.xls
diff --git a/tests/fs2000/fs2000_cmaes.mod b/tests/analytic_derivatives/fs2000_analytic_derivation.mod
similarity index 60%
rename from tests/fs2000/fs2000_cmaes.mod
rename to tests/analytic_derivatives/fs2000_analytic_derivation.mod
index 5ef75a76b84490e28d86bc7b6923d7a8558571ff..3dc8b7ad04c429b1c54f9a878de77d3d6540673e 100644
--- a/tests/fs2000/fs2000_cmaes.mod
+++ b/tests/analytic_derivatives/fs2000_analytic_derivation.mod
@@ -1,4 +1,4 @@
-// See fs2000.mod in the examples/ directory for details on the model
+// 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;
@@ -61,7 +61,7 @@ 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;
+rho, beta_pdf, 0.129, 0.1;
 psi, beta_pdf, 0.65, 0.05;
 del, beta_pdf, 0.01, 0.005;
 stderr e_a, inv_gamma_pdf, 0.035449, inf;
@@ -72,4 +72,9 @@ varobs gp_obs gy_obs;
 
 options_.solve_tolf = 1e-12;
 
-estimation(order=1,datafile=fsdat_simul,nobs=192,loglinear,mode_compute=9,mh_replic=0);
+estimation(order=1,mode_compute=5,analytic_derivation,kalman_algo=1,datafile=fsdat_simul,nobs=192,mh_replic=0,mh_nblocks=2,mh_jscale=0.8);
+estimation(order=1,mode_compute=5,analytic_derivation,kalman_algo=2,datafile=fsdat_simul,nobs=192,mh_replic=0,mh_nblocks=2,mh_jscale=0.8);
+estimation(order=1,mode_compute=4,analytic_derivation,kalman_algo=1,datafile=fsdat_simul,nobs=192,mh_replic=0,mh_nblocks=2,mh_jscale=0.8);
+estimation(order=1,mode_compute=4,analytic_derivation,kalman_algo=2,datafile=fsdat_simul,nobs=192,mh_replic=0,mh_nblocks=2,mh_jscale=0.8);
+//estimation(order=1,mode_compute=5,analytic_derivation,kalman_algo=3,datafile=fsdat_simul,nobs=192,mh_replic=0,mh_nblocks=2,mh_jscale=0.8);
+//estimation(order=1,mode_compute=5,analytic_derivation,kalman_algo=4,datafile=fsdat_simul,nobs=192,mh_replic=0,mh_nblocks=2,mh_jscale=0.8);
\ No newline at end of file
diff --git a/tests/analytic_derivatives/fsdat_simul.m b/tests/analytic_derivatives/fsdat_simul.m
new file mode 100644
index 0000000000000000000000000000000000000000..d4f4a8066f17ba49faad004256693ebc1b9b01e9
--- /dev/null
+++ b/tests/analytic_derivatives/fsdat_simul.m
@@ -0,0 +1,828 @@
+gy_obs          =[
+      1.0030045
+     0.99990934
+      1.0172778
+     0.99464043
+      1.0253423
+      1.0150215
+     0.97772557
+     0.97832186
+      1.0159561
+      1.0085937
+      1.0102649
+      1.0007604
+      1.0112596
+      1.0163279
+      1.0173204
+      1.0103896
+      1.0006493
+     0.99447124
+      1.0196405
+      1.0089304
+     0.99650737
+      1.0139707
+     0.97865842
+      1.0192225
+     0.99139628
+      1.0141362
+      1.0196612
+     0.97483476
+     0.99686151
+     0.99594464
+      1.0000642
+      1.0172243
+      1.0025773
+     0.97199728
+      1.0217815
+      1.0219949
+     0.99490252
+      1.0190728
+      1.0111337
+      1.0003792
+     0.98969164
+       1.010438
+      1.0216309
+      1.0016671
+      1.0357588
+     0.98803787
+      1.0093457
+      1.0177035
+     0.98548204
+      1.0274294
+      1.0141377
+      1.0091174
+     0.96427632
+      1.0083272
+      1.0007882
+     0.99038262
+      1.0031336
+     0.99500213
+     0.98203716
+      0.9889452
+       1.011632
+     0.99451949
+     0.97291047
+     0.98750871
+     0.99992418
+     0.97657318
+     0.99930448
+      1.0008515
+      1.0044064
+     0.98133792
+      1.0091702
+      1.0087023
+      1.0119876
+      1.0143019
+      1.0311061
+     0.99340471
+      1.0057428
+     0.99197259
+      1.0071019
+     0.99448853
+      1.0061819
+      1.0070088
+      0.9950913
+      1.0302318
+      0.9817693
+      1.0072885
+     0.97355282
+     0.98782586
+      1.0136674
+     0.99863956
+      1.0205668
+     0.99611384
+      1.0073805
+     0.99691529
+      1.0089194
+      1.0030467
+      1.0112006
+      1.0260523
+     0.97803331
+     0.99423374
+      1.0043727
+      1.0140173
+      1.0111473
+     0.99524348
+     0.99775943
+      0.9958619
+      0.9982344
+      1.0210212
+      1.0022288
+      1.0014801
+       1.011456
+      1.0124871
+     0.99843599
+     0.99324886
+     0.99912838
+       1.003327
+      1.0072071
+      1.0115223
+       1.009266
+      1.0070554
+      1.0129916
+      1.0053413
+      1.0051638
+     0.99212952
+      1.0214422
+     0.98716707
+     0.99905788
+     0.98877357
+     0.98568476
+     0.99767393
+      1.0061791
+     0.98423439
+     0.99492949
+     0.98786999
+     0.99754239
+      1.0168619
+     0.99472384
+      1.0041658
+     0.98123181
+      1.0112882
+     0.99245422
+      1.0010255
+      1.0017799
+      1.0089968
+      1.0072824
+     0.99768475
+      1.0044726
+      1.0118678
+      1.0056385
+      1.0276965
+      1.0025122
+      1.0065161
+      1.0234338
+     0.99760167
+     0.98922272
+      1.0101918
+       1.011615
+      1.0085286
+      1.0074455
+     0.98866757
+     0.99959012
+      1.0129881
+     0.99127881
+     0.97971901
+      1.0185314
+       1.020054
+      1.0132605
+     0.98063643
+     0.99490253
+      1.0101531
+      1.0004526
+      1.0059109
+     0.98974491
+      1.0062391
+      1.0216488
+     0.99398446
+     0.97786609
+      1.0019274
+     0.99587153
+      1.0095881
+      1.0111887
+     0.99457649
+     0.97896734
+       1.000172
+      1.0142951
+      1.0034224
+      1.0037242
+      1.0016059
+       1.016556
+     0.99687023
+      1.0117844
+      1.0059212
+     0.98083159
+     0.98638851
+      1.0128713
+      1.0096232
+      1.0115891
+      1.0011213
+      1.0147105
+      1.0066344
+      1.0164429
+     0.99825038
+     0.99403411
+
+];
+
+gp_obs          =[
+      1.0079715
+      1.0074573
+      1.0153107
+      1.0152677
+      1.0011653
+     0.99950061
+      1.0328311
+      1.0192317
+       1.009827
+     0.99588916
+       1.007474
+      1.0113061
+     0.98696624
+     0.99978663
+     0.98240542
+     0.98861723
+     0.99008763
+      1.0185076
+      1.0052452
+     0.99447194
+      1.0092685
+        1.01208
+      1.0105237
+     0.98513875
+      1.0165628
+     0.99485934
+      1.0050255
+      1.0140756
+      1.0093128
+      1.0155868
+      1.0107023
+     0.99212762
+      1.0095465
+      1.0028435
+      1.0069437
+      1.0070473
+      1.0145902
+      1.0186922
+      1.0059917
+      1.0113072
+      1.0107386
+     0.99769196
+     0.99793444
+      1.0050791
+     0.98307821
+      1.0107594
+     0.99689982
+     0.98667064
+      0.9991662
+     0.98274722
+     0.98422032
+     0.99393016
+      1.0118567
+     0.99912781
+      1.0023744
+      1.0086662
+      1.0164773
+      1.0169327
+      1.0372478
+      1.0314242
+      1.0004256
+      1.0110541
+      1.0076575
+      1.0119851
+      1.0055188
+      1.0213959
+      1.0234416
+      1.0264917
+      1.0292725
+      1.0385184
+      1.0200999
+      1.0107697
+       1.008583
+      1.0200332
+      1.0030413
+      1.0108659
+      1.0185145
+      1.0168619
+      1.0180462
+      1.0239657
+      1.0205509
+      1.0189973
+      1.0246446
+      1.0135089
+      1.0352973
+      1.0099289
+      1.0266474
+      1.0279829
+      1.0101653
+       1.041216
+      1.0103861
+      1.0114727
+      1.0054605
+      1.0190722
+      1.0114837
+      1.0179213
+       1.006082
+      1.0049696
+      1.0143629
+      0.9971036
+      1.0005602
+      1.0078403
+      1.0240222
+      1.0195063
+      1.0355136
+      1.0218743
+      1.0171331
+      1.0049817
+      1.0140974
+      1.0168431
+      1.0049966
+      1.0045568
+      1.0156414
+      1.0273055
+      1.0197653
+      1.0030624
+      1.0154993
+     0.99782084
+     0.99711648
+       1.014408
+      1.0057417
+     0.99936837
+      1.0096934
+      1.0095138
+      1.0057734
+      1.0114497
+      1.0059784
+      1.0328889
+      1.0098032
+      1.0041114
+      1.0101247
+      1.0181588
+      1.0115712
+      1.0227509
+      1.0065104
+      1.0110902
+      1.0298169
+      1.0089532
+      1.0368733
+      1.0123033
+      1.0060763
+      1.0150937
+      1.0239325
+     0.99555536
+     0.99861271
+      1.0076201
+     0.99941535
+      1.0119522
+      1.0129183
+     0.99288924
+      1.0260784
+      1.0144982
+      1.0121985
+      1.0234916
+        1.02215
+      1.0190118
+      1.0172679
+      1.0118398
+      1.0002123
+      1.0092124
+      1.0071943
+     0.99508468
+      1.0019303
+      1.0030733
+      0.9964198
+      1.0027298
+     0.99797614
+       1.006942
+     0.99793928
+      1.0083214
+      1.0283732
+      1.0111102
+       1.016936
+      1.0229061
+     0.98846454
+      1.0015387
+      1.0201769
+      1.0079822
+      1.0064007
+      1.0095543
+      1.0092207
+      1.0135485
+      1.0198974
+      1.0140252
+      1.0128686
+      1.0092903
+      1.0141974
+      1.0023492
+     0.99731455
+      1.0026598
+     0.99303643
+      1.0036469
+      1.0160975
+      1.0368378
+      1.0139625
+        1.01493
+      1.0113531
+      1.0114548
+     0.99833441
+     0.99648401
+     0.97645361
+      1.0154053
+        1.01703
+
+];
+
+Y_obs           =[
+              1
+     0.99690484
+      1.0111781
+      1.0028141
+      1.0251518
+      1.0371688
+      1.0118899
+     0.98720726
+      1.0001589
+      1.0057481
+      1.0130085
+      1.0107643
+      1.0190194
+      1.0323428
+      1.0466587
+      1.0540438
+      1.0516886
+      1.0431553
+      1.0597913
+      1.0657172
+      1.0592201
+      1.0701863
+      1.0458402
+      1.0620582
+      1.0504499
+      1.0615817
+      1.0782384
+      1.0500687
+      1.0439257
+      1.0368658
+      1.0339255
+      1.0481453
+      1.0477181
+      1.0167109
+      1.0354878
+      1.0544782
+      1.0463762
+      1.0624445
+      1.0705737
+      1.0679484
+      1.0546356
+      1.0620691
+      1.0806955
+      1.0793581
+      1.1121124
+      1.0971458
+      1.1034869
+      1.1181859
+      1.1006634
+      1.1250883
+      1.1362214
+      1.1423343
+      1.1036061
+      1.1089288
+      1.1067125
+      1.0940906
+      1.0942197
+      1.0862174
+        1.06525
+      1.0511907
+      1.0598182
+      1.0513331
+      1.0212391
+      1.0057433
+       1.002663
+     0.97623167
+     0.97253165
+     0.97037865
+     0.97178055
+     0.95011397
+     0.95627969
+     0.96197747
+     0.97096053
+     0.98225794
+      1.0103595
+      1.0007597
+       1.003498
+     0.99246608
+     0.99656347
+     0.98804749
+     0.99122491
+     0.99522926
+     0.98731605
+      1.0145434
+     0.99330816
+     0.99759216
+     0.96814048
+     0.95296183
+     0.96362471
+     0.95925977
+     0.97682205
+     0.96993138
+      0.9743074
+     0.96821818
+     0.97413308
+      0.9741753
+     0.98237142
+      1.0054193
+     0.98044807
+      0.9716773
+      0.9730455
+     0.98405828
+     0.99220103
+     0.98444001
+     0.97919493
+     0.97205233
+     0.96728223
+     0.98529893
+     0.98452324
+     0.98299888
+     0.99145042
+       1.000933
+     0.99636447
+     0.98660883
+     0.98273271
+     0.98305518
+     0.98725774
+     0.99577549
+       1.002037
+      1.0060879
+       1.016075
+      1.0184118
+      1.0205711
+      1.0096961
+      1.0281337
+      1.0122963
+      1.0083497
+     0.99411874
+       0.976799
+     0.97146842
+     0.97464304
+     0.95587292
+     0.94779791
+     0.93266339
+     0.92720128
+     0.94105864
+     0.93277798
+     0.93393927
+     0.91216657
+     0.92045028
+         0.9099
+     0.90792098
+     0.90669634
+     0.91268867
+     0.91696661
+     0.91164685
+     0.91311495
+     0.92197825
+     0.92461222
+     0.94930422
+      0.9488119
+     0.95232353
+     0.97275278
+     0.96734995
+     0.95356817
+     0.96075548
+     0.96936594
+     0.97489002
+     0.97933106
+     0.96499412
+     0.96157973
+     0.97156334
+     0.95983765
+     0.93655215
+     0.95207909
+     0.96912862
+     0.97938462
+     0.95701655
+     0.94891457
+     0.95606317
+     0.95351125
+     0.95641767
+     0.94315807
+     0.94639265
+     0.96503697
+     0.95601693
+     0.93087851
+     0.92980141
+     0.92266844
+     0.92925206
+     0.93743628
+     0.92900826
+      0.9049711
+     0.90213859
+     0.91342916
+     0.91384707
+     0.91456681
+     0.91316822
+     0.92671976
+     0.92058549
+     0.92936541
+     0.93228212
+     0.91010921
+     0.89349322
+     0.90336005
+     0.90997873
+     0.91856328
+     0.91668007
+     0.92838606
+       0.932016
+     0.94545438
+     0.94070026
+     0.93172987
+
+];
+
+P_obs           =[
+              1
+     0.99948573
+      1.0068249
+      1.0141211
+      1.0073149
+     0.99884398
+      1.0237035
+      1.0349636
+       1.036819
+      1.0247366
+      1.0242391
+      1.0275737
+      1.0065684
+     0.99838346
+     0.97281734
+     0.95346302
+      0.9355791
+      0.9461152
+     0.94338882
+     0.92988921
+      0.9311862
+     0.93529467
+     0.93784681
+     0.91501401
+     0.92360522
+     0.91049302
+     0.90754698
+     0.91365103
+     0.91499228
+     0.92260749
+     0.92533824
+     0.90949431
+     0.91106924
+     0.90594116
+     0.90491334
+      0.9039891
+     0.91060772
+     0.92132842
+     0.91934854
+     0.92268418
+     0.92545127
+     0.91517169
+     0.90513459
+     0.90224212
+     0.87734878
+     0.88013667
+     0.86906494
+     0.84776403
+     0.83895869
+     0.81373437
+     0.78998314
+     0.77594176
+     0.77982695
+     0.77098321
+     0.76538611
+     0.76608075
+     0.77458654
+     0.78354767
+     0.81282389
+     0.83627649
+     0.82873051
+     0.83181309
+     0.83149903
+     0.83551261
+     0.83305985
+     0.84648418
+     0.86195421
+     0.88047436
+     0.90177533
+     0.93232215
+     0.94445051
+      0.9472487
+     0.94786015
+     0.95992178
+     0.95499149
+     0.95788581
+      0.9684288
+     0.97731917
+     0.98739379
+      1.0033879
+      1.0159673
+      1.0269931
+      1.0436661
+      1.0492034
+      1.0765292
+      1.0784865
+      1.0971624
+      1.1171737
+      1.1193675
+      1.1526119
+      1.1550265
+      1.1585277
+      1.1560166
+      1.1671172
+      1.1706294
+      1.1805791
+      1.1786896
+      1.1756876
+      1.1820789
+       1.171211
+      1.1637997
+      1.1636684
+       1.179719
+      1.1912538
+      1.2187959
+      1.2326986
+      1.2418602
+      1.2388704
+      1.2449963
+      1.2538678
+      1.2508929
+      1.2474781
+       1.255148
+       1.274482
+      1.2862757
+      1.2813665
+      1.2888943
+      1.2787436
+      1.2678886
+       1.274325
+      1.2720952
+       1.263492
+      1.2652139
+      1.2667561
+       1.264558
+      1.2680362
+      1.2660431
+      1.2909605
+      1.2927921
+       1.288932
+      1.2910852
+      1.3012725
+      1.3048721
+      1.3196515
+      1.3181903
+       1.321309
+      1.3431543
+       1.344136
+      1.3730377
+      1.3773695
+      1.3754742
+      1.3825964
+      1.3985574
+      1.3861412
+      1.3767823
+      1.3764309
+      1.3678747
+      1.3718554
+      1.3768022
+      1.3617199
+      1.3798267
+      1.3863533
+      1.3905803
+      1.4061004
+      1.4202788
+      1.4313191
+      1.4406155
+      1.4444837
+      1.4367244
+      1.4379653
+      1.4371881
+      1.4243012
+        1.41826
+      1.4133617
+        1.40181
+      1.3965683
+      1.3865729
+      1.3855433
+      1.3755111
+      1.3758609
+      1.3962625
+      1.3994012
+      1.4083656
+      1.4233002
+      1.4037932
+      1.3973604
+      1.4095657
+      1.4095764
+      1.4080055
+      1.4095882
+      1.4108374
+      1.4164143
+      1.4283402
+      1.4343939
+      1.4392909
+      1.4406097
+      1.4468355
+      1.4412132
+      1.4305562
+      1.4252445
+      1.4103094
+      1.4059847
+      1.4141106
+      1.4429769
+      1.4489679
+      1.4559263
+      1.4593079
+      1.4627911
+       1.453154
+      1.4416665
+      1.4101485
+      1.4175823
+      1.4266407
+
+];
+
diff --git a/tests/deterministic_simulations/rbc_det_exo_lag_2a.mod b/tests/deterministic_simulations/rbc_det_exo_lag_2a.mod
new file mode 100644
index 0000000000000000000000000000000000000000..b831cfdda7d82e059daad123bcb658de0c930aca
--- /dev/null
+++ b/tests/deterministic_simulations/rbc_det_exo_lag_2a.mod
@@ -0,0 +1,75 @@
+var Capital, Output, Labour, Consumption, Efficiency, efficiency, ExpectedTerm;
+
+varexo EfficiencyInnovation;
+
+parameters beta, theta, tau, alpha, psi, delta, rho, effstar, sigma2;
+
+beta    =   0.9900;
+theta   =   0.3570;
+tau     =   2.0000;
+alpha   =   0.4500;
+psi     =  -0.1000;
+delta   =   0.0200;
+rho     =   0.8000;
+effstar =   1.0000;
+sigma2  =   0;
+
+model;
+
+  // Eq. n°1:
+  efficiency = rho*efficiency(-1) + EfficiencyInnovation;
+
+  // Eq. n°2:
+  Efficiency = effstar*exp(efficiency);
+
+  // Eq. n°3:
+  Output = Efficiency*(alpha*(Capital(-1)^psi)+(1-alpha)*(Labour^psi))^(1/psi);
+
+  // Eq. n°4:
+  Capital = Output-Consumption + (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;
+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;
+
+% 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;
+Efficiency=effstar;
+efficiency=0;
+ExpectedTerm=beta*((((Consumption^theta)*((1-Labour)^(1-theta)))^(1-tau))/Consumption)
+             *(alpha*((Output/Capital)^(1-psi))+1-delta);
+LagrangeMultiplier=0;
+end;
+
+//steady;
+
+shocks;
+var EfficiencyInnovation;
+periods 3;
+values -0.1;
+end;
+
+simul(periods=300);
+
+rplot Consumption;
+rplot Capital;
\ No newline at end of file
diff --git a/tests/deterministic_simulations/rbc_det_exo_lag_2b.mod b/tests/deterministic_simulations/rbc_det_exo_lag_2b.mod
new file mode 100644
index 0000000000000000000000000000000000000000..d59a8e61333bf1271388448c760f5fac1f26912e
--- /dev/null
+++ b/tests/deterministic_simulations/rbc_det_exo_lag_2b.mod
@@ -0,0 +1,80 @@
+// check exogenous variable lag > 1 with *.m file
+var Capital, Output, Labour, Consumption, Efficiency, efficiency, ExpectedTerm;
+
+varexo EfficiencyInnovation;
+
+parameters beta, theta, tau, alpha, psi, delta, rho, effstar, sigma2;
+
+beta    =   0.9900;
+theta   =   0.3570;
+tau     =   2.0000;
+alpha   =   0.4500;
+psi     =  -0.1000;
+delta   =   0.0200;
+rho     =   0.8000;
+effstar =   1.0000;
+sigma2  =   0;
+
+model;
+
+  // Eq. n°1:
+  efficiency = rho*efficiency(-1) + EfficiencyInnovation(-2);
+
+  // Eq. n°2:
+  Efficiency = effstar*exp(efficiency);
+
+  // Eq. n°3:
+  Output = Efficiency*(alpha*(Capital(-1)^psi)+(1-alpha)*(Labour^psi))^(1/psi);
+
+  // Eq. n°4:
+  Capital = Output-Consumption + (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;
+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;
+
+% 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;
+Efficiency=effstar;
+efficiency=0;
+ExpectedTerm=beta*((((Consumption^theta)*((1-Labour)^(1-theta)))^(1-tau))/Consumption)
+             *(alpha*((Output/Capital)^(1-psi))+1-delta);
+LagrangeMultiplier=0;
+end;
+
+//steady;
+
+shocks;
+var EfficiencyInnovation;
+periods 1;
+values -0.1;
+end;
+
+simul(periods=300);
+
+rplot Consumption;
+rplot Capital;
+
+O=load('rbc_det_exo_lag_2a_results');
+
+fataltest(oo_.endo_simul(:,2:end),O.oo_.endo_simul);
\ No newline at end of file
diff --git a/tests/deterministic_simulations/rbc_det_exo_lag_2c.mod b/tests/deterministic_simulations/rbc_det_exo_lag_2c.mod
new file mode 100644
index 0000000000000000000000000000000000000000..fd702410904fcc8722cd14b30f503c9d851d214d
--- /dev/null
+++ b/tests/deterministic_simulations/rbc_det_exo_lag_2c.mod
@@ -0,0 +1,80 @@
+// check exogenous variable lag > 1 with block+bytecode
+var Capital, Output, Labour, Consumption, Efficiency, efficiency, ExpectedTerm;
+
+varexo EfficiencyInnovation;
+
+parameters beta, theta, tau, alpha, psi, delta, rho, effstar, sigma2;
+
+beta    =   0.9900;
+theta   =   0.3570;
+tau     =   2.0000;
+alpha   =   0.4500;
+psi     =  -0.1000;
+delta   =   0.0200;
+rho     =   0.8000;
+effstar =   1.0000;
+sigma2  =   0;
+
+model(block,bytecode,cutoff=0);
+
+  // Eq. n°1:
+  efficiency = rho*efficiency(-1) + EfficiencyInnovation(-2);
+
+  // Eq. n°2:
+  Efficiency = effstar*exp(efficiency);
+
+  // Eq. n°3:
+  Output = Efficiency*(alpha*(Capital(-1)^psi)+(1-alpha)*(Labour^psi))^(1/psi);
+
+  // Eq. n°4:
+  Capital = Output-Consumption + (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;
+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;
+
+% 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;
+Efficiency=effstar;
+efficiency=0;
+ExpectedTerm=beta*((((Consumption^theta)*((1-Labour)^(1-theta)))^(1-tau))/Consumption)
+             *(alpha*((Output/Capital)^(1-psi))+1-delta);
+LagrangeMultiplier=0;
+end;
+
+//steady;
+
+shocks;
+var EfficiencyInnovation;
+periods 1;
+values -0.1;
+end;
+
+simul(periods=300);
+
+rplot Consumption;
+rplot Capital;
+
+O=load('rbc_det_exo_lag_2a_results');
+
+fataltest(oo_.endo_simul(:,2:end),O.oo_.endo_simul);
\ No newline at end of file
diff --git a/tests/deterministic_simulations/sim_several_leads_lags.mod b/tests/deterministic_simulations/sim_several_leads_lags.mod
new file mode 100644
index 0000000000000000000000000000000000000000..058315bd30d180ab800c673b27608033f87479a1
--- /dev/null
+++ b/tests/deterministic_simulations/sim_several_leads_lags.mod
@@ -0,0 +1,35 @@
+var c k z_forward z_backward;
+varexo x z_shock;
+
+parameters alph gam delt bet aa;
+alph=0.5;
+gam=0.5;
+delt=0.02;
+bet=0.05;
+aa=0.5;
+
+model;
+c + k - aa*x*k(-1)^alph - (1-delt)*k(-1); // Resource constraint
+c^(-gam) - (1+bet)^(-1)*(aa*alph*x(+1)*k^(alph-1) + 1 - delt)*c(+1)^(-gam); // Euler equation
+z_backward=0.1*1+0.3*z_backward(-1)+0.3*z_backward(-2)+0.3*z_backward(-3)+(x(-4)-1);
+z_forward=0.1*1+0.45*z_forward(+1)+0.45*z_forward(+2)+(x(+4)-1);
+end;
+
+initval;
+c = 1.2;
+k = 12;
+x = 1;
+end;
+
+histval;
+x(-1)=1.30;
+x(-2)=1.30;
+end;
+
+shocks;
+var x;
+periods 2;
+values 0.9;
+end;
+
+simul(periods=200,maxit=100);
\ No newline at end of file
diff --git a/tests/differentiate_forward_vars/RBC_differentiate_forward.mod b/tests/differentiate_forward_vars/RBC_differentiate_forward.mod
new file mode 100644
index 0000000000000000000000000000000000000000..f95c85404dcf38b29a99341fe3dd67f5f5e43f21
--- /dev/null
+++ b/tests/differentiate_forward_vars/RBC_differentiate_forward.mod
@@ -0,0 +1,92 @@
+/*
+* This model shows how to use the  differentiate_forward_vars option to simulate 
+* perfect foresight models  when the steady state is unknown
+* or when the model is very persistent. In this file, we  consider an  RBC model  
+* with a  CES technology  and  very  persistent  productivity shock. We set the 
+* autoregressive  parameter of this exogenous productivity  to 0.999, so that 
+* in period 400 the level of productivity,  after an  initial one percent shock,  
+* is still  0.67\% above its steady state level.  
+*
+* Written by Stéphane Adjemian. For more information, see 
+* http://gitlab.ithaca.fr/Dynare/differentiate-forward-variables
+*/
+var Capital, Output, Labour, Consumption, Efficiency, efficiency, ExpectedTerm;
+
+varexo EfficiencyInnovation;
+
+parameters beta, theta, tau, alpha, psi, delta, rho, effstar, sigma;
+
+/*
+** Calibration
+*/
+
+beta    =  0.990;
+theta   =  0.357;
+tau     =  30.000;
+alpha   =  0.450;
+psi     =  -1.000; // So that the elasticity of substitution between inputs is 1/(1-psi)=1/10
+delta   =  0.020;
+rho     =  0.999;
+effstar =  1.000;
+sigma   =  0.010;
+
+model(differentiate_forward_vars);
+
+  // Eq. n°1:
+  efficiency = rho*efficiency(-1) + sigma*EfficiencyInnovation;
+
+  // Eq. n°2:
+  Efficiency = effstar*exp(efficiency);
+
+  // Eq. n°3:
+  Output = Efficiency*(alpha*(Capital(-1)^psi)+(1-alpha)*(Labour^psi))^(1/psi);
+
+  // Eq. n°4:
+  Consumption + Capital - Output - (1-delta)*Capital(-1);
+
+  // Eq. n°5:
+  ((1-theta)/theta)*(Consumption/(1-Labour)) - (1-alpha)*(Output/Labour)^(1-psi);
+
+  // Eq. n°6:
+  (((Consumption^theta)*((1-Labour)^(1-theta)))^(1-tau))/Consumption - ExpectedTerm(1);
+
+  // Eq. n°7:
+  ExpectedTerm = beta*((((Consumption^theta)*((1-Labour)^(1-theta)))^(1-tau))/Consumption)*(alpha*((Output/Capital(-1))^(1-psi))+1-delta);
+
+end;
+
+steady_state_model;
+  
+  efficiency = 0;
+  Efficiency = effstar;
+  
+  // Compute some 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;
+periods 1;
+values 1;
+end;
+
+steady;
+check;
+
+simul(periods=500);
diff --git a/tests/estimation/MH_recover/fs2000_recover.mod b/tests/estimation/MH_recover/fs2000_recover.mod
new file mode 100644
index 0000000000000000000000000000000000000000..bfb7b68d0416081562215d638c620d29334c77b3
--- /dev/null
+++ b/tests/estimation/MH_recover/fs2000_recover.mod
@@ -0,0 +1,139 @@
+/*
+ * This file replicates the estimation of the cash in advance model described
+ * Frank Schorfheide (2000): "Loss function-based evaluation of DSGE models",
+ * Journal of Applied Econometrics, 15(6), 645-670.
+ *
+ * The data are in file "fsdat_simul.m", and have been artificially generated.
+ * They are therefore different from the original dataset used by Schorfheide.
+ *
+ * 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.
+ *
+ * This implementation was written by Michel Juillard. Please note that the
+ * following copyright notice only applies to this Dynare implementation of the
+ * model.
+ */
+
+/*
+ * 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/>.
+ */
+
+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;
+
+shocks;
+var e_a; stderr 0.014;
+var e_m; stderr 0.005;
+end;
+
+steady_state_model;
+  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;
+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_.MaxNumberOfBytes=2000*11*8/4;
+estimation(order=1, datafile='../fsdat_simul',nobs=192, loglinear, mh_replic=2000, mh_nblocks=2, mh_jscale=0.8);
+copyfile([M_.dname filesep 'metropolis' filesep 'fs2000_recover_mh1_blck1.mat'],'fs2000_mh1_blck1.mat')
+copyfile([M_.dname filesep 'metropolis' filesep 'fs2000_recover_mh3_blck2.mat'],'fs2000_mh3_blck2.mat')
+delete([M_.dname filesep 'metropolis' filesep 'fs2000_recover_mh4_blck2.mat'])
+
+estimation(order=1, datafile='../fsdat_simul',mode_compute=0,mode_file=fs2000_recover_mode, nobs=192, loglinear, mh_replic=2000, mh_nblocks=2, mh_jscale=0.8,mh_recover);
+
+%check first unaffected chain
+temp1=load('fs2000_mh1_blck1.mat');
+temp2=load([M_.dname filesep 'Metropolis' filesep 'fs2000_recover_mh1_blck1.mat']);
+
+if max(max(temp1.x2-temp2.x2))>1e-10
+    error('Draws of unaffected chain are not the same')
+end
+
+%check second, affected chain with last unaffected file
+temp1=load('fs2000_mh3_blck2.mat');
+temp2=load([M_.dname filesep 'Metropolis' filesep 'fs2000_recover_mh3_blck2.mat']);
+
+if max(max(temp1.x2-temp2.x2))>1e-10
+    error('Draws of affected chain''s unaffected files are not the same')
+end
diff --git a/tests/estimation/t_proposal/fs2000_student.mod b/tests/estimation/t_proposal/fs2000_student.mod
new file mode 100644
index 0000000000000000000000000000000000000000..e920b105aa4e1bb00bc6641a032a435343e02753
--- /dev/null
+++ b/tests/estimation/t_proposal/fs2000_student.mod
@@ -0,0 +1,117 @@
+/*
+ * This file replicates the estimation of the cash in advance model described
+ * Frank Schorfheide (2000): "Loss function-based evaluation of DSGE models",
+ * Journal of Applied Econometrics, 15(6), 645-670.
+ *
+ * The data are in file "fsdat_simul.m", and have been artificially generated.
+ * They are therefore different from the original dataset used by Schorfheide.
+ *
+ * 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.
+ *
+ * This implementation was written by Michel Juillard. Please note that the
+ * following copyright notice only applies to this Dynare implementation of the
+ * model.
+ */
+
+/*
+ * Copyright (C) 2004-2015 Dynare Team
+ *
+ * This file is part of Dynare.
+ *
+ * Dynare is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * Dynare is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+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;
+
+shocks;
+var e_a; stderr 0.014;
+var e_m; stderr 0.005;
+end;
+
+steady_state_model;
+  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;
+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',nobs=192, loglinear, mh_replic=2002, mh_nblocks=2, mh_jscale=0.8,mode_compute=4, proposal_distribution=rand_multivariate_studuuent, student_degrees_of_freedom=5);
diff --git a/tests/expectations/expectation.mod b/tests/expectations/expectation.mod
index c05d7528d1771ed9ae3fb537d195c1db5a641a91..23a36a0e673f47e25603466a260e122fc95f25fa 100644
--- a/tests/expectations/expectation.mod
+++ b/tests/expectations/expectation.mod
@@ -35,6 +35,8 @@ e = 0;
 u = 0;
 end;
 
+write_latex_original_model;
+
 shocks;
 var e; stderr 0.009;
 var u; stderr 0.009;
diff --git a/tests/test.m b/tests/fataltest.m
similarity index 100%
rename from tests/test.m
rename to tests/fataltest.m
diff --git a/tests/fs2000/fs2000_mode_compute_8.mod b/tests/fs2000/fs2000_mode_compute_8.mod
deleted file mode 100644
index 4f39e10bfed58663ae0ec3e90966d4969f058ec7..0000000000000000000000000000000000000000
--- a/tests/fs2000/fs2000_mode_compute_8.mod
+++ /dev/null
@@ -1,82 +0,0 @@
-// 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,mode_compute=8,loglinear,mh_replic=0,optim=(
-'MaxIter',5000,
-'TolFun',1e-4,
-'TolX',1e-4,
-'MaxFunEvals',5000,
-'MaxFunEvalFactor',500,
-'InitialSimplexSize',0.05
-));
diff --git a/tests/fs2000/fs2000d.mod b/tests/fs2000/fs2000d.mod
deleted file mode 100644
index 04f1228053ffe5d1f28878be21e29dc6bb4f28f0..0000000000000000000000000000000000000000
--- a/tests/fs2000/fs2000d.mod
+++ /dev/null
@@ -1,75 +0,0 @@
-// 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,mode_compute=5,loglinear,mh_replic=0);
diff --git a/tests/fs2000/fs2000e.mod b/tests/fs2000/fs2000e.mod
deleted file mode 100644
index 83416a7917c9c2c6d804bb2f6ec23caf262e1bd5..0000000000000000000000000000000000000000
--- a/tests/fs2000/fs2000e.mod
+++ /dev/null
@@ -1,75 +0,0 @@
-// 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,optim=('NumgradEpsilon',1e-6,'NumgradAlgorithm',3,'MaxIter',100,'InitialInverseHessian','eye(9)*.0001'),loglinear,mh_replic=0);
diff --git a/tests/gsa/ls2003a.mod b/tests/gsa/ls2003a.mod
index fcbd9b75cfb606ff7e5c4510b181ada0f7865400..19d5f88bacb79ec1ae684d3f35291dc985eeb44a 100644
--- a/tests/gsa/ls2003a.mod
+++ b/tests/gsa/ls2003a.mod
@@ -54,11 +54,18 @@ rho_q ,beta_pdf,0.4,0.2;
 rho_A ,beta_pdf,0.5,0.2;
 rho_ys ,beta_pdf,0.8,0.1;
 rho_pies,beta_pdf,0.7,0.15;
-stderr e_R,inv_gamma_pdf,1.2533,0.6551;
-stderr e_q,inv_gamma_pdf,2.5066,1.3103;
-stderr e_A,inv_gamma_pdf,1.2533,0.6551;
-stderr e_ys,inv_gamma_pdf,1.2533,0.6551;
-stderr e_pies,inv_gamma_pdf,1.88,0.9827;
+/*
+stderr e_R,inv_gamma_pdf,(1.2533),(0.6551);
+stderr e_q,inv_gamma_pdf,(2.5066),(1.3103);
+stderr e_A,inv_gamma_pdf,(1.2533),(0.6551);
+stderr e_ys,inv_gamma_pdf,(1.2533),(0.6551);
+stderr e_pies,inv_gamma_pdf,(1.88),(0.9827);
+*/
+stderr e_R,inv_gamma_pdf,(1.2533/3),(0.6551/10);
+stderr e_q,inv_gamma_pdf,(2.5066/3),(1.3103/10);
+stderr e_A,inv_gamma_pdf,(1.2533/3),(0.6551/10);
+stderr e_ys,inv_gamma_pdf,(1.2533/3),(0.6551/10);
+stderr e_pies,inv_gamma_pdf,(1.88/3),(0.9827/10);
 end;
 
 // endogenous prior restrictions
@@ -83,12 +90,21 @@ end;
 moment_calibration;
 //y_obs,y_obs, [0.8 1.1]; //[unconditional variance]
 y_obs,y_obs(-(1:4)), +; //[first year acf]
-@#for ilag in 0:1
-y_obs,R_obs(-@{ilag}), -; //[ccf]
+//y_obs,pie_obs(-4:4), -; //[ccf]
+@#for ilag in -2:2
+y_obs,R_obs(@{ilag}), -; //[ccf]
+@#endfor
+@#for ilag in -4:4
+y_obs,pie_obs(@{ilag}), -; //[ccf]
 @#endfor
 end;
 
-dynare_sensitivity(prior_range=0);
+if isoctave()
+  dynare_sensitivity(prior_range=0, nodisplay, graph_format=(eps));
+else
+  dynare_sensitivity(prior_range=0, nodisplay, graph_format=(fig));
+end
+
 /*
 estimation(datafile='data_ca1.m',first_obs=8,nobs=79,mh_nblocks=2, mode_file = ls2003a_mode,
   prefilter=1,mh_jscale=0.5,mh_replic=5000, mode_compute=0, mh_drop=0.6, bayesian_irf);
diff --git a/tests/ramst_initval_file.mod b/tests/initval_file/ramst_initval_file.mod
similarity index 51%
rename from tests/ramst_initval_file.mod
rename to tests/initval_file/ramst_initval_file.mod
index 192edc9bad44f0d3209594b8df43afa832880e18..f6afae20b43cbed500d583dcd0aff75a6575b77d 100644
--- a/tests/ramst_initval_file.mod
+++ b/tests/initval_file/ramst_initval_file.mod
@@ -23,12 +23,25 @@ c = aa*k^alph-delt*k;
 end;
 
 initval_file(filename = ramst_initval_file_data);
-
 steady;
+perfect_foresight_setup(periods=200);
+perfect_foresight_solver;
+
 
-check;
+initval_file(filename = ramst_initval_file_data_row_vec_mat);
+steady;
+perfect_foresight_setup(periods=200);
+perfect_foresight_solver;
 
-simul(periods=200);
 
-rplot c;
-rplot k;
+initval_file(filename = ramst_initval_file_data_col_vec_mat);
+steady;
+perfect_foresight_setup(periods=200);
+perfect_foresight_solver;
+
+if ispc()
+    initval_file(filename = ramst_initval_file_excel);
+    steady;
+    perfect_foresight_setup(periods=200);
+    perfect_foresight_solver;
+end
diff --git a/tests/initval_file/ramst_initval_file_data.m b/tests/initval_file/ramst_initval_file_data.m
new file mode 100644
index 0000000000000000000000000000000000000000..aa94ecbd3f7af95ec3ce386a2ce27de24b3ecb26
--- /dev/null
+++ b/tests/initval_file/ramst_initval_file_data.m
@@ -0,0 +1,14 @@
+x = vertcat([ 1; 1.2 ], repmat(1, 200, 1));
+k = repmat(12.7551, 202, 1);
+c = repmat(1.53061, 202, 1);
+save('ramst_initval_file_data_col_vec_mat.mat');
+
+if ispc()
+    xlswrite('ramst_initval_file_excel',[x k c],1,'A2');
+    xlswrite('ramst_initval_file_excel',{'x' 'k' 'c'},1,'A1');
+end
+
+c=c';
+k=k';
+x=x';
+save('ramst_initval_file_data_row_vec_mat.mat');
\ No newline at end of file
diff --git a/tests/kalman_filter_smoother/fs2000_smoother_only.mod b/tests/kalman_filter_smoother/fs2000_smoother_only.mod
new file mode 100644
index 0000000000000000000000000000000000000000..f46f06e2cf88a7cc917b9966317bf6a512dddde3
--- /dev/null
+++ b/tests/kalman_filter_smoother/fs2000_smoother_only.mod
@@ -0,0 +1,132 @@
+/*
+ * This file replicates the estimation of the cash in advance model described
+ * Frank Schorfheide (2000): "Loss function-based evaluation of DSGE models",
+ * Journal of Applied Econometrics, 15(6), 645-670.
+ *
+ * The data are in file "fsdat_simul.m", and have been artificially generated.
+ * They are therefore different from the original dataset used by Schorfheide.
+ *
+ * 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.
+ *
+ * This implementation was written by Michel Juillard. Please note that the
+ * following copyright notice only applies to this Dynare implementation of the
+ * model.
+ */
+
+/*
+ * 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/>.
+ */
+
+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_state_model;
+  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;
+end;
+
+steady;
+
+check;
+
+varobs gp_obs gy_obs;
+
+estimation(order=1, datafile=fsdat_simul, mode_compute=0,nobs=192, loglinear, smoother) m P c e W R k d n l gy_obs gp_obs y dA;
+
+
+/*
+ * 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/ms-dsge/test_ms_dsge.mod b/tests/ms-dsge/test_ms_dsge.mod
index e11715b3e43c63ee6b083a5c1852139a61b60e82..51b132adf9275761ba8637b719907f64f23184e5 100644
--- a/tests/ms-dsge/test_ms_dsge.mod
+++ b/tests/ms-dsge/test_ms_dsge.mod
@@ -35,4 +35,6 @@ alpha.options(init=1);
 rho.options(init=1);
 beta.options(init=0.2);
 std(u).options(init=3);
-corr(y,c).options(init=.02);
\ No newline at end of file
+corr(y,c).options(init=.02);
+
+[alpha , beta , rho].prior(shape=beta, mean=[2 3 4], variance=[[1 2 3],[2 3 4]]);
\ No newline at end of file
diff --git a/tests/ms-sbvar/test_global_identification_FAILURE.mod b/tests/ms-sbvar/test_global_identification_FAILURE.mod
new file mode 100644
index 0000000000000000000000000000000000000000..8ff9cfdddc849b27e42e54847977d271adec1421
--- /dev/null
+++ b/tests/ms-sbvar/test_global_identification_FAILURE.mod
@@ -0,0 +1,16 @@
+// same as test_lower_cholesky.mod, but using exclusion syntax
+var R Pie Y;
+
+varobs Y Pie R;
+
+svar_identification;
+exclusion lag 0;
+equation 1, Pie, Y;
+exclusion lag 1;
+equation 2, Y;
+end;
+
+sbvar_global_identification_check(options_);
+
+sbvar(datafile = data,freq=4,initial_year=1959,final_year=2005,nlags=4);
+
diff --git a/tests/ms-sbvar/test_global_identification_OK.mod b/tests/ms-sbvar/test_global_identification_OK.mod
new file mode 100644
index 0000000000000000000000000000000000000000..7e54d9223c74b96284124f8a33923c256edbf0cf
--- /dev/null
+++ b/tests/ms-sbvar/test_global_identification_OK.mod
@@ -0,0 +1,15 @@
+// same as test_lower_cholesky.mod, but using exclusion syntax
+var R Pie Y;
+
+varobs Y Pie R;
+
+svar_identification;
+exclusion lag 0;
+equation 1, Pie, Y;
+equation 2, Y;
+end;
+
+sbvar_global_identification_check(options_);
+
+sbvar(datafile = data,freq=4,initial_year=1959,final_year=2005,nlags=4);
+
diff --git a/tests/optimal_policy/OSR/osr_obj_corr_algo_1.mod b/tests/optimal_policy/OSR/osr_obj_corr_algo_1.mod
new file mode 100644
index 0000000000000000000000000000000000000000..2b8a30406a3baeec9061ff3c2727fa11ed0eed17
--- /dev/null
+++ b/tests/optimal_policy/OSR/osr_obj_corr_algo_1.mod
@@ -0,0 +1,110 @@
+// Example of optimal simple rule using opt_algo=4
+var y inflation r dummy_var;
+varexo y_ inf_;
+
+parameters delta sigma alpha kappa gammax0 gammac0 gamma_y_ gamma_inf_;
+
+delta =  0.44;
+kappa =  0.18;
+alpha =  0.48;
+sigma = -0.06;
+
+
+model(linear);
+y  = delta * y(-1)  + (1-delta)*y(+1)+sigma *(r - inflation(+1)) + y_; 
+inflation  =   alpha * inflation(-1) + (1-alpha) * inflation(+1) + kappa*y + inf_;
+dummy_var=0.9*dummy_var(-1)+0.01*y;
+r = gammax0*y(-1)+gammac0*inflation(-1)+gamma_y_*y_+gamma_inf_*inf_;
+end;
+
+shocks;
+var y_;
+stderr 0.63;
+var inf_;
+stderr 0.4;
+end;
+
+options_.nograph=1;
+options_.nocorr=1;
+osr_params gammax0 gammac0 gamma_y_ gamma_inf_;
+
+if ~isoctave
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+end;
+
+
+gammax0 = 0.2;
+gammac0 = 1.5;
+gamma_y_ = 8;
+gamma_inf_ = 3;
+
+osr(opt_algo=1);
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'));
+        
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+
+%redo computation with covariance specified
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+y,inflation 0.5;
+end;
+
+osr;
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'))+0.5*oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'));
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+
+gammax0=1.35533;
+gammac0=1.39664;
+gamma_y_=16.6667;
+gamma_inf_=9.13199;
+        
+%redo computation with double weight on one covariance 
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+y,inflation 1;
+end;
+
+osr;
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'))+1*oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'));
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+oo_covar_single=oo_;
+
+%redo computation with single weight on both covariances
+
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+y,inflation 0.5;
+inflation,y 0.5;
+end;
+
+osr;
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'))+0.5*oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+0.5*oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'));
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+if abs(oo_.osr.objective_function-oo_covar_single.osr.objective_function)>1e-8
+    error('Objective Function is wrong')
+end
+if max(abs((cell2mat(struct2cell(oo_.osr.optim_params))-cell2mat(struct2cell(oo_covar_single.osr.optim_params)))./cell2mat(struct2cell(oo_.osr.optim_params))))>1e-4
+    error('Parameters should be identical')
+end
+end
\ No newline at end of file
diff --git a/tests/optimal_policy/OSR/osr_obj_corr_algo_3.mod b/tests/optimal_policy/OSR/osr_obj_corr_algo_3.mod
new file mode 100644
index 0000000000000000000000000000000000000000..a54224fc82b68e164886cf358565199a2aff6d14
--- /dev/null
+++ b/tests/optimal_policy/OSR/osr_obj_corr_algo_3.mod
@@ -0,0 +1,109 @@
+// Example of optimal simple rule using opt_algo=4
+var y inflation r dummy_var;
+varexo y_ inf_;
+
+parameters delta sigma alpha kappa gammax0 gammac0 gamma_y_ gamma_inf_;
+
+delta =  0.44;
+kappa =  0.18;
+alpha =  0.48;
+sigma = -0.06;
+
+
+model(linear);
+y  = delta * y(-1)  + (1-delta)*y(+1)+sigma *(r - inflation(+1)) + y_; 
+inflation  =   alpha * inflation(-1) + (1-alpha) * inflation(+1) + kappa*y + inf_;
+dummy_var=0.9*dummy_var(-1)+0.01*y;
+r = gammax0*y(-1)+gammac0*inflation(-1)+gamma_y_*y_+gamma_inf_*inf_;
+end;
+
+shocks;
+var y_;
+stderr 0.63;
+var inf_;
+stderr 0.4;
+end;
+
+options_.nograph=1;
+options_.nocorr=1;
+osr_params gammax0 gammac0 gamma_y_ gamma_inf_;
+
+
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+end;
+
+
+gammax0 = 0.2;
+gammac0 = 1.5;
+gamma_y_ = 8;
+gamma_inf_ = 3;
+
+osr(opt_algo=3);
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'));
+        
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+
+%redo computation with covariance specified
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+y,inflation 0.5;
+end;
+
+osr;
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'))+0.5*oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'));
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+
+gammax0=1.35533;
+gammac0=1.39664;
+gamma_y_=16.6667;
+gamma_inf_=9.13199;
+        
+%redo computation with double weight on one covariance 
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+y,inflation 1;
+end;
+
+osr;
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'))+1*oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'));
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+oo_covar_single=oo_;
+
+%redo computation with single weight on both covariances
+
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+y,inflation 0.5;
+inflation,y 0.5;
+end;
+
+osr;
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'))+0.5*oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+0.5*oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'));
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+if abs(oo_.osr.objective_function-oo_covar_single.osr.objective_function)>1e-8
+    error('Objective Function is wrong')
+end
+if max(abs((cell2mat(struct2cell(oo_.osr.optim_params))-cell2mat(struct2cell(oo_covar_single.osr.optim_params)))./cell2mat(struct2cell(oo_.osr.optim_params))))>1e-4
+    error('Parameters should be identical')
+end
diff --git a/tests/optimal_policy/OSR/osr_obj_corr_algo_4.mod b/tests/optimal_policy/OSR/osr_obj_corr_algo_4.mod
new file mode 100644
index 0000000000000000000000000000000000000000..cbbabab6b1d37eae2a4bedc840a9701b19a1929c
--- /dev/null
+++ b/tests/optimal_policy/OSR/osr_obj_corr_algo_4.mod
@@ -0,0 +1,110 @@
+// Example of optimal simple rule using opt_algo=4
+var y inflation r dummy_var;
+varexo y_ inf_;
+
+parameters delta sigma alpha kappa gammax0 gammac0 gamma_y_ gamma_inf_;
+
+delta =  0.44;
+kappa =  0.18;
+alpha =  0.48;
+sigma = -0.06;
+
+
+model(linear);
+y  = delta * y(-1)  + (1-delta)*y(+1)+sigma *(r - inflation(+1)) + y_; 
+inflation  =   alpha * inflation(-1) + (1-alpha) * inflation(+1) + kappa*y + inf_;
+dummy_var=0.9*dummy_var(-1)+0.01*y;
+r = gammax0*y(-1)+gammac0*inflation(-1)+gamma_y_*y_+gamma_inf_*inf_;
+end;
+
+shocks;
+var y_;
+stderr 0.63;
+var inf_;
+stderr 0.4;
+end;
+
+options_.nograph=1;
+options_.nocorr=1;
+options_.osr.tolf=1e-20;
+osr_params gammax0 gammac0 gamma_y_ gamma_inf_;
+
+
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+end;
+
+
+gammax0 = 0.2;
+gammac0 = 1.5;
+gamma_y_ = 8;
+gamma_inf_ = 3;
+
+osr(opt_algo=4);
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'));
+        
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+
+%redo computation with covariance specified
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+y,inflation 0.5;
+end;
+
+osr;
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'))+0.5*oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'));
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+
+gammax0=1.35533;
+gammac0=1.39664;
+gamma_y_=16.6667;
+gamma_inf_=9.13199;
+        
+%redo computation with double weight on one covariance 
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+y,inflation 1;
+end;
+
+osr;
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'))+1*oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'));
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+oo_covar_single=oo_;
+
+%redo computation with single weight on both covariances
+
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+y,inflation 0.5;
+inflation,y 0.5;
+end;
+
+osr;
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'))+0.5*oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+0.5*oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'));
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+if abs(oo_.osr.objective_function-oo_covar_single.osr.objective_function)>1e-8
+    error('Objective Function is wrong')
+end
+if max(abs((cell2mat(struct2cell(oo_.osr.optim_params))-cell2mat(struct2cell(oo_covar_single.osr.optim_params)))./cell2mat(struct2cell(oo_.osr.optim_params))))>1e-4
+    error('Parameters should be identical')
+end
diff --git a/tests/optimal_policy/OSR/osr_obj_corr_algo_7.mod b/tests/optimal_policy/OSR/osr_obj_corr_algo_7.mod
new file mode 100644
index 0000000000000000000000000000000000000000..d23466728f4c9e7b1c1660a795a386d6f6f151fe
--- /dev/null
+++ b/tests/optimal_policy/OSR/osr_obj_corr_algo_7.mod
@@ -0,0 +1,111 @@
+// Example of optimal simple rule using opt_algo=2
+var y inflation r dummy_var;
+varexo y_ inf_;
+
+parameters delta sigma alpha kappa gammax0 gammac0 gamma_y_ gamma_inf_;
+
+delta =  0.44;
+kappa =  0.18;
+alpha =  0.48;
+sigma = -0.06;
+
+
+model(linear);
+y  = delta * y(-1)  + (1-delta)*y(+1)+sigma *(r - inflation(+1)) + y_; 
+inflation  =   alpha * inflation(-1) + (1-alpha) * inflation(+1) + kappa*y + inf_;
+dummy_var=0.9*dummy_var(-1)+0.01*y;
+r = gammax0*y(-1)+gammac0*inflation(-1)+gamma_y_*y_+gamma_inf_*inf_;
+end;
+
+shocks;
+var y_;
+stderr 0.63;
+var inf_;
+stderr 0.4;
+end;
+
+options_.nograph=1;
+options_.nocorr=1;
+osr_params gammax0 gammac0 gamma_y_ gamma_inf_;
+
+
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+end;
+
+
+gammax0 = 0.2;
+gammac0 = 1.5;
+gamma_y_ = 8;
+gamma_inf_ = 3;
+
+if ~isoctave
+osr(opt_algo=7);
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'));
+        
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+
+%redo computation with covariance specified
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+y,inflation 0.5;
+end;
+
+osr;
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'))+0.5*oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'));
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+
+gammax0=1.35533;
+gammac0=1.39664;
+gamma_y_=16.6667;
+gamma_inf_=9.13199;
+        
+%redo computation with double weight on one covariance 
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+y,inflation 1;
+end;
+
+osr;
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'))+1*oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'));
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+oo_covar_single=oo_;
+
+%redo computation with single weight on both covariances
+
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+y,inflation 0.5;
+inflation,y 0.5;
+end;
+
+osr;
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'))+0.5*oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+0.5*oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'));
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+if abs(oo_.osr.objective_function-oo_covar_single.osr.objective_function)>1e-8
+    error('Objective Function is wrong')
+end
+if max(abs((cell2mat(struct2cell(oo_.osr.optim_params))-cell2mat(struct2cell(oo_covar_single.osr.optim_params)))./cell2mat(struct2cell(oo_.osr.optim_params))))>1e-4
+    error('Parameters should be identical')
+end
+end
\ No newline at end of file
diff --git a/tests/optimal_policy/OSR/osr_obj_corr_algo_8.mod b/tests/optimal_policy/OSR/osr_obj_corr_algo_8.mod
new file mode 100644
index 0000000000000000000000000000000000000000..77d014d2f1e85f8eef3d55f4857b27b3808df1ff
--- /dev/null
+++ b/tests/optimal_policy/OSR/osr_obj_corr_algo_8.mod
@@ -0,0 +1,109 @@
+// Example of optimal simple rule using opt_algo=2
+var y inflation r dummy_var;
+varexo y_ inf_;
+
+parameters delta sigma alpha kappa gammax0 gammac0 gamma_y_ gamma_inf_;
+
+delta =  0.44;
+kappa =  0.18;
+alpha =  0.48;
+sigma = -0.06;
+
+
+model(linear);
+y  = delta * y(-1)  + (1-delta)*y(+1)+sigma *(r - inflation(+1)) + y_; 
+inflation  =   alpha * inflation(-1) + (1-alpha) * inflation(+1) + kappa*y + inf_;
+dummy_var=0.9*dummy_var(-1)+0.01*y;
+r = gammax0*y(-1)+gammac0*inflation(-1)+gamma_y_*y_+gamma_inf_*inf_;
+end;
+
+shocks;
+var y_;
+stderr 0.63;
+var inf_;
+stderr 0.4;
+end;
+
+options_.nograph=1;
+options_.nocorr=1;
+osr_params gammax0 gammac0 gamma_y_ gamma_inf_;
+
+
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+end;
+
+
+gammax0 = 0.2;
+gammac0 = 1.5;
+gamma_y_ = 8;
+gamma_inf_ = 3;
+
+osr(opt_algo=8);
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'));
+        
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+
+%redo computation with covariance specified
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+y,inflation 0.5;
+end;
+
+osr;
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'))+0.5*oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'));
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+
+gammax0=1.35533;
+gammac0=1.39664;
+gamma_y_=16.6667;
+gamma_inf_=9.13199;
+        
+%redo computation with double weight on one covariance 
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+y,inflation 1;
+end;
+
+osr;
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'))+1*oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'));
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+oo_covar_single=oo_;
+
+%redo computation with single weight on both covariances
+
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+y,inflation 0.5;
+inflation,y 0.5;
+end;
+
+osr;
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'))+0.5*oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+0.5*oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'));
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+if abs(oo_.osr.objective_function-oo_covar_single.osr.objective_function)>1e-8
+    error('Objective Function is wrong')
+end
+if max(abs((cell2mat(struct2cell(oo_.osr.optim_params))-cell2mat(struct2cell(oo_covar_single.osr.optim_params)))./cell2mat(struct2cell(oo_.osr.optim_params))))>1e-4
+    error('Parameters should be identical')
+end
diff --git a/tests/optimal_policy/OSR/osr_obj_corr_algo_9.mod b/tests/optimal_policy/OSR/osr_obj_corr_algo_9.mod
new file mode 100644
index 0000000000000000000000000000000000000000..59a2fa250f62137bbd77a12b7920b3dd81c0d3c8
--- /dev/null
+++ b/tests/optimal_policy/OSR/osr_obj_corr_algo_9.mod
@@ -0,0 +1,109 @@
+// Example of optimal simple rule using opt_algo=3
+var y inflation r dummy_var;
+varexo y_ inf_;
+
+parameters delta sigma alpha kappa gammax0 gammac0 gamma_y_ gamma_inf_;
+
+delta =  0.44;
+kappa =  0.18;
+alpha =  0.48;
+sigma = -0.06;
+
+
+model(linear);
+y  = delta * y(-1)  + (1-delta)*y(+1)+sigma *(r - inflation(+1)) + y_; 
+inflation  =   alpha * inflation(-1) + (1-alpha) * inflation(+1) + kappa*y + inf_;
+dummy_var=0.9*dummy_var(-1)+0.01*y;
+r = gammax0*y(-1)+gammac0*inflation(-1)+gamma_y_*y_+gamma_inf_*inf_;
+end;
+
+shocks;
+var y_;
+stderr 0.63;
+var inf_;
+stderr 0.4;
+end;
+
+options_.nograph=1;
+options_.nocorr=1;
+osr_params gammax0 gammac0 gamma_y_ gamma_inf_;
+
+
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+end;
+
+
+gammax0 = 0.2;
+gammac0 = 1.5;
+gamma_y_ = 8;
+gamma_inf_ = 3;
+
+osr(opt_algo=9);
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'));
+        
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+
+%redo computation with covariance specified
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+y,inflation 0.5;
+end;
+
+osr;
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'))+0.5*oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'));
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+
+gammax0=1.35533;
+gammac0=1.39664;
+gamma_y_=16.6667;
+gamma_inf_=9.13199;
+        
+%redo computation with double weight on one covariance 
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+y,inflation 1;
+end;
+
+osr;
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'))+1*oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'));
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+oo_covar_single=oo_;
+
+%redo computation with single weight on both covariances
+
+optim_weights;
+inflation 1;
+y 1;
+dummy_var 1;
+y,inflation 0.5;
+inflation,y 0.5;
+end;
+
+osr;
+%compute objective function manually
+objective=oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'))+oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+oo_.var(strmatch('dummy_var',M_.endo_names,'exact'),strmatch('dummy_var',M_.endo_names,'exact'))+0.5*oo_.var(strmatch('y',M_.endo_names,'exact'),strmatch('inflation',M_.endo_names,'exact'))+0.5*oo_.var(strmatch('inflation',M_.endo_names,'exact'),strmatch('y',M_.endo_names,'exact'));
+if abs(oo_.osr.objective_function-objective)>1e-8
+    error('Objective Function is wrong')
+end
+if abs(oo_.osr.objective_function-oo_covar_single.osr.objective_function)>1e-8
+    error('Objective Function is wrong')
+end
+if max(abs((cell2mat(struct2cell(oo_.osr.optim_params))-cell2mat(struct2cell(oo_covar_single.osr.optim_params)))./cell2mat(struct2cell(oo_.osr.optim_params))))>1e-4
+    error('Parameters should be identical')
+end
diff --git a/tests/optimal_policy/ramsey.mod b/tests/optimal_policy/ramsey_.mod
similarity index 100%
rename from tests/optimal_policy/ramsey.mod
rename to tests/optimal_policy/ramsey_.mod
diff --git a/tests/optimizers/fs2000.common.inc b/tests/optimizers/fs2000.common.inc
new file mode 100644
index 0000000000000000000000000000000000000000..b0762753f7631ef7beeebff7167a36b26a0547cd
--- /dev/null
+++ b/tests/optimizers/fs2000.common.inc
@@ -0,0 +1,133 @@
+/*
+ * This file replicates the estimation of the cash in advance model described
+ * Frank Schorfheide (2000): "Loss function-based evaluation of DSGE models",
+ * Journal of Applied Econometrics, 15(6), 645-670.
+ *
+ * The data are in file "fs2000/fsdat_simul.m", and have been artificially generated.
+ * They are therefore different from the original dataset used by Schorfheide.
+ *
+ * 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.
+ *
+ * This implementation was written by Michel Juillard. Please note that the
+ * following copyright notice only applies to this Dynare implementation of the
+ * model.
+ */
+
+/*
+ * 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/>.
+ */
+
+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_state_model;
+  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;
+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_.plot_priors=0;
diff --git a/tests/optimizers/fs2000_1.mod b/tests/optimizers/fs2000_1.mod
new file mode 100644
index 0000000000000000000000000000000000000000..fe37048359d3731ca32d9bb4e68e33f18f6b89c5
--- /dev/null
+++ b/tests/optimizers/fs2000_1.mod
@@ -0,0 +1,5 @@
+@#include "fs2000.common.inc"
+
+if ~isoctave() && exist('fmincon','file')
+  estimation(mode_compute=1,order=1, datafile='../fs2000/fsdat_simul', nobs=192, mh_replic=0);
+end
diff --git a/tests/optimizers/fs2000_10.mod b/tests/optimizers/fs2000_10.mod
new file mode 100644
index 0000000000000000000000000000000000000000..d46ef9d85f9631fa94fd03a51252849a75a112f4
--- /dev/null
+++ b/tests/optimizers/fs2000_10.mod
@@ -0,0 +1,3 @@
+@#include "fs2000.common.inc"
+
+estimation(mode_compute=10,order=1, datafile='../fs2000/fsdat_simul', nobs=192, mh_replic=0);
diff --git a/tests/optimizers/fs2000_101.mod b/tests/optimizers/fs2000_101.mod
new file mode 100644
index 0000000000000000000000000000000000000000..d301ecd186165a81dba729760d0e664e2ab7ca04
--- /dev/null
+++ b/tests/optimizers/fs2000_101.mod
@@ -0,0 +1,3 @@
+@#include "fs2000.common.inc"
+
+estimation(mode_compute=101,order=1, datafile='../fs2000/fsdat_simul', nobs=192, mh_replic=0);
diff --git a/tests/optimizers/fs2000_102.mod b/tests/optimizers/fs2000_102.mod
new file mode 100644
index 0000000000000000000000000000000000000000..e43dcb254b8ba82cc7348d72b8c87a9c1e85d0dc
--- /dev/null
+++ b/tests/optimizers/fs2000_102.mod
@@ -0,0 +1,5 @@
+@#include "fs2000.common.inc"
+
+if ~isoctave() && exist('simulannealbnd','file')
+   estimation(mode_compute=102,mode_file=fs2000_mode,order=1, datafile='../fs2000/fsdat_simul', nobs=192, mh_replic=0, mh_nblocks=2, mh_jscale=0.8);
+end
diff --git a/tests/optimizers/fs2000_2.mod b/tests/optimizers/fs2000_2.mod
new file mode 100644
index 0000000000000000000000000000000000000000..bfd38c7c491cff9548284dbdf054aa13838c0a3f
--- /dev/null
+++ b/tests/optimizers/fs2000_2.mod
@@ -0,0 +1,3 @@
+@#include "fs2000.common.inc"
+
+estimation(mode_compute=2,order=1, datafile='../fs2000/fsdat_simul', nobs=192, mh_replic=0);
diff --git a/tests/optimizers/fs2000_3.mod b/tests/optimizers/fs2000_3.mod
new file mode 100644
index 0000000000000000000000000000000000000000..5efc98d2a4e87b089c3a0ab7b46a1256733d7111
--- /dev/null
+++ b/tests/optimizers/fs2000_3.mod
@@ -0,0 +1,5 @@
+@#include "fs2000.common.inc"
+
+if exist('fminunc','file')
+  estimation(mode_compute=3,order=1, datafile='../fs2000/fsdat_simul', nobs=192, mh_replic=0);
+end
diff --git a/tests/optimizers/fs2000_4.mod b/tests/optimizers/fs2000_4.mod
new file mode 100644
index 0000000000000000000000000000000000000000..c500afa7fbc7e003c0574900f6fc5abe8628856d
--- /dev/null
+++ b/tests/optimizers/fs2000_4.mod
@@ -0,0 +1,3 @@
+@#include "fs2000.common.inc"
+
+estimation(mode_compute=4,order=1, datafile='../fs2000/fsdat_simul', nobs=192, mh_replic=0);
diff --git a/tests/optimizers/fs2000_4_with_optim.mod b/tests/optimizers/fs2000_4_with_optim.mod
new file mode 100644
index 0000000000000000000000000000000000000000..ecb4254ed8d0cf5636af76cd51ba4d7ca497379c
--- /dev/null
+++ b/tests/optimizers/fs2000_4_with_optim.mod
@@ -0,0 +1,3 @@
+@#include "fs2000.common.inc"
+
+estimation(mode_compute=4,order=1, datafile='../fs2000/fsdat_simul', nobs=192, mh_replic=0,optim=('NumgradEpsilon',1e-6,'NumgradAlgorithm',3,'MaxIter',100,'InitialInverseHessian','eye(9)*.0001'));
\ No newline at end of file
diff --git a/tests/optimizers/fs2000_5.mod b/tests/optimizers/fs2000_5.mod
new file mode 100644
index 0000000000000000000000000000000000000000..16fdd957e23612ccfc5ba6b0670ee438085e12de
--- /dev/null
+++ b/tests/optimizers/fs2000_5.mod
@@ -0,0 +1,3 @@
+@#include "fs2000.common.inc"
+
+estimation(mode_compute=5,order=1, datafile='../fs2000/fsdat_simul', nobs=192, mh_replic=0);
diff --git a/tests/optimizers/fs2000_6.mod b/tests/optimizers/fs2000_6.mod
new file mode 100644
index 0000000000000000000000000000000000000000..7bd0673a71079e33f2e3d2e461cf0d7084036255
--- /dev/null
+++ b/tests/optimizers/fs2000_6.mod
@@ -0,0 +1,3 @@
+@#include "fs2000.common.inc"
+
+estimation(mode_compute=6,order=1, datafile='../fs2000/fsdat_simul', nobs=192, mh_replic=0);
diff --git a/tests/optimizers/fs2000_7.mod b/tests/optimizers/fs2000_7.mod
new file mode 100644
index 0000000000000000000000000000000000000000..3a58b5fa2f210f7055dbe774d514810c2f55c9d4
--- /dev/null
+++ b/tests/optimizers/fs2000_7.mod
@@ -0,0 +1,5 @@
+@#include "fs2000.common.inc"
+
+if exist('fminsearch','file')
+  estimation(mode_compute=7,order=1, datafile='../fs2000/fsdat_simul', nobs=192, mh_replic=0);
+end
diff --git a/tests/optimizers/fs2000_8.mod b/tests/optimizers/fs2000_8.mod
new file mode 100644
index 0000000000000000000000000000000000000000..f7415df12cb43d33f7b21165464d8883d1b2611f
--- /dev/null
+++ b/tests/optimizers/fs2000_8.mod
@@ -0,0 +1,3 @@
+@#include "fs2000.common.inc"
+
+estimation(mode_compute=8,order=1, datafile='../fs2000/fsdat_simul', nobs=192, mh_replic=0);
diff --git a/tests/optimizers/fs2000_8_with_optim.mod b/tests/optimizers/fs2000_8_with_optim.mod
new file mode 100644
index 0000000000000000000000000000000000000000..c166d7047ab56793ddad8a7c25feea785986c68d
--- /dev/null
+++ b/tests/optimizers/fs2000_8_with_optim.mod
@@ -0,0 +1,11 @@
+@#include "fs2000.common.inc"
+
+options_.solve_tolf = 1e-12;
+estimation(mode_compute=8,order=1, datafile='../fs2000/fsdat_simul', nobs=192, mh_replic=0,optim=(
+'MaxIter',5000,
+'TolFun',1e-4,
+'TolX',1e-4,
+'MaxFunEvals',5000,
+'MaxFunEvalFactor',500,
+'InitialSimplexSize',0.05
+));
diff --git a/tests/optimizers/fs2000_9.mod b/tests/optimizers/fs2000_9.mod
new file mode 100644
index 0000000000000000000000000000000000000000..96d75bf96f54df7b099d617e24e74ea3af30fae4
--- /dev/null
+++ b/tests/optimizers/fs2000_9.mod
@@ -0,0 +1,3 @@
+@#include "fs2000.common.inc"
+
+estimation(mode_compute=9,order=1, datafile='../fs2000/fsdat_simul', nobs=192, mh_replic=0);
diff --git a/tests/optimizers/fs2000_w.mod b/tests/optimizers/fs2000_w.mod
new file mode 100644
index 0000000000000000000000000000000000000000..73f6bdc62a2dcfb33e744cb97035071b6310cc7d
--- /dev/null
+++ b/tests/optimizers/fs2000_w.mod
@@ -0,0 +1,3 @@
+@#include "fs2000.common.inc"
+
+estimation(mode_compute=optimizer_function_wrapper,order=1, datafile='../fs2000/fsdat_simul', nobs=192, mh_replic=0);
diff --git a/tests/optimizers/optimizer_function_wrapper.m b/tests/optimizers/optimizer_function_wrapper.m
new file mode 100644
index 0000000000000000000000000000000000000000..a7992bab3e980c18478d6554229aa30d2f11198e
--- /dev/null
+++ b/tests/optimizers/optimizer_function_wrapper.m
@@ -0,0 +1,16 @@
+function [opt_par_values,fval,exitflag]=optimizer_function_wrapper(objective_function_handle,start_par_value,varargin)
+% function [opt_par_values,fval,exitflag]=optimizer_function_wrapper(objective_function_handle,start_par_value,varargin)
+% Demonstrates how to invoke external optimizer for mode_computation
+
+%set options of optimizer
+H0 = 1e-4*eye(length(start_par_value),length(start_par_value));
+nit=1000;
+crit = 1e-7;
+numgrad = 2; 
+epsilon = 1e-6; 
+analytic_grad=[];
+
+%call optimizer
+[fval,opt_par_values,grad,hessian_mat,itct,fcount,exitflag] = ...
+    csminwel1(objective_function_handle, start_par_value, H0, analytic_grad, crit, nit, numgrad, epsilon, varargin{:});
+end
\ No newline at end of file
diff --git a/tests/particle/dsge_base2.mod b/tests/particle/dsge_base2.mod
index 8a847295276305c8305efe0616440185a78c5ebc..a4a56415bc96d70a5c1d23212fe82e928ffca7aa 100644
--- a/tests/particle/dsge_base2.mod
+++ b/tests/particle/dsge_base2.mod
@@ -137,8 +137,8 @@ options_.mode_check.number_of_points = 250;
 //estimation(datafile=risky,order=2,nograph,filter_algorithm=gf,distribution_approximation=montecarlo,number_of_particles=1000,nobs=150,mh_replic=0,mode_compute=4,mode_check);
 
 // GCF
-//estimation(datafile=extreme,order=2,nograph,filter_algorithm=gf,nobs=150,mh_replic=0,mode_compute=4);
-//estimation(datafile=extreme,order=2,nograph,filter_algorithm=gf,nobs=150,mh_replic=0,mode_compute=8,mode_file=dsge_base2_mode,mode_check);
+estimation(datafile=extreme,order=2,nograph,filter_algorithm=gf,nobs=150,mh_replic=0,mode_compute=8);
+estimation(datafile=extreme,order=2,nograph,filter_algorithm=gf,nobs=150,mh_replic=0,mode_compute=4,mode_file=dsge_base2_mode,mode_check);
 
 // GUF
 //estimation(datafile=extreme,order=2,nograph,filter_algorithm=gf,proposal_approximation=unscented,distribution_approximation=unscented,nobs=150,mh_replic=0,mode_compute=4);
@@ -155,15 +155,15 @@ options_.mode_check.number_of_points = 250;
 //estimation(datafile=extreme,nograph,order=2,filter_algorithm=gmf,nobs=150,mh_replic=0,mode_compute=0,mode_file=dsge_base2_mode,mode_check);
 
 // P-MH with SIR
-%options_.mh_posterior_mode_estimation = 1 ;
-%options_.mh_jscale = 1.2e-3 ; 
-options_.mh_nblck = 10 ;
+//options_.mh_posterior_mode_estimation = 1 ;
+//options_.mh_jscale = 1.2e-3 ; 
+//options_.mh_nblck = 10 ;
 //estimation(datafile=extreme,order=2,nobs=150,number_of_particles=50000,mh_replic=0,mode_compute=7);
-options_.posterior_sampling_method = 'RWGMH';
-options_.rwgmh_scale_shock = (1e-5)*[10 10 1 1 10 10 10 1000 10 10] ;
+//options_.posterior_sampling_method = 'RWGMH';
+//options_.rwgmh_scale_shock = (1e-5)*[10 10 1 1 10 10 10 1000 10 10] ;
 //estimation(datafile=extreme,order=2,nobs=150,number_of_particles=1000,mh_replic=10000,mode_compute=8);
 //estimation(datafile=extreme,order=2,nobs=150,number_of_particles=1000,mh_replic=10000,mode_file=dsge_base2_mode,mode_compute=0);
-estimation(datafile=extreme,order=1,mh_replic=5000,mode_compute=0,mode_file=dsge_base2_mode);
+//estimation(datafile=extreme,order=1,mh_replic=5000,mode_compute=0,mode_file=dsge_base2_mode);
 
 //estimation(datafile=extreme,order=2,nobs=150,number_of_particles=50000,mode_file=dsge_base2_mode,mh_replic=60000,mode_compute=7);
 //estimation(datafile=extreme,order=2,nobs=150,number_of_particles=10000,load_mh_file,mh_replic=1,mode_compute=0);
diff --git a/tests/particle/dummy_model.mod b/tests/particle/dummy_model.mod
index 39aa3e34d864bd97d9ebe942b4ec7e53c71c6951..845e0a4b6ac415565c8476d0cf7f3aa5e168d8c9 100644
--- a/tests/particle/dummy_model.mod
+++ b/tests/particle/dummy_model.mod
@@ -44,7 +44,6 @@ varobs x, y;
 //estimation(datafile=mydata,order=1,first_obs=5001,nobs=100,mh_replic=0);
 
 options_.particle.status = 1;
-options_.particle.algorithm = 'sequential_importance_particle_filter';
 options_.particle.initialization = 1;
 options_.particle.number_of_particles = 1000;
 
@@ -58,4 +57,4 @@ d, 0.7912;
 g, 0.2448;
 end;
 
-estimation(datafile=mydata,order=2,first_obs=5001,nobs=100,mh_replic=0,mode_compute=8);
+estimation(datafile=mydata,order=2,first_obs=5001,nobs=100,mh_replic=0,mode_compute=8,filter_algorithm=sis);
diff --git a/tests/particle/linear_model.mod b/tests/particle/linear_model.mod
index c99fe372548dc1588b205d3e68575574e5dfba56..b14e2bc28c7c0bb3245865c8507fd8366e32682b 100644
--- a/tests/particle/linear_model.mod
+++ b/tests/particle/linear_model.mod
@@ -56,7 +56,6 @@ varobs y, z;
 
 
 options_.particle.status = 1;
-options_.particle.algorithm = 'sequential_importance_particle_filter';
 options_.particle.initialization = 1;
 options_.particle.pruning = 0;
 options_.particle.number_of_particles = 20000;
@@ -71,4 +70,4 @@ options_.mode_check_neighbourhood_size = 0.05;
 set_dynare_threads('local_state_space_iteration_2',3);
 
 
-estimation(order=2,nobs=100,datafile=linear_model_data,mh_replic=0);
+estimation(order=2,nobs=100,datafile=linear_model_data,mh_replic=0,filter_algorithm=sis);
diff --git a/tests/particle/noisy_ar1.mod b/tests/particle/noisy_ar1.mod
index 9a3f4a2334fe18ba465bce4a305bbe2cba018b03..aaebcfea2e0912b461d96b168e254a91cfe48c2d 100644
--- a/tests/particle/noisy_ar1.mod
+++ b/tests/particle/noisy_ar1.mod
@@ -38,7 +38,6 @@ particle = 1;
 
 if particle;
 options_.particle.status = 1;
-options_.particle.algorithm = 'sequential_importance_particle_filter';
 options_.particle.initialization = 1;
 options_.particle.pruning = 0;
 options_.particle.number_of_particles = 20000;
@@ -52,7 +51,7 @@ options_.mode_check_neighbourhood_size = 0.05;
 
 set_dynare_threads('local_state_space_iteration_2',3);
 
-estimation(order=2,nobs=100,datafile=linear_model_data,mh_replic=0);
+estimation(order=2,nobs=100,datafile=linear_model_data,mh_replic=0,filter_algorithm=sis);
 
 else;
 
diff --git a/tests/pi2004/ireland.mod b/tests/pi2004/ireland.mod
index ea17baad31120e471c685df0877ed85b8fd840f4..4c6552bdecedd88b916dd13cb9efca22043e1293 100644
--- a/tests/pi2004/ireland.mod
+++ b/tests/pi2004/ireland.mod
@@ -87,4 +87,4 @@ oy (log(eta));
 oc (log(eta));
 end;
 
-estimation(datafile=idata,mode_compute=1,nograph);
\ No newline at end of file
+estimation(datafile=idata,mode_compute=1,nograph,dirname='MYDIR/mysubdir');
\ No newline at end of file
diff --git a/tests/ramst_initval_file_data.m b/tests/ramst_initval_file_data.m
deleted file mode 100644
index 75e6e919a08d2c3a88b89ff3227774f072d06a06..0000000000000000000000000000000000000000
--- a/tests/ramst_initval_file_data.m
+++ /dev/null
@@ -1,3 +0,0 @@
-x = vertcat([ 1; 1.2 ], repmat(1, 200, 1));
-k = repmat(12.7551, 202, 1);
-c = repmat(1.53061, 202, 1);
diff --git a/tests/recursive/ls2003_bayesian_xls.mod b/tests/recursive/ls2003_bayesian_xls.mod
new file mode 100644
index 0000000000000000000000000000000000000000..c0b048a6012951ffe3ed7f73ed65f1af293bb2fb
--- /dev/null
+++ b/tests/recursive/ls2003_bayesian_xls.mod
@@ -0,0 +1,72 @@
+if ~isoctave() && ~matlab_ver_less_than('8.4')
+   websave('data_ca1_xls.xlsx','http://www.dynare.org/Datasets/data_ca1_xls.xlsx')
+else
+   urlwrite('http://www.dynare.org/Datasets/data_ca1_xls.xlsx','data_ca1_xls.xlsx')
+end
+
+var y y_s R pie dq pie_s de A y_obs pie_obs R_obs;
+varexo e_R e_q e_ys e_pies e_A;
+
+parameters psi1 psi2 psi3 rho_R tau alpha rr k rho_q rho_A rho_ys rho_pies;
+
+psi1 = 1.54;
+psi2 = 0.25;
+psi3 = 0.25;
+rho_R = 0.5;
+alpha = 0.3;
+rr = 2.51;
+k = 0.5;
+tau = 0.5;
+rho_q = 0.4;
+rho_A = 0.2;
+rho_ys = 0.9;
+rho_pies = 0.7;
+
+
+model(linear);
+y = y(+1) - (tau +alpha*(2-alpha)*(1-tau))*(R-pie(+1))-alpha*(tau +alpha*(2-alpha)*(1-tau))*dq(+1) + alpha*(2-alpha)*((1-tau)/tau)*(y_s-y_s(+1))-A(+1);
+pie = exp(-rr/400)*pie(+1)+alpha*exp(-rr/400)*dq(+1)-alpha*dq+(k/(tau+alpha*(2-alpha)*(1-tau)))*y+alpha*(2-alpha)*(1-tau)/(tau*(tau+alpha*(2-alpha)*(1-tau)))*y_s;
+pie = de+(1-alpha)*dq+pie_s;
+R = rho_R*R(-1)+(1-rho_R)*(psi1*pie+psi2*(y+alpha*(2-alpha)*((1-tau)/tau)*y_s)+psi3*de)+e_R;
+dq = rho_q*dq(-1)+e_q;
+y_s = rho_ys*y_s(-1)+e_ys;
+pie_s = rho_pies*pie_s(-1)+e_pies;
+A = rho_A*A(-1)+e_A;
+y_obs = y-y(-1)+A;
+pie_obs = 4*pie;
+R_obs = 4*R;
+end;
+
+shocks;
+var e_R = 1.25^2;
+var e_q = 2.5^2;
+var e_A = 1.89;
+var e_ys = 1.89;
+var e_pies = 1.89;
+end;
+
+varobs y_obs R_obs pie_obs dq de;
+
+estimated_params;
+psi1 , gamma_pdf,1.5,0.5;
+psi2 , gamma_pdf,0.25,0.125;
+psi3 , gamma_pdf,0.25,0.125;
+rho_R ,beta_pdf,0.5,0.2;
+alpha ,beta_pdf,0.3,0.1;
+rr ,gamma_pdf,2.5,1;
+k , gamma_pdf,0.5,0.25;
+tau ,gamma_pdf,0.5,0.2;
+rho_q ,beta_pdf,0.4,0.2;
+rho_A ,beta_pdf,0.5,0.2;
+rho_ys ,beta_pdf,0.8,0.1;
+rho_pies,beta_pdf,0.7,0.15;
+stderr e_R,inv_gamma_pdf,1.2533,0.6551;
+stderr e_q,inv_gamma_pdf,2.5066,1.3103;
+stderr e_A,inv_gamma_pdf,1.2533,0.6551;
+stderr e_ys,inv_gamma_pdf,1.2533,0.6551;
+stderr e_pies,inv_gamma_pdf,1.88,0.9827;
+end;
+
+estimation(datafile=data_ca1_xls,first_obs=8,nobs=[76 79],mh_nblocks=1,prefilter=1,mh_jscale=0.5,mh_replic=2000,forecast=8) y_obs R_obs pie_obs dq de;
+
+delete('data_ca1_xls.xlsx')
diff --git a/tests/reporting/runDynareReport.m b/tests/reporting/runDynareReport.m
index 4ce50f40835efc17a711a03eb2e0930403c75ff9..61057946b7509bb31ceb762e7f18c984f3b6df60 100644
--- a/tests/reporting/runDynareReport.m
+++ b/tests/reporting/runDynareReport.m
@@ -156,6 +156,11 @@ rep = rep.addGraph('title', {'World Real Oil Price Index','SUBTITLE'}, ...
                    'xTicks', [1,5,10,15,find(srange(1)==prange),length(prange)], ...
                    'xTickLabels',{startpoint{:},'2008Q1','2009Q2','2010Q3',shaded{:}, endpoint{:}},...
                    'xTickLabelRotation', 0);
+rep = rep.addSeries('data', db_q{'LRPFOOD_BAR_WORLD'}, ...
+                    'graphBar', true, ...
+                    'graphBarColor', 'red', ...
+                    'graphBarFillColor', 'gray', ...
+                    'graphBarWidth', 1);
 db_q = db_q.tex_rename('LRPOIL_WORLD', 'Oil Price');
 rep = rep.addSeries('data', db_q{'LRPOIL_WORLD'}, ...
                     'graphLineColor', 'blue', ...
@@ -175,16 +180,19 @@ rep = rep.addGraph('title', 'World Real Food Price Index', ...
                    'shade', srange, ...
                    'xTicks', [1,5,10,15,find(srange(1)==prange),length(prange)], ...
                    'xTickLabels',{startpoint{:},'2008Q1','2009Q2','2010Q3',shaded{:}, endpoint{:}},...
-                   'xTickLabelRotation', 0);
+                   'xTickLabelRotation', 0, ...
+                   'showLegend', true, ...
+                   'legendAt', [.5,.5]);
+rep = rep.addSeries('data', db_q{'LRPFOOD_BAR_WORLD'}, ...
+                    'graphBar', true, ...
+                    'graphBarColor', 'green', ...
+                    'graphBarFillColor', 'yellow', ...
+                    'graphBarWidth', 1);
 db_q = db_q.tex_rename('LRPFOOD_WORLD', 'Food Price');
 rep = rep.addSeries('data', db_q{'LRPFOOD_WORLD'}, ...
                     'graphLineColor', 'blue', ...
                     'graphLineWidth', 1.5);
 db_q = db_q.tex_rename('LRPFOOD_BAR_WORLD', 'Equilibrium Food Price');
-rep = rep.addSeries('data', db_q{'LRPFOOD_BAR_WORLD'}, ...
-                    'graphLineColor', 'green', ...
-                    'graphLineStyle', 'solid', ...
-                    'graphLineWidth', 1.5);
 rep = rep.addSeries('graphVline', dates('2009q2'), ...
                     'graphLineColor', 'red', ...
                     'graphLineWidth', 1.5);
@@ -249,26 +257,46 @@ rep = rep.addSeries('graphHline', 460, ...
                     'graphLineColor', 'red', ...
                     'graphLineWidth', 1.5);
 
+a=dseries([1:200]', '1984q1');
+b=a;
+c=a;
+d=a;
+b(dates('2012q2'):dates('2015q2'))=b(dates('2012q2'):dates('2015q2'))+2;
+c(dates('2012q2'):dates('2015q2'))=c(dates('2012q2'):dates('2015q2'))+4;
+d(dates('2012q2'):dates('2015q2'))=d(dates('2012q2'):dates('2015q2'))+6;
 
 rep = rep.addGraph('title', 'Equilibrium World Real Food Price', ...
                    'xrange', prange, ...
                    'shade', srange, ...
                    'showLegend', true, ...
                    'xTickLabelRotation', 0);
-rep = rep.addSeries('data', db_q{'LRPFOOD_BAR_WORLD'}, ...
+rep = rep.addSeries('data', a, ...
                     'graphLineColor', 'blue', ...
                     'graphLineWidth', 1.5, ...
                     'graphLegendName', 'baseline', ...
                     'graphMiscTikzAddPlotOptions', 'mark=halfcircle*,color=red');
-rep = rep.addSeries('data', dc_q{'LRPFOOD_BAR_WORLD'}, ...
+rep = rep.addSeries('data', b, ...
                     'graphLineColor', 'blue', ...
                     'graphLineStyle', 'dashed', ...
                     'graphLineWidth', 1.5, ...
                     'graphLegendName', 'control', ...
-                    'graphMiscTikzAddPlotOptions', 'mark=halfcircle*,mark options={rotate=90,scale=3}');
+                    'graphMiscTikzAddPlotOptions', 'mark=halfcircle*,mark options={rotate=90,scale=3}', ...
+                    'graphFanShadeColor', 'red', 'graphFanShadeOpacity', 40);
+rep = rep.addSeries('data', c, ...
+                    'graphLineColor', 'blue', ...
+                    'graphLineStyle', 'dashed', ...
+                    'graphLineWidth', 1.5, ...
+                    'graphLegendName', 'control', ....
+                    'graphFanShadeColor', 'red', 'graphFanShadeOpacity', 30);
+rep = rep.addSeries('data', d, ...
+                    'graphLineColor', 'blue', ...
+                    'graphLineStyle', 'dashed', ...
+                    'graphLineWidth', 1.5, ...
+                    'graphLegendName', 'control', ...
+                    'graphFanShadeColor', 'red', 'graphFanShadeOpacity', 20);
 
 %% Write & Compile Report
 rep.write();
 rep.compile();
 toc
-end
\ No newline at end of file
+end
diff --git a/tests/run_m_script.m b/tests/run_m_script.m
new file mode 100644
index 0000000000000000000000000000000000000000..f40fc242c098cb1420fe5615862f4478c6752b53
--- /dev/null
+++ b/tests/run_m_script.m
@@ -0,0 +1,52 @@
+% Copyright (C) 2015 Dynare Team
+%
+% This file is part of Dynare.
+%
+% Dynare is free software: you can redistribute it and/or modify
+% it under the terms of the GNU General Public License as published by
+% the Free Software Foundation, either version 3 of the License, or
+% (at your option) any later version.
+%
+% Dynare is distributed in the hope that it will be useful,
+% but WITHOUT ANY WARRANTY; without even the implied warranty of
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+% GNU General Public License for more details.
+%
+% You should have received a copy of the GNU General Public License
+% along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+top_test_dir = getenv('TOP_TEST_DIR');
+[mfile, name] = strtok(getenv('FILESTEM'));
+
+[directory, mscript, ext] = fileparts([top_test_dir '/' mfile]);
+cd(directory);
+
+try
+  mscript;
+  testFailed = false;
+catch exception
+  printMakeCheckMatlabErrMsg(strtok(getenv('FILESTEM')), exception);
+  testFailed = true;
+end
+
+cd(top_test_dir);
+name = strtok(getenv('FILESTEM'));
+fid = fopen([name '.m.tls'], 'w');
+if fid < 0
+  wd = pwd
+  filestep = getenv('FILESTEM')
+  error(['ERROR: problem opening file ' name '.m.tls for writing....']);
+end
+if testFailed
+  fprintf(fid,':test-result: FAIL\n');
+  fprintf(fid,':number-tests: 1\n');
+  fprintf(fid,':number-failed-tests: 1\n');
+  fprintf(fid,':list-of-failed-tests: %s\n', [name '.m']);
+else
+  fprintf(fid,':test-result: PASS\n');
+  fprintf(fid,':number-tests: 1\n');
+  fprintf(fid,':number-failed-tests: 0\n');
+  fprintf(fid,':list-of-passed-tests: %s\n', [name '.m']);
+end
+fclose(fid);
+exit;
\ No newline at end of file
diff --git a/tests/run_o_script.m b/tests/run_o_script.m
new file mode 100644
index 0000000000000000000000000000000000000000..317f8cc1830b28badcb4b47fdbcd8bb0963850ae
--- /dev/null
+++ b/tests/run_o_script.m
@@ -0,0 +1,52 @@
+## Copyright (C) 2015 Dynare Team
+##
+## This file is part of Dynare.
+##
+## Dynare is free software: you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation, either version 3 of the License, or
+## (at your option) any later version.
+##
+## Dynare is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+## GNU General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with Dynare.  If not, see <http://www.gnu.org/licenses/>.
+
+top_test_dir = getenv('TOP_TEST_DIR');
+[mfile, name] = strtok(getenv('FILESTEM'));
+
+[directory, mscript, ext] = fileparts([top_test_dir '/' mfile]);
+cd(directory);
+
+try
+  mscript;
+  testFailed = false;
+catch
+  printMakeCheckOctaveErrMsg(getenv('FILESTEM'), lasterror);
+  testFailed = true;
+end_try_catch
+
+cd(top_test_dir);
+name = strtok(getenv('FILESTEM'));
+fid = fopen([name '.o.tls'], 'w+');
+if testFailed
+  fprintf(fid,':test-result: FAIL\n');
+  fprintf(fid,':number-tests: 1\n');
+  fprintf(fid,':number-failed-tests: 1\n');
+  fprintf(fid,':list-of-failed-tests: %s\n', [name '.m']);
+else
+  fprintf(fid,':test-result: PASS\n');
+  fprintf(fid,':number-tests: 1\n');
+  fprintf(fid,':number-failed-tests: 0\n');
+  fprintf(fid,':list-of-passed-tests: %s\n', [name '.m']);
+end
+fclose(fid);
+exit;
+
+
+## Local variables:
+## mode: Octave
+## End:
diff --git a/tests/t_sgu_ex1.mod b/tests/t_sgu_ex1.mod
index 9ac2e6fd93babab7cd443c8444d871b7a94c36c5..87e270666659efa7c0651985a7cca3f020f8c546 100644
--- a/tests/t_sgu_ex1.mod
+++ b/tests/t_sgu_ex1.mod
@@ -28,10 +28,10 @@ stoch_simul(nomoments,nocorr,ar=0,irf=0);
 global dr_
 load objectives/sgu_ex1;
 
-test(oo_.dr.ghx,dr_obj_.ghx,1);
-test(oo_.dr.ghu,dr_obj_.ghu,2);
-test(oo_.dr.ghxx,dr_obj_.ghxx,3);
-test(oo_.dr.ghxu,dr_obj_.ghxu,4);
-test(oo_.dr.ghuu,dr_obj_.ghuu,5);
+fataltest(oo_.dr.ghx,dr_obj_.ghx,1);
+fataltest(oo_.dr.ghu,dr_obj_.ghu,2);
+fataltest(oo_.dr.ghxx,dr_obj_.ghxx,3);
+fataltest(oo_.dr.ghxu,dr_obj_.ghxu,4);
+fataltest(oo_.dr.ghuu,dr_obj_.ghuu,5);
 
-disp('TESTS OK');
\ No newline at end of file
+disp('TESTS OK');
diff --git a/windows/dynare.nsi b/windows/dynare.nsi
index 6f7a45b7a13490facb3c9d998fb07cdc11b068ac..c76bb51755a566407335fd35ed638cc52a38182f 100644
--- a/windows/dynare.nsi
+++ b/windows/dynare.nsi
@@ -58,7 +58,12 @@ Section "Dynare core (preprocessor and M-files)"
 
  SetOutPath $INSTDIR\matlab
  File /r ..\matlab\*.m
- File ..\matlab\dynare_m.exe
+
+ SetOutPath $INSTDIR\matlab\preprocessor32
+ File ..\matlab\preprocessor32\dynare_m.exe
+
+ SetOutPath $INSTDIR\matlab\preprocessor64
+ File ..\matlab\preprocessor64\dynare_m.exe
 
  SetOutPath $INSTDIR\contrib
  File /r ..\contrib\*.m
@@ -83,9 +88,9 @@ SectionEnd
 
 SectionGroup "MEX files for MATLAB"
 
-Section "MEX files for MATLAB 32-bit, version 7.5 to 8.4 (R2007b to R2014b)"
- SetOutPath $INSTDIR\mex\matlab\win32-7.5-8.4
- File ..\mex\matlab\win32-7.5-8.4\*.mexw32
+Section "MEX files for MATLAB 32-bit, version 7.5 to 8.5 (R2007b to R2015a)"
+ SetOutPath $INSTDIR\mex\matlab\win32-7.5-8.5
+ File ..\mex\matlab\win32-7.5-8.5\*.mexw32
 SectionEnd
 
 Section "MEX files for MATLAB 64-bit, version 7.5 to 7.7 (R2007b to R2008b)"
@@ -93,9 +98,9 @@ Section "MEX files for MATLAB 64-bit, version 7.5 to 7.7 (R2007b to R2008b)"
  File ..\mex\matlab\win64-7.5-7.7\*.mexw64
 SectionEnd
 
-Section "MEX files for MATLAB 64-bit, version 7.8 to 8.4 (R2009a to R2014b)"
- SetOutPath $INSTDIR\mex\matlab\win64-7.8-8.4
- File ..\mex\matlab\win64-7.8-8.4\*.mexw64
+Section "MEX files for MATLAB 64-bit, version 7.8 to 8.5 (R2009a to R2015a)"
+ SetOutPath $INSTDIR\mex\matlab\win64-7.8-8.5
+ File ..\mex\matlab\win64-7.8-8.5\*.mexw64
 SectionEnd
 
 SectionGroupEnd